context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using Gtk;
using Gdk;
using Pango;
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Moscrif.IDE.Completion;
namespace Moscrif.IDE.Controls
{
public class ListWidget : Gtk.DrawingArea
{
int margin = 0;
int padding = 4;
int listWidth = 300;
Pango.Layout layout;
ListWindow win;
int selection = 0;
int page = 0;
int rowHeight;
bool buttonPressed;
public event EventHandler SelectionChanged;
string completionString;
public string CompletionString {
get { return completionString; }
set {
if (completionString != value) {
completionString = value;
FilterWords ();
QueueDraw ();
}
}
}
public string DefaultCompletionString {
get;
set;
}
public bool PreviewCompletionString {
get;
set;
}
static bool inCategoryMode;
public bool InCategoryMode {
get { return inCategoryMode; }
set { inCategoryMode = value; this.CalcVisibleRows (); this.UpdatePage (); }
}
public ListWidget (ListWindow win)
{
this.win = win;
this.Events = EventMask.ButtonPressMask | EventMask.ButtonReleaseMask | EventMask.PointerMotionMask;
DefaultCompletionString = "";
layout = new Pango.Layout (this.PangoContext);
layout.Wrap = Pango.WrapMode.Char;
FontDescription des = this.Style.FontDescription.Copy ();
layout.FontDescription = des;
}
public void Reset ()
{
if (win.DataProvider == null) {
selection = -1;
return;
}
selection = win.DataProvider.ItemCount == 0 ? -1 : 0;
page = 0;
AutoSelect = false;
CalcVisibleRows ();
if (SelectionChanged != null)
SelectionChanged (this, EventArgs.Empty);
}
public int SelectionIndex {
get {
if (Selection < 0 || filteredItems.Count <= Selection)
return -1;
return filteredItems[Selection];
}
}
public int Selection {
get { return selection; }
set {
value = Math.Min (filteredItems.Count - 1, Math.Max (0, value));
if (value != selection) {
selection = value;
UpdatePage ();
if (SelectionChanged != null)
SelectionChanged (this, EventArgs.Empty);
this.QueueDraw ();
}
}
}
int GetIndex (bool countCategories, int itemNumber)
{
//if (!InCategoryMode || categories.Count == 1)
// return itemNumber;
int result = -1;
int yPos = 0;
int curItem = 0;
Iterate (false, ref yPos, //delegate (Category category,int ypos) { if (countCategories) curItem++;},
delegate (int item, int ypos) {//Category curCategory,
if (item == itemNumber) {
result = curItem;
return false;
}
curItem++;
return true;
});
return result;
}
int GetItem (bool countCategories, int index)
{
//if (!InCategoryMode || categories.Count == 1)
// return index;
int result = -1;
int curItem = 0;
int yPos = 0;
Iterate (false, ref yPos, //delegate (Category category, int ypos) {if (countCategories) {if (curItem == index) result = category.Items[0];curItem++;} },
delegate ( int item, int ypos) {//Category curCategory,
if (curItem == index) {
result = item;
return false;
}
curItem++;
return true;
});
return result;
}
/*public void MoveToCategory (int relative)
{
int current = CurrentCategory ();
int next = System.Math.Min (categories.Count - 1, System.Math.Max (0, current + relative));
if (next < 0 || next >= categories.Count)
return;
Category newCategory = categories[next];
Selection = newCategory.Items[0];
if (next == 0)
Page = 0;
UpdatePage ();
}*/
/*int CurrentCategory ()
{
for (int i = 0; i < categories.Count; i++) {
if (categories[i].Items.Contains (Selection))
return i;
}
return -1;
}*/
public void MoveCursor (int relative)
{
int newIndex = GetIndex (false, Selection) + relative;
/* if (Math.Abs (relative) == 1) {
if (newIndex < 0)
newIndex = filteredItems.Count - 1;
if (newIndex >= filteredItems.Count)
newIndex = 0;
}*/
int newSelection = GetItem (false, System.Math.Min (filteredItems.Count - 1, System.Math.Max (0, newIndex)));
if (newSelection < 0)
return;
if (Selection == newSelection && relative < 0) {
Page = 0;
} else {
Selection = newSelection;
}
}
public void UpdatePage ()
{
int index = GetIndex (true, Selection);
if (index < page || index >= page + VisibleRows)
page = index - (VisibleRows / 2);
int itemCount = filteredItems.Count;
/*if (InCategoryMode) {
itemCount += categories.Count;
if (categories.Any (cat => cat.CompletionCategory == null))
itemCount--;
}*/
Page = System.Math.Max (0, System.Math.Min (page, itemCount - VisibleRows - 1));
}
bool autoSelect;
public bool AutoSelect {
get { return autoSelect; }
set {
autoSelect = value;
QueueDraw ();
}
}
public bool AutoCompleteEmptyMatch {
get;
set;
}
public bool SelectionEnabled {
get {
return AutoSelect && (AutoCompleteEmptyMatch || !string.IsNullOrEmpty (CompletionString) || !string.IsNullOrEmpty (DefaultCompletionString));
}
}
public int Page {
get { return page; }
set {
if (page != value) {
page = value;
this.QueueDraw ();
}
if (SelectionChanged != null)
SelectionChanged (this, EventArgs.Empty);
}
}
protected override bool OnButtonPressEvent (EventButton e)
{
Selection = GetRowByPosition ((int)e.Y);
buttonPressed = true;
return base.OnButtonPressEvent (e);
}
protected override bool OnButtonReleaseEvent (EventButton e)
{
buttonPressed = false;
return base.OnButtonReleaseEvent (e);
}
protected override void OnRealized ()
{
base.OnRealized ();
this.GdkWindow.Background = this.Style.Base (StateType.Normal);
}
protected override bool OnMotionNotifyEvent (EventMotion e)
{
if (!buttonPressed)
return base.OnMotionNotifyEvent (e);
int winWidth, winHeight;
this.GdkWindow.GetSize (out winWidth, out winHeight);
Selection = GetRowByPosition ((int)e.Y);
return true;
}
protected override bool OnExposeEvent (Gdk.EventExpose args)
{
Gdk.Window window = args.Window;
var alloc = Allocation;
int width = alloc.Width;
int height = alloc.Height;
int lineWidth = width - margin * 2;
int xpos = margin + padding;
int yPos = margin;
if (PreviewCompletionString) {
layout.SetText (string.IsNullOrEmpty (CompletionString) ? MainClass.Languages.Translate("select") : CompletionString);
int wi, he;
layout.GetPixelSize (out wi, out he);
window.DrawRectangle (this.Style.BaseGC (StateType.Insensitive), true, margin, yPos, lineWidth, he + padding);
window.DrawLayout (string.IsNullOrEmpty (CompletionString) ? this.Style.TextGC (StateType.Insensitive) : this.Style.TextGC (StateType.Normal), xpos, yPos, layout);
yPos += rowHeight;
}
if (filteredItems.Count == 0) {
Gdk.GC gc = new Gdk.GC (window);
gc.RgbFgColor = new Gdk.Color (0xff, 0xbc, 0xc1);
window.DrawRectangle (gc, true, 0, yPos, width, height - yPos);
gc.Dispose ();
layout.SetText (MainClass.Languages.Translate("no_suggestions"));
int lWidth, lHeight;
layout.GetPixelSize (out lWidth, out lHeight);
window.DrawLayout (this.Style.TextGC (StateType.Normal), (width - lWidth) / 2, yPos + (height - lHeight - yPos) / 2, layout);
return true;
}
var textGCInsensitive = this.Style.TextGC (StateType.Insensitive);
var textGCNormal = this.Style.TextGC (StateType.Normal);
var fgGCNormal = this.Style.ForegroundGC (StateType.Normal);
Iterate (true, ref yPos, //delegate (Category category, int ypos) {if
//(ypos >= height - margin) return;
// Gdk.Pixbuf icon = MainClass.Tools.GetIconFromStock (category.CompletionCategory.Icon, IconSize.Menu);
//window.DrawPixbuf (fgGCNormal, icon, 0, 0, margin, ypos, icon.Width, icon.Height, Gdk.RgbDither.None, 0, 0);
//layout.SetMarkup ("<span weight='bold'>" + category.CompletionCategory.DisplayText + "</span>");
//window.DrawLayout (textGCInsensitive, icon.Width + 4, ypos, layout);
//layout.SetMarkup ("");
//},
delegate ( int item, int ypos) {//Category curCategory,
if (ypos >= height - margin)
return false;
int itemIndex = filteredItems[item];
//if (InCategoryMode && curCategory != null && curCategory.CompletionCategory != null) {
// xpos = margin + padding + 8;
//} else {
xpos = margin + padding;
//}
string markup = win.DataProvider.HasMarkup (itemIndex) ? (win.DataProvider.GetMarkup (itemIndex) ?? "<null>") : GLib.Markup.EscapeText (win.DataProvider.GetText (itemIndex) ?? "<null>");
string description = win.DataProvider.GetDescription (itemIndex);
if (string.IsNullOrEmpty (description)) {
layout.SetMarkup (markup);
} else {
if (item == selection) {
layout.SetMarkup (markup + " " + description );
} else {
layout.SetMarkup (markup + " <span foreground=\"darkgray\">" + description + "</span>");
}
}
int mw, mh;
layout.GetPixelSize (out mw, out mh);
if (mw > listWidth) {
WidthRequest = listWidth = mw;
win.WidthRequest = win.Allocation.Width + mw - width;
win.QueueResize ();
}
string text = win.DataProvider.GetText (itemIndex);
if ((!SelectionEnabled || item != selection) && !string.IsNullOrEmpty (text)) {
int[] matchIndices = Match (CompletionString, text);
if (matchIndices != null) {
Pango.AttrList attrList = layout.Attributes ?? new Pango.AttrList ();
for (int newSelection = 0; newSelection < matchIndices.Length; newSelection++) {
int idx = matchIndices[newSelection];
Pango.AttrForeground fg = new Pango.AttrForeground (0, 0, ushort.MaxValue);
fg.StartIndex = (uint)idx;
fg.EndIndex = (uint)(idx + 1);
attrList.Insert (fg);
}
layout.Attributes = attrList;
}
}
Gdk.Pixbuf icon = win.DataProvider.GetIcon (itemIndex);
int iconHeight, iconWidth;
if (icon != null) {
iconWidth = icon.Width;
iconHeight = icon.Height;
} else if (!Gtk.Icon.SizeLookup (Gtk.IconSize.Menu, out iconWidth, out iconHeight)) {
iconHeight = iconWidth = 24;
}
int wi, he, typos, iypos;
layout.GetPixelSize (out wi, out he);
typos = he < rowHeight ? ypos + (rowHeight - he) / 2 : ypos;
iypos = iconHeight < rowHeight ? ypos + (rowHeight - iconHeight) / 2 : ypos;
if (item == selection) {
if (SelectionEnabled) {
window.DrawRectangle (this.Style.BaseGC (StateType.Selected), true, margin, ypos, lineWidth, he + padding);
window.DrawLayout (this.Style.TextGC (StateType.Selected), xpos + iconWidth + 2, typos, layout);
} else {
window.DrawRectangle (this.Style.DarkGC (StateType.Prelight), false, margin, ypos, lineWidth - 1, he + padding - 1);
window.DrawLayout (textGCNormal, xpos + iconWidth + 2, typos, layout);
}
} else
window.DrawLayout (textGCNormal, xpos + iconWidth + 2, typos, layout);
if (icon != null)
window.DrawPixbuf (fgGCNormal, icon, 0, 0, xpos, iypos, iconWidth, iconHeight, Gdk.RgbDither.None, 0, 0);
layout.SetMarkup ("");
if (layout.Attributes != null) {
layout.Attributes.Dispose ();
layout.Attributes = null;
}
return true;
});
/*
int n = 0;
while (ypos < winHeight - margin && (page + n) < filteredItems.Count) {
bool hasMarkup = win.DataProvider.HasMarkup (filteredItems[page + n]);
if (hasMarkup) {
layout.SetMarkup (win.DataProvider.GetMarkup (filteredItems[page + n]) ?? "<null>");
} else {
layout.SetText (win.DataProvider.GetText (filteredItems[page + n]) ?? "<null>");
}
string text = win.DataProvider.GetText (filteredItems[page + n]);
if ((!SelectionEnabled || page + n != selection) && !string.IsNullOrEmpty (text)) {
int[] matchIndices = Match (CompletionString, text);
if (matchIndices != null) {
Pango.AttrList attrList = layout.Attributes ?? new Pango.AttrList ();
for (int newSelection = 0; newSelection < matchIndices.Length; newSelection++) {
int idx = matchIndices[newSelection];
Pango.AttrForeground fg = new Pango.AttrForeground (0, 0, ushort.MaxValue);
fg.StartIndex = (uint)idx;
fg.EndIndex = (uint)(idx + 1);
attrList.Insert (fg);
}
layout.Attributes = attrList;
}
}
Gdk.Pixbuf icon = win.DataProvider.GetIcon (filteredItems[page + n]);
int iconHeight, iconWidth;
if (icon != null) {
iconWidth = icon.Width;
iconHeight = icon.Height;
} else if (!Gtk.Icon.SizeLookup (Gtk.IconSize.Menu, out iconWidth, out iconHeight)) {
iconHeight = iconWidth = 24;
}
int wi, he, typos, iypos;
layout.GetPixelSize (out wi, out he);
typos = he < rowHeight ? ypos + (rowHeight - he) / 2 : ypos;
iypos = iconHeight < rowHeight ? ypos + (rowHeight - iconHeight) / 2 : ypos;
if (page + n == selection) {
if (SelectionEnabled) {
window.DrawRectangle (this.Style.BaseGC (StateType.Selected), true, margin, ypos, lineWidth, he + padding);
window.DrawLayout (this.Style.TextGC (StateType.Selected), xpos + iconWidth + 2, typos, layout);
} else {
window.DrawRectangle (this.Style.DarkGC (StateType.Prelight), false, margin, ypos, lineWidth - 1, he + padding - 1);
window.DrawLayout (this.Style.TextGC (StateType.Normal), xpos + iconWidth + 2, typos, layout);
}
} else
window.DrawLayout (this.Style.TextGC (StateType.Normal), xpos + iconWidth + 2, typos, layout);
if (icon != null)
window.DrawPixbuf (this.Style.ForegroundGC (StateType.Normal), icon, 0, 0, xpos, iypos, iconWidth, iconHeight, Gdk.RgbDither.None, 0, 0);
ypos += rowHeight;
n++;
if (hasMarkup)
layout.SetMarkup (string.Empty);
if (layout.Attributes != null) {
layout.Attributes.Dispose ();
layout.Attributes = null;
}
}
*/
return true;
}
public int TextOffset {
get {
int iconWidth, iconHeight;
if (!Gtk.Icon.SizeLookup (Gtk.IconSize.Menu, out iconWidth, out iconHeight))
iconHeight = iconWidth = 24;
return iconWidth + margin + padding + 2;
}
}
internal List<int> filteredItems = new List<int> ();
internal static bool Match2 (string filterText, string text){
return text.StartsWith(filterText);
/*if (text.IndexOf(filterText) > -1) return true;
else return false;*/
}
internal static int[] Match (string filterText, string text)
{
//Console.WriteLine("filterText->"+filterText);
//Console.WriteLine("text->"+text);
if (string.IsNullOrEmpty (filterText))
return new int[0];
if (string.IsNullOrEmpty (text))
return null;
List<int> matchIndices = new List<int> ();
bool wasMatch = false;
int itemIndex = 0;
for (int newSelection = 0; newSelection < text.Length && itemIndex < filterText.Length; newSelection++) {
char ch1 = char.ToUpper (text[newSelection]);
char ch2 = char.ToUpper (filterText[itemIndex]);
bool ch1IsUpper = char.IsUpper (text[newSelection]);
bool ch2IsUpper = char.IsUpper (filterText[itemIndex]);
if (ch1 == ch2 && !(!ch1IsUpper && ch2IsUpper)) {
itemIndex++;
matchIndices.Add (newSelection);
wasMatch = true;
continue;
} else {
for (; newSelection < text.Length; newSelection++) {
if (char.IsUpper (text[newSelection]) /*&& newSelection + 1 < text.Length && (!char.IsUpper (text[newSelection + 1]) || !char.IsLetter (text[newSelection + 1]))*/ && ch2 == text[newSelection]) {
matchIndices.Add (newSelection);
itemIndex++;
wasMatch = true;
break;
}
}
if (wasMatch)
continue;
}
if ((char.IsPunctuation (ch2) || char.IsWhiteSpace (ch2))) {
wasMatch = false;
break;
}
if (wasMatch) {
wasMatch = false;
bool match = false;
for (; newSelection < text.Length; newSelection++) {
if (ch2 == text[newSelection]) {
newSelection--;
match = true;
break;
}
}
if (match)
continue;
}
break;
}
return itemIndex == filterText.Length ? matchIndices.ToArray () : null;
}
public static bool Matches (string filterText, string text)
{
/*int[] intpole =Match (filterText, text);
if(intpole != null){
foreach (int i in intpole)
Console.WriteLine( "Match->"+ i);
}*/
return Match2(filterText, text);
//return Match (filterText, text) != null;
}
/* Category GetCategory (CompletionCategory completionCategory)
{
foreach (Category cat in categories) {
if (cat.CompletionCategory == completionCategory)
return cat;
}
Category result = new Category ();
result.CompletionCategory = completionCategory;
if (completionCategory == null) {
categories.Add (result);
} else {
categories.Insert (0, result);
}
return result;
}
*/
public void FilterWords ()
{
filteredItems.Clear ();
//categories.Clear ();
for (int newSelection = 0; newSelection < win.DataProvider.ItemCount; newSelection++) {
if (string.IsNullOrEmpty (CompletionString) || Matches (CompletionString, win.DataProvider.GetText (newSelection))) {
//CompletionCategory completionCategory = win.DataProvider.GetCompletionCategory (newSelection);
//GetCategory (completionCategory).Items.Add (filteredItems.Count);
filteredItems.Add (newSelection);
}
}
/*categories.Sort (delegate (Category left, Category right) {
return right.CompletionCategory != null ? right.CompletionCategory.CompareTo (left.CompletionCategory) : -1;
});*/
CalcVisibleRows ();
UpdatePage ();
OnWordsFiltered (EventArgs.Empty);
}
protected virtual void OnWordsFiltered (EventArgs e)
{
EventHandler handler = this.WordsFiltered;
if (handler != null)
handler (this, e);
}
public event EventHandler WordsFiltered;
int GetRowByPosition (int ypos)
{
return GetItem (true, page + (ypos - margin) / rowHeight - (PreviewCompletionString ? 1 : 0));
}
public Gdk.Rectangle GetRowArea (int row)
{
if (this.GdkWindow == null)
return Gdk.Rectangle.Zero;
row -= page;
int winWidth, winHeight;
this.GdkWindow.GetSize (out winWidth, out winHeight);
return new Gdk.Rectangle (margin, margin + rowHeight * row, winWidth, rowHeight);
}
public int VisibleRows {
get {
int rowWidth;
layout.GetPixelSize (out rowWidth, out rowHeight);
rowHeight += padding;
return Allocation.Height / rowHeight;
}
}
protected override void OnSizeAllocated (Gdk.Rectangle allocation)
{
base.OnSizeAllocated (allocation);
UpdatePage ();
}
/* protected override void OnSizeRequested (ref Requisition requisition)
{
base.OnSizeRequested (ref requisition);
requisition.Height += requisition.Height % rowHeight;
}
*/
void CalcVisibleRows ()
{
int winHeight = 200;
int lvWidth, lvHeight;
this.GetSizeRequest (out lvWidth, out lvHeight);
int rowWidth;
layout.GetPixelSize (out rowWidth, out rowHeight);
rowHeight += padding;
int requestedVisibleRows = (winHeight + padding - margin * 2) / rowHeight;
int viewableCats =0;// InCategoryMode ? categories.Count: 0;
//if (InCategoryMode && categories.Any (cat => cat.CompletionCategory == null))
// viewableCats--;
int newHeight = (rowHeight * Math.Max (1, Math.Min (requestedVisibleRows, filteredItems.Count + viewableCats))) + margin * 2;
if (PreviewCompletionString) {
newHeight += rowHeight;
}
if (lvWidth != listWidth || lvHeight != newHeight)
this.SetSizeRequest (listWidth, newHeight);
}
const int spacing = 2;
// delegate void CategoryAction (Category category, int yPos);
delegate bool ItemAction (int item, int yPos);//Category curCategory,
void Iterate (bool startAtPage, ref int ypos, ItemAction action)//CategoryAction catAction,
{
int curItem = 0;
/*if (InCategoryMode) {
foreach (Category category in this.categories) {
if (category.CompletionCategory != null) {
if (!startAtPage || curItem >= page) {
if (catAction != null)
catAction (category, ypos);
ypos += rowHeight;
}
curItem++;
}
bool result = IterateItems (category, startAtPage,ref ypos, ref curItem, action);
if (!result)
break;
}
} else {*/
int startItem = 0;
if (startAtPage)
startItem = curItem = page;
if (action != null) {
for (int item = startItem; item < filteredItems.Count; item++) {
bool result = action ( item, ypos);//null,
if (!result)
break;
ypos += rowHeight;
curItem++;
}
} else {
int itemCount = (filteredItems.Count - startItem);
ypos += rowHeight * itemCount;
curItem += itemCount;
}
//}
}
/*bool IterateItems ( bool startAtPage, ref int ypos, ref int curItem, ItemAction action)//Category category,
{
foreach (int item in category.Items) {
if (!startAtPage || curItem >= page) {
if (action != null) {
bool result = action (category, item, ypos);
if (!result)
return false;
}
ypos += rowHeight;
}
curItem++;
}
return true;
}*/
}
}
| |
//----------------------------------------------//
// Gamelogic Grids //
// http://www.gamelogic.co.za //
// Copyright (c) 2013 Gamelogic (Pty) Ltd //
//----------------------------------------------//
using System;
using System.Collections.Generic;
using System.Linq;
namespace Gamelogic.Grids
{
/**
This class provide generic functions for common grid operations, such as finding a
shortest path or conneced shapes.
@copyright Gamelogic.
@author Herman Tulleken
@since 1.0
@ingroup Utilities
*/
public static partial class Algorithms
{
#region Graph Algorithms
public static bool IsConnected<TCell, TPoint>(
IGrid<TCell, TPoint> grid,
IEnumerable<TPoint> collection,
Func<TPoint, TPoint, bool> isNeighborsConnected)
where TPoint : IGridPoint<TPoint>
{
//What if collection is empty?
var openSet = new HashSet<TPoint>(new PointComparer<TPoint>());
var closedSet = new HashSet<TPoint>(new PointComparer<TPoint>());
openSet.Add(collection.First());
while (!openSet.IsEmpty())
{
var current = openSet.First();
openSet.Remove(current);
closedSet.Add(current);
//Adds all connected neighbors that
//are in the grid and in the collection
var connectedNeighbors = from neighbor in grid.GetNeighbors(current)
where !closedSet.Contains(neighbor)
&& isNeighborsConnected(current, neighbor)
&& collection.Contains(neighbor)
select neighbor;
openSet.AddRange(connectedNeighbors);
}
return collection.All(closedSet.Contains);
}
public static bool IsConnected<TCell, TPoint>(
IGrid<TCell, TPoint> grid,
TPoint point1,
TPoint point2,
Func<TPoint, TPoint, bool> isNeighborsConnected)
where TPoint : IGridPoint<TPoint>
{
var openSet = new HashSet<TPoint>(new PointComparer<TPoint>()) { point1 };
var closedSet = new HashSet<TPoint>(new PointComparer<TPoint>());
while (!openSet.IsEmpty())
{
var current = openSet.First();
if (current.Equals(point2))
{
return true;
}
openSet.Remove(current);
closedSet.Add(current);
var connectedNeighbors =
from neighbor in grid.GetNeighbors(current)
where !closedSet.Contains(neighbor) && isNeighborsConnected(current, neighbor)
select neighbor;
openSet.AddRange(connectedNeighbors);
}
return false;
}
public static HashSet<TPoint> GetConnectedSet<TCell, TPoint>(
IGrid<TCell, TPoint> grid,
TPoint point,
Func<TPoint, TPoint, bool> isNeighborsConnected)
where TPoint : IGridPoint<TPoint>
{
var openSet = new HashSet<TPoint>(new PointComparer<TPoint>()) { point };
var closedSet = new HashSet<TPoint>(new PointComparer<TPoint>());
while (!openSet.IsEmpty())
{
var current = openSet.First();
openSet.Remove(current);
closedSet.Add(current);
var connectedNeighbors =
from neighbor in grid.GetNeighbors(current)
where !closedSet.Contains(neighbor) && isNeighborsConnected(current, neighbor)
select neighbor;
openSet.AddRange(connectedNeighbors);
}
return closedSet;
}
/**
Find the shortest path between a start and goal node.
This method uses the distance function as the cost
heuristic, and it is assumed that all cells in the
grid are accessible.
\param HeuristicCostEstimate A function that returns
an heuristic cost of reaching one node from another.
@returns The list of nodes on the path in order. If no
path is possible, null is returned.
*/
public static IEnumerable<TPoint> AStar<TCell, TPoint>(
IGrid<TCell, TPoint> grid,
TPoint start,
TPoint goal)
where TPoint : IGridPoint<TPoint>
{
return AStar(grid, start, goal, (p1, p2) => p1.DistanceFrom(p2), x => true);
}
/**
Find the shortest path between a start and goal node.
The distance between nodes are used as the actual cost
between nodes.
\param HeuristicCostEstimate A function that returns
an heuristic cost of reaching one node from another.
The heuristic cost estimate must be monotonic.
@returns The list of nodes on the path in order. If no
path is possible, null is returned.
*/
public static IEnumerable<TPoint> AStar<TCell, TPoint>(
IGrid<TCell, TPoint> grid,
TPoint start,
TPoint goal,
Func<TPoint, TPoint, float> heuristicCostEstimate,
Func<TCell, bool> isAccessible)
where TPoint : IGridPoint<TPoint>
{
return AStar(
grid,
start,
goal,
heuristicCostEstimate,
isAccessible,
(p, q) => p.DistanceFrom(q));
}
/// <summary>
/// @author Adam Romney
/// Added this override so we can use the TPoint (PointyHexPoint) to look up byte data in a dictionary
/// </summary>
/// <returns>The star.</returns>
/// <param name="grid">Grid.</param>
/// <param name="start">Start.</param>
/// <param name="goal">Goal.</param>
/// <param name="heuristicCostEstimate">Heuristic cost estimate.</param>
/// <param name="isAccessible">Is accessible.</param>
/// <typeparam name="TCell">The 1st type parameter.</typeparam>
/// <typeparam name="TPoint">The 2nd type parameter.</typeparam>
public static IEnumerable<TPoint> AStarPoint<TCell, TPoint>(
IGrid<TCell, TPoint> grid,
TPoint start,
TPoint goal,
Func<TPoint, TPoint, float> heuristicCostEstimate,
Func<TPoint, bool> isAccessible)
where TPoint : IGridPoint<TPoint>
{
return AStarPoint(
grid,
start,
goal,
heuristicCostEstimate,
isAccessible,
(p, q) => p.DistanceFrom(q));
}
/**
Find the shortest path between a start and goal node.
\param heuristicCostEstimate A function that returns
an heuristic cost of reaching one node from another.
The heuristic cost estimate must be monotonic.
\param cost The actual cost of reaching one node from
another.
@returns The list of nodes on the path in order. If no
path is possible, null is returned.
@since 1.7
*/
public static IEnumerable<TPoint> AStar<TCell, TPoint>(
IGrid<TCell, TPoint> grid,
TPoint start,
TPoint goal,
Func<TPoint, TPoint, float> heuristicCostEstimate,
Func<TCell, bool> isAccessible,
Func<TPoint, TPoint, float> cost)
where TPoint : IGridPoint<TPoint>
{
var closedSet = new PointList<TPoint>();
// The set of tentative nodes to be evaluated
var openSet = new PointList<TPoint> { start };
// The map of navigated nodes.
var cameFrom = new Dictionary<TPoint, TPoint>(new PointComparer<TPoint>());
// Cost from start along best known path.
var gScore = new Dictionary<TPoint, float>(new PointComparer<TPoint>());
gScore[start] = 0;
// Estimated total cost from start to goal through y.
var fScore = new Dictionary<TPoint, float>(new PointComparer<TPoint>());
fScore[start] = gScore[start] + heuristicCostEstimate(start, goal);
while (!openSet.IsEmpty())
{
var current = FindNodeWithLowestScore(openSet, fScore);
if (current.Equals(goal))
{
return ReconstructPath(cameFrom, goal);
}
openSet.Remove(current);
closedSet.Add(current);
var currentNodeNeighbors = grid.GetNeighbors(current);
var accessibleNeighbors = from neighbor in currentNodeNeighbors
where isAccessible(grid[neighbor])
select neighbor;
foreach (var neighbor in accessibleNeighbors)
{
var tentativeGScore = gScore[current] + cost(current, neighbor);
if (closedSet.Contains(neighbor))
{
if (tentativeGScore >= gScore[neighbor])
{
continue;
}
}
if (!openSet.Contains(neighbor) || tentativeGScore < gScore[neighbor])
{
cameFrom[neighbor] = current;
gScore[neighbor] = tentativeGScore;
fScore[neighbor] = gScore[neighbor] + heuristicCostEstimate(neighbor, goal);
if (!openSet.Contains(neighbor))
{
openSet.Add(neighbor);
}
}
}
}
return null;
}
/**
@Author Adam Romney
Override to allow use the TPoint (PointyHexPoint) to look up byte data in a dictionary
Find the shortest path between a start and goal node.
\param heuristicCostEstimate A function that returns
an heuristic cost of reaching one node from another.
The heuristic cost estimate must be monotonic.
\param cost The actual cost of reaching one node from
another.
@returns The list of nodes on the path in order. If no
path is possible, null is returned.
@since 1.7
*/
public static IEnumerable<TPoint> AStarPoint<TCell, TPoint>(
IGrid<TCell, TPoint> grid,
TPoint start,
TPoint goal,
Func<TPoint, TPoint, float> heuristicCostEstimate,
Func<TPoint, bool> isAccessible,
Func<TPoint, TPoint, float> cost)
where TPoint : IGridPoint<TPoint>
{
var closedSet = new PointList<TPoint>();
// The set of tentative nodes to be evaluated
var openSet = new PointList<TPoint> { start };
// The map of navigated nodes.
var cameFrom = new Dictionary<TPoint, TPoint>(new PointComparer<TPoint>());
// Cost from start along best known path.
var gScore = new Dictionary<TPoint, float>(new PointComparer<TPoint>());
gScore[start] = 0;
// Estimated total cost from start to goal through y.
var fScore = new Dictionary<TPoint, float>(new PointComparer<TPoint>());
fScore[start] = gScore[start] + heuristicCostEstimate(start, goal);
while (!openSet.IsEmpty())
{
var current = FindNodeWithLowestScore(openSet, fScore);
if (current.Equals(goal))
{
return ReconstructPath(cameFrom, goal);
}
openSet.Remove(current);
closedSet.Add(current);
var currentNodeNeighbors = grid.GetNeighbors(current);
var accessibleNeighbors = from neighbor in currentNodeNeighbors
where isAccessible(neighbor)
select neighbor;
foreach (var neighbor in accessibleNeighbors)
{
var tentativeGScore = gScore[current] + cost(current, neighbor);
if (closedSet.Contains(neighbor))
{
if (tentativeGScore >= gScore[neighbor])
{
continue;
}
}
if (!openSet.Contains(neighbor) || tentativeGScore < gScore[neighbor])
{
cameFrom[neighbor] = current;
gScore[neighbor] = tentativeGScore;
fScore[neighbor] = gScore[neighbor] + heuristicCostEstimate(neighbor, goal);
if (!openSet.Contains(neighbor))
{
openSet.Add(neighbor);
}
}
}
}
return null;
}
#endregion
#region Lines
/**
Returns a list containing lines connected to the given points. A line is a list of points.
Only returns correct results for square or hex grids.
\param IsNeighborsConnected a functions that returns true or false, depending on whether
two points can be considered connected when they are neighbors. For example, if you want
rays of points that refer to cells of the same color, you can pass in a functions that
compares the colours of cells.
@code
private bool IsSameColour(point1, point2)
{
return grid[point1].Color == grid[point2].Color;
}
private SomeMethod()
{
...
var rays = GetConnectedRays<ColourCell, PointyHexPoint, PointyHexNeighborIndex>(
grid, point, IsSameColour);
...
}
@endcode
You can of course also use a lambda expression, like this:
@code
//The following code returns all lines that radiate from the given point,
GetConnectedRays<ColourCell, PointyHexPoint, PointyHexNeighborIndex>(
grid, point, (x, y) => grid[x].Color == grid[y].Color);
@endcode
*/
public static IEnumerable<IEnumerable<TPoint>> GetConnectedRays<TCell, TPoint>(
AbstractUniformGrid<TCell, TPoint> grid,
TPoint point,
Func<TPoint, TPoint, bool> isNeighborsConnected)
where TPoint : IVectorPoint<TPoint>, IGridPoint<TPoint>
{
var lines = new List<IEnumerable<TPoint>>();
foreach (var direction in grid.GetNeighborDirections())
{
var line = new PointList<TPoint>();
var edge = point;
while (grid.Contains(edge) && isNeighborsConnected(point, edge))
{
line.Add(edge);
edge = edge.MoveBy(direction);
}
if (line.Count > 1)
{
lines.Add(line);
}
}
return lines;
}
/**
Gets the longest of the rays connected to this cell.
@see GetConnectedRays
*/
public static IEnumerable<TPoint> GetLongestConnectedRay<TCell, TPoint>(
AbstractUniformGrid<TCell, TPoint> grid,
TPoint point,
Func<TPoint, TPoint, bool> isNeighborsConnected)
where TPoint : IVectorPoint<TPoint>, IGridPoint<TPoint>
{
var rays = GetConnectedRays(grid, point, isNeighborsConnected);
return GetBiggestShape(rays);
}
/**
Gets the longest line of connected points that contains this point.
@see GetConnectedRays
*/
public static IEnumerable<IEnumerable<TPoint>> GetConnectedLines<TCell, TPoint, TBasePoint>(
IEvenGrid<TCell, TPoint, TBasePoint> grid,
TPoint point,
Func<TPoint, TPoint, bool> isNeighborsConnected)
where TPoint : ISplicedVectorPoint<TPoint, TBasePoint>, IGridPoint<TPoint>
where TBasePoint : IVectorPoint<TBasePoint>, IGridPoint<TBasePoint>
{
var lines = new List<IEnumerable<TPoint>>();
foreach (var direction in grid.GetPrincipleNeighborDirections())
{
var line = new PointList<TPoint>();
var edge = point;
//go forwards
while (grid.Contains(edge) && isNeighborsConnected(point, edge))
{
edge = edge.MoveBy(direction);
}
var oppositeDirection = direction.Negate();
//TPoint oppositeNeighbor = point.MoveBy(direction.Negate());
edge = edge.MoveBy(oppositeDirection);
//go backwards
while (grid.Contains(edge) && isNeighborsConnected(point, edge))
{
line.Add(edge);
edge = edge.MoveBy(oppositeDirection);
}
if (line.Count > 1)
{
lines.Add(line);
}
}
return lines;
}
/**
*/
public static IEnumerable<TPoint> GetLongestConnected<TCell, TPoint, TBasePoint>(
IEvenGrid<TCell, TPoint, TBasePoint> grid,
TPoint point,
Func<TPoint, TPoint, bool> isNeighborsConnected)
where TPoint : ISplicedVectorPoint<TPoint, TBasePoint>, IGridPoint<TPoint>
where TBasePoint : IVectorPoint<TBasePoint>, IGridPoint<TBasePoint>
{
var lines = GetConnectedLines(grid, point, isNeighborsConnected);
return GetBiggestShape(lines);
}
#endregion
#region Shapes (Collections of points)
public static IEnumerable<TPoint> GetBiggestShape<TPoint>(
IEnumerable<IEnumerable<TPoint>> shapes)
where TPoint : IGridPoint<TPoint>
{
return shapes.MaxBy(x => x.Count());
}
public static bool Contains<TPoint>(IEnumerable<TPoint> bigShape, IEnumerable<TPoint> smallShape)
where TPoint : IGridPoint<TPoint>
{
return smallShape.All(bigShape.Contains);
}
public static bool IsEquivalent<TPoint>(IEnumerable<TPoint> shape1, IEnumerable<TPoint> shape2)
where TPoint : IGridPoint<TPoint>
{
if (ReferenceEquals(shape1, shape2))
{
return true;
}
return Contains(shape1, shape2) && Contains(shape2, shape1);
}
public static IEnumerable<TPoint> TransformShape<TPoint>(
IEnumerable<TPoint> shape,
Func<TPoint, TPoint> pointTransformation)
where TPoint : IGridPoint<TPoint>
{
return from point in shape
select pointTransformation(point);
}
public static bool IsEquivalentUnderTranslation<TPoint>(
IEnumerable<TPoint> shape1,
IEnumerable<TPoint> shape2,
Func<IEnumerable<TPoint>, IEnumerable<TPoint>> toCanonicalPosition)
where TPoint : IGridPoint<TPoint>
{
return IsEquivalent(
toCanonicalPosition(shape1),
toCanonicalPosition(shape2));
}
public static bool IsEquivalentUnderTransformsAndTranslation<TPoint>(
IEnumerable<TPoint> shape1,
IEnumerable<TPoint> shape2,
IEnumerable<Func<TPoint, TPoint>> pointTransformations,
Func<IEnumerable<TPoint>, IEnumerable<TPoint>> toCanonicalPosition)
where TPoint : IGridPoint<TPoint>
{
var cannicalShape1 = toCanonicalPosition(shape1);
var cannicalShape2 = toCanonicalPosition(shape2);
if (IsEquivalent<TPoint>(cannicalShape1, cannicalShape2))
{
return true;
}
foreach (var PointTransformation in pointTransformations)
{
cannicalShape2 = toCanonicalPosition(TransformShape<TPoint>(shape2, PointTransformation));
if (IsEquivalent<TPoint>(cannicalShape1, cannicalShape2))
{
return true;
}
}
return false;
}
#endregion
#region FilterType
public static TResultGrid
AggregateNeighborhood<TCell, TPoint, TResultGrid, TResultCell>(
IGrid<TCell, TPoint> grid,
Func<TPoint, IEnumerable<TPoint>, TResultCell> aggregator)
where TPoint : IGridPoint<TPoint>
where TResultGrid : IGrid<TResultCell, TPoint>
{
var newGrid = (TResultGrid)grid.CloneStructure<TResultCell>();
foreach (var point in newGrid)
{
newGrid[point] = aggregator(point, newGrid.GetNeighbors(point));
}
return newGrid;
}
public static void
AggregateNeighborhood<TCell, TPoint>(
IGrid<TCell, TPoint> grid,
Func<TPoint, IEnumerable<TPoint>, TCell> aggregator)
where TPoint : IGridPoint<TPoint>
{
var newGrid = grid.CloneStructure<TCell>();
foreach (var point in newGrid)
{
newGrid[point] = aggregator(point, grid.GetNeighbors(point));
}
foreach (var point in grid)
{
grid[point] = newGrid[point];
}
}
#endregion
#region Helpers
private static TPoint FindNodeWithLowestScore<TPoint>(IEnumerable<TPoint> list, IDictionary<TPoint, float> score)
{
return list.Aggregate((item, minObject) => score[item] < score[minObject] ? item : minObject);
}
//TODO remove construcctions of list!
private static IList<TPoint> ReconstructPath<TPoint>(
Dictionary<TPoint, TPoint> cameFrom,
TPoint currentNode)
where TPoint : IGridPoint<TPoint>
{
IList<TPoint> path = new PointList<TPoint>();
ReconstructPath(cameFrom, currentNode, path);
return path;
}
private static void ReconstructPath<TPoint>(Dictionary<TPoint, TPoint> cameFrom, TPoint currentNode, IList<TPoint> path)
where TPoint : IGridPoint<TPoint>
{
if (cameFrom.ContainsKey(currentNode))
{
ReconstructPath(cameFrom, cameFrom[currentNode], path);
}
path.Add(currentNode);
return;
}
#endregion
}
}
| |
namespace Ocelot.UnitTests.DownstreamRouteFinder
{
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.DownstreamRouteFinder;
using Ocelot.DownstreamRouteFinder.Finder;
using Ocelot.LoadBalancer.LoadBalancers;
using Responses;
using Shouldly;
using System.Collections.Generic;
using System.Net.Http;
using TestStack.BDDfy;
using Xunit;
public class DownstreamRouteCreatorTests
{
private readonly DownstreamRouteCreator _creator;
private readonly QoSOptions _qoSOptions;
private readonly HttpHandlerOptions _handlerOptions;
private readonly LoadBalancerOptions _loadBalancerOptions;
private Response<DownstreamRoute> _result;
private string _upstreamHost;
private string _upstreamUrlPath;
private string _upstreamHttpMethod;
private IInternalConfiguration _configuration;
private Mock<IQoSOptionsCreator> _qosOptionsCreator;
private Response<DownstreamRoute> _resultTwo;
private string _upstreamQuery;
public DownstreamRouteCreatorTests()
{
_qosOptionsCreator = new Mock<IQoSOptionsCreator>();
_qoSOptions = new QoSOptionsBuilder().Build();
_handlerOptions = new HttpHandlerOptionsBuilder().Build();
_loadBalancerOptions = new LoadBalancerOptionsBuilder().WithType(nameof(NoLoadBalancer)).Build();
_qosOptionsCreator
.Setup(x => x.Create(It.IsAny<QoSOptions>(), It.IsAny<string>(), It.IsAny<List<string>>()))
.Returns(_qoSOptions);
_creator = new DownstreamRouteCreator(_qosOptionsCreator.Object);
}
[Fact]
public void should_create_downstream_route()
{
var configuration = new InternalConfiguration(null, "doesnt matter", null, "doesnt matter", _loadBalancerOptions, "http", _qoSOptions, _handlerOptions);
this.Given(_ => GivenTheConfiguration(configuration))
.When(_ => WhenICreate())
.Then(_ => ThenTheDownstreamRouteIsCreated())
.BDDfy();
}
[Fact]
public void should_create_downstream_route_with_rate_limit_options()
{
var rateLimitOptions = new RateLimitOptionsBuilder()
.WithEnableRateLimiting(true)
.WithClientIdHeader("test")
.Build();
var downstreamReRoute = new DownstreamReRouteBuilder()
.WithServiceName("auth")
.WithRateLimitOptions(rateLimitOptions)
.Build();
var reRoute = new ReRouteBuilder()
.WithDownstreamReRoute(downstreamReRoute)
.Build();
var reRoutes = new List<ReRoute> { reRoute };
var configuration = new InternalConfiguration(reRoutes, "doesnt matter", null, "doesnt matter", _loadBalancerOptions, "http", _qoSOptions, _handlerOptions);
this.Given(_ => GivenTheConfiguration(configuration))
.When(_ => WhenICreate())
.Then(_ => ThenTheDownstreamRouteIsCreated())
.And(_ => WithRateLimitOptions(rateLimitOptions))
.BDDfy();
}
[Fact]
public void should_cache_downstream_route()
{
var configuration = new InternalConfiguration(null, "doesnt matter", null, "doesnt matter", _loadBalancerOptions, "http", _qoSOptions, _handlerOptions);
this.Given(_ => GivenTheConfiguration(configuration, "/geoffisthebest/"))
.When(_ => WhenICreate())
.And(_ => GivenTheConfiguration(configuration, "/geoffisthebest/"))
.When(_ => WhenICreateAgain())
.Then(_ => ThenTheDownstreamRoutesAreTheSameReference())
.BDDfy();
}
[Fact]
public void should_not_cache_downstream_route()
{
var configuration = new InternalConfiguration(null, "doesnt matter", null, "doesnt matter", _loadBalancerOptions, "http", _qoSOptions, _handlerOptions);
this.Given(_ => GivenTheConfiguration(configuration, "/geoffistheworst/"))
.When(_ => WhenICreate())
.And(_ => GivenTheConfiguration(configuration, "/geoffisthebest/"))
.When(_ => WhenICreateAgain())
.Then(_ => ThenTheDownstreamRoutesAreTheNotSameReference())
.BDDfy();
}
[Fact]
public void should_create_downstream_route_with_no_path()
{
var upstreamUrlPath = "/auth/";
var configuration = new InternalConfiguration(null, "doesnt matter", null, "doesnt matter", _loadBalancerOptions, "http", _qoSOptions, _handlerOptions);
this.Given(_ => GivenTheConfiguration(configuration, upstreamUrlPath))
.When(_ => WhenICreate())
.Then(_ => ThenTheDownstreamPathIsForwardSlash())
.BDDfy();
}
[Fact]
public void should_create_downstream_route_with_only_first_segment_no_traling_slash()
{
var upstreamUrlPath = "/auth";
var configuration = new InternalConfiguration(null, "doesnt matter", null, "doesnt matter", _loadBalancerOptions, "http", _qoSOptions, _handlerOptions);
this.Given(_ => GivenTheConfiguration(configuration, upstreamUrlPath))
.When(_ => WhenICreate())
.Then(_ => ThenTheDownstreamPathIsForwardSlash())
.BDDfy();
}
[Fact]
public void should_create_downstream_route_with_segments_no_traling_slash()
{
var upstreamUrlPath = "/auth/test";
var configuration = new InternalConfiguration(null, "doesnt matter", null, "doesnt matter", _loadBalancerOptions, "http", _qoSOptions, _handlerOptions);
this.Given(_ => GivenTheConfiguration(configuration, upstreamUrlPath))
.When(_ => WhenICreate())
.Then(_ => ThenThePathDoesNotHaveTrailingSlash())
.BDDfy();
}
[Fact]
public void should_create_downstream_route_and_remove_query_string()
{
var upstreamUrlPath = "/auth/test?test=1&best=2";
var configuration = new InternalConfiguration(null, "doesnt matter", null, "doesnt matter", _loadBalancerOptions, "http", _qoSOptions, _handlerOptions);
this.Given(_ => GivenTheConfiguration(configuration, upstreamUrlPath))
.When(_ => WhenICreate())
.Then(_ => ThenTheQueryStringIsRemoved())
.BDDfy();
}
[Fact]
public void should_create_downstream_route_for_sticky_sessions()
{
var loadBalancerOptions = new LoadBalancerOptionsBuilder().WithType(nameof(CookieStickySessions)).WithKey("boom").WithExpiryInMs(1).Build();
var configuration = new InternalConfiguration(null, "doesnt matter", null, "doesnt matter", loadBalancerOptions, "http", _qoSOptions, _handlerOptions);
this.Given(_ => GivenTheConfiguration(configuration))
.When(_ => WhenICreate())
.Then(_ => ThenTheStickySessionLoadBalancerIsUsed(loadBalancerOptions))
.BDDfy();
}
[Fact]
public void should_create_downstream_route_with_qos()
{
var qoSOptions = new QoSOptionsBuilder()
.WithExceptionsAllowedBeforeBreaking(1)
.WithTimeoutValue(1)
.Build();
var configuration = new InternalConfiguration(null, "doesnt matter", null, "doesnt matter", _loadBalancerOptions, "http", qoSOptions, _handlerOptions);
this.Given(_ => GivenTheConfiguration(configuration))
.And(_ => GivenTheQosCreatorReturns(qoSOptions))
.When(_ => WhenICreate())
.Then(_ => ThenTheQosOptionsAreSet(qoSOptions))
.BDDfy();
}
[Fact]
public void should_create_downstream_route_with_handler_options()
{
var configuration = new InternalConfiguration(null, "doesnt matter", null, "doesnt matter", _loadBalancerOptions, "http", _qoSOptions, _handlerOptions);
this.Given(_ => GivenTheConfiguration(configuration))
.When(_ => WhenICreate())
.Then(_ => ThenTheHandlerOptionsAreSet())
.BDDfy();
}
private void GivenTheQosCreatorReturns(QoSOptions options)
{
_qosOptionsCreator
.Setup(x => x.Create(It.IsAny<QoSOptions>(), It.IsAny<string>(), It.IsAny<List<string>>()))
.Returns(options);
}
private void WithRateLimitOptions(RateLimitOptions expected)
{
_result.Data.ReRoute.DownstreamReRoute[0].EnableEndpointEndpointRateLimiting.ShouldBeTrue();
_result.Data.ReRoute.DownstreamReRoute[0].RateLimitOptions.EnableRateLimiting.ShouldBe(expected.EnableRateLimiting);
_result.Data.ReRoute.DownstreamReRoute[0].RateLimitOptions.ClientIdHeader.ShouldBe(expected.ClientIdHeader);
}
private void ThenTheDownstreamRouteIsCreated()
{
_result.Data.ReRoute.DownstreamReRoute[0].DownstreamPathTemplate.Value.ShouldBe("/test");
_result.Data.ReRoute.UpstreamHttpMethod[0].ShouldBe(HttpMethod.Get);
_result.Data.ReRoute.DownstreamReRoute[0].ServiceName.ShouldBe("auth");
_result.Data.ReRoute.DownstreamReRoute[0].LoadBalancerKey.ShouldBe("/auth/test|GET");
_result.Data.ReRoute.DownstreamReRoute[0].UseServiceDiscovery.ShouldBeTrue();
_result.Data.ReRoute.DownstreamReRoute[0].HttpHandlerOptions.ShouldNotBeNull();
_result.Data.ReRoute.DownstreamReRoute[0].QosOptions.ShouldNotBeNull();
_result.Data.ReRoute.DownstreamReRoute[0].DownstreamScheme.ShouldBe("http");
_result.Data.ReRoute.DownstreamReRoute[0].LoadBalancerOptions.Type.ShouldBe(nameof(NoLoadBalancer));
_result.Data.ReRoute.DownstreamReRoute[0].HttpHandlerOptions.ShouldBe(_handlerOptions);
_result.Data.ReRoute.DownstreamReRoute[0].QosOptions.ShouldBe(_qoSOptions);
_result.Data.ReRoute.UpstreamTemplatePattern.ShouldNotBeNull();
_result.Data.ReRoute.DownstreamReRoute[0].UpstreamPathTemplate.ShouldNotBeNull();
}
private void ThenTheDownstreamPathIsForwardSlash()
{
_result.Data.ReRoute.DownstreamReRoute[0].DownstreamPathTemplate.Value.ShouldBe("/");
_result.Data.ReRoute.DownstreamReRoute[0].ServiceName.ShouldBe("auth");
_result.Data.ReRoute.DownstreamReRoute[0].LoadBalancerKey.ShouldBe("/auth/|GET");
}
private void ThenThePathDoesNotHaveTrailingSlash()
{
_result.Data.ReRoute.DownstreamReRoute[0].DownstreamPathTemplate.Value.ShouldBe("/test");
_result.Data.ReRoute.DownstreamReRoute[0].ServiceName.ShouldBe("auth");
_result.Data.ReRoute.DownstreamReRoute[0].LoadBalancerKey.ShouldBe("/auth/test|GET");
}
private void ThenTheQueryStringIsRemoved()
{
_result.Data.ReRoute.DownstreamReRoute[0].DownstreamPathTemplate.Value.ShouldBe("/test");
_result.Data.ReRoute.DownstreamReRoute[0].ServiceName.ShouldBe("auth");
_result.Data.ReRoute.DownstreamReRoute[0].LoadBalancerKey.ShouldBe("/auth/test|GET");
}
private void ThenTheStickySessionLoadBalancerIsUsed(LoadBalancerOptions expected)
{
_result.Data.ReRoute.DownstreamReRoute[0].LoadBalancerKey.ShouldBe($"{nameof(CookieStickySessions)}:boom");
_result.Data.ReRoute.DownstreamReRoute[0].LoadBalancerOptions.Type.ShouldBe(nameof(CookieStickySessions));
_result.Data.ReRoute.DownstreamReRoute[0].LoadBalancerOptions.ShouldBe(expected);
}
private void ThenTheQosOptionsAreSet(QoSOptions expected)
{
_result.Data.ReRoute.DownstreamReRoute[0].QosOptions.ShouldBe(expected);
_result.Data.ReRoute.DownstreamReRoute[0].QosOptions.UseQos.ShouldBeTrue();
_qosOptionsCreator
.Verify(x => x.Create(expected, _upstreamUrlPath, It.IsAny<List<string>>()), Times.Once);
}
private void GivenTheConfiguration(IInternalConfiguration config)
{
_upstreamHost = "doesnt matter";
_upstreamUrlPath = "/auth/test";
_upstreamHttpMethod = "GET";
_configuration = config;
}
private void GivenTheConfiguration(IInternalConfiguration config, string upstreamUrlPath)
{
_upstreamHost = "doesnt matter";
_upstreamUrlPath = upstreamUrlPath;
_upstreamHttpMethod = "GET";
_configuration = config;
}
private void ThenTheHandlerOptionsAreSet()
{
_result.Data.ReRoute.DownstreamReRoute[0].HttpHandlerOptions.ShouldBe(_handlerOptions);
}
private void WhenICreate()
{
_result = _creator.Get(_upstreamUrlPath, _upstreamQuery, _upstreamHttpMethod, _configuration, _upstreamHost);
}
private void WhenICreateAgain()
{
_resultTwo = _creator.Get(_upstreamUrlPath, _upstreamQuery, _upstreamHttpMethod, _configuration, _upstreamHost);
}
private void ThenTheDownstreamRoutesAreTheSameReference()
{
_result.ShouldBe(_resultTwo);
}
private void ThenTheDownstreamRoutesAreTheNotSameReference()
{
_result.ShouldNotBe(_resultTwo);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using EnvDTE;
using Microsoft.VisualStudio.ExtensionsExplorer;
using NuGet.VisualStudio;
namespace NuGet.Dialog.Providers
{
/// <summary>
/// IVsExtensionsProvider implementation responsible for gathering
/// a list of packages from a package feed which will be shown in the Add NuGet dialog.
/// </summary>
internal class OnlineProvider : PackagesProviderBase
{
private readonly IPackageRepositoryFactory _packageRepositoryFactory;
private readonly IPackageSourceProvider _packageSourceProvider;
private readonly IVsPackageManagerFactory _packageManagerFactory;
private readonly Project _project;
public OnlineProvider(
Project project,
IPackageRepository localRepository,
ResourceDictionary resources,
IPackageRepositoryFactory packageRepositoryFactory,
IPackageSourceProvider packageSourceProvider,
IVsPackageManagerFactory packageManagerFactory,
ProviderServices providerServices,
IProgressProvider progressProvider,
ISolutionManager solutionManager) :
base(localRepository, resources, providerServices, progressProvider, solutionManager)
{
_packageRepositoryFactory = packageRepositoryFactory;
_packageSourceProvider = packageSourceProvider;
_packageManagerFactory = packageManagerFactory;
_project = project;
}
public override string Name
{
get
{
return Resources.Dialog_OnlineProvider;
}
}
public override float SortOrder
{
get
{
return 2.0f;
}
}
public override bool RefreshOnNodeSelection
{
get
{
// only refresh if the current node doesn't have any extensions
return (SelectedNode == null || SelectedNode.Extensions.Count == 0);
}
}
public override IEnumerable<string> SupportedFrameworks
{
get
{
string targetFramework = _project.GetTargetFramework();
return targetFramework != null ? new[] { targetFramework } : new string[0];
}
}
public virtual string OperationName
{
get { return RepositoryOperationNames.Install; }
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design",
"CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "We want to suppress all errors to show an empty node.")]
protected override void FillRootNodes()
{
var packageSources = _packageSourceProvider.GetEnabledPackageSourcesWithAggregate();
// create one tree node per package source
foreach (var source in packageSources)
{
PackagesTreeNodeBase node;
try
{
var repository = new LazyRepository(_packageRepositoryFactory, source);
node = CreateTreeNodeForPackageSource(source, repository);
}
catch (Exception exception)
{
// exception occurs if the Source value is invalid. In which case, adds an empty tree node in place.
node = new EmptyTreeNode(this, source.Name, RootNode);
ExceptionHelper.WriteToActivityLog(exception);
}
RootNode.Nodes.Add(node);
}
if (RootNode.Nodes.Count >= 2)
{
// Bug #628 : Do not set aggregate source as default because it
// will slow down the dialog when querying two or more sources.
RootNode.Nodes[1].IsSelected = true;
}
}
protected virtual PackagesTreeNodeBase CreateTreeNodeForPackageSource(PackageSource source, IPackageRepository repository)
{
return new OnlineTreeNode(this, source.Name, RootNode, repository);
}
protected internal virtual IVsPackageManager GetActivePackageManager()
{
if (SelectedNode == null)
{
return null;
}
else if (SelectedNode.IsSearchResultsNode)
{
PackagesSearchNode searchNode = (PackagesSearchNode)SelectedNode;
SimpleTreeNode baseNode = (SimpleTreeNode)searchNode.BaseNode;
return _packageManagerFactory.CreatePackageManager(baseNode.Repository, useFallbackForDependencies: true);
}
else
{
var selectedNode = SelectedNode as SimpleTreeNode;
return (selectedNode != null) ? _packageManagerFactory.CreatePackageManager(selectedNode.Repository, useFallbackForDependencies: true) : null;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design",
"CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "We don't want one failed project to affect the other projects.")]
protected override bool ExecuteCore(PackageItem item)
{
IVsPackageManager activePackageManager = GetActivePackageManager();
Debug.Assert(activePackageManager != null);
using (activePackageManager.SourceRepository.StartOperation(OperationName, item.Id, item.Version))
{
ShowProgressWindow();
IList<PackageOperation> operations;
bool acceptLicense = ShowLicenseAgreement(
item.PackageIdentity,
activePackageManager,
_project.GetTargetFrameworkName(),
out operations);
if (!acceptLicense)
{
return false;
}
ExecuteCommandOnProject(_project, item, activePackageManager, operations);
return true;
}
}
protected void ExecuteCommandOnProject(Project activeProject, PackageItem item, IVsPackageManager activePackageManager, IList<PackageOperation> operations)
{
IProjectManager projectManager = null;
try
{
projectManager = activePackageManager.GetProjectManager(activeProject);
RegisterPackageOperationEvents(activePackageManager, projectManager);
ExecuteCommand(projectManager, item, activePackageManager, operations);
}
finally
{
if (projectManager != null)
{
UnregisterPackageOperationEvents(activePackageManager, projectManager);
}
}
}
protected virtual void ExecuteCommand(IProjectManager projectManager, PackageItem item, IVsPackageManager activePackageManager, IList<PackageOperation> operations)
{
activePackageManager.InstallPackage(projectManager, item.PackageIdentity, operations, ignoreDependencies: false, allowPrereleaseVersions: IncludePrerelease, logger: this);
}
public override bool CanExecute(PackageItem item)
{
var latestPackageLookup = LocalRepository as ILatestPackageLookup;
if (latestPackageLookup != null)
{
// in this case, we mark this package as installed if the current project has
// any lower-or-equal-versioned package with the same id installed.
SemanticVersion installedVersion;
return !latestPackageLookup.TryFindLatestPackageById(item.Id, out installedVersion) ||
installedVersion < item.PackageIdentity.Version;
}
else
{
// Only enable command on a Package in the Online provider if it is not installed yet
return !LocalRepository.Exists(item.PackageIdentity);
}
}
public override IVsExtension CreateExtension(IPackage package)
{
return new PackageItem(this, package)
{
CommandName = Resources.Dialog_InstallButton,
TargetFramework = _project.GetTargetFrameworkName()
};
}
protected override PackagesProviderBase GetSearchProvider()
{
var baseProvider = base.GetSearchProvider();
return new OnlineSearchProvider(baseProvider);
}
public override string NoItemsMessage
{
get
{
return Resources.Dialog_OnlineProviderNoItem;
}
}
public override string ProgressWindowTitle
{
get
{
return Dialog.Resources.Dialog_InstallProgress;
}
}
protected override string GetProgressMessage(IPackage package)
{
return Resources.Dialog_InstallProgress + package.ToString();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace SMSServer.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Schema;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Design;
using System.Xml;
using System.Globalization;
using System.ComponentModel;
namespace XmlNotepad {
/// <summary>
/// This interface is used to provide extensible popup modal dialog for editing a particular
/// type of value in the XML document. (e.g. color picker).
/// </summary>
public interface IXmlBuilder {
/// <summary>
/// Return a caption for the button that launches your dialog.
/// </summary>
string Caption { get; }
/// <summary>
/// Provides the ISite objects which is how you get services from the hosting application.
/// </summary>
/// <param name="site"></param>
ISite Site { get; set; }
/// <summary>
/// Provides the IntellisenseProvider that created this object.
/// </summary>
IIntellisenseProvider Owner { get; set; }
/// <summary>
/// This method launches a custom builder (e.g. color picker, etc)
/// with an initial value and produces a resulting value.
/// </summary>
/// <param name="owner">The parent window that is calling us</param>
/// <param name="type">The type associated with the value being edited</param>
/// <param name="input">The current value being edited</param>
/// <param name="output">The result of the builder</param>
/// <returns>Returns false if the user cancelled the operation</returns>
bool EditValue(IWin32Window owner, XmlSchemaType type, string input, out string output);
}
/// <summary>
/// This interface is used to provide other types of editors besides the default TextBox for
/// inline editing of particular types of values in the XML document. For example, DateTimePicker.
/// </summary>
public interface IXmlEditor {
/// <summary>
/// Provides the ISite objects which is how you get services from the hosting application.
/// </summary>
/// <param name="site"></param>
ISite Site { get; set; }
/// <summary>
/// Provides the IntellisenseProvider that created this object.
/// </summary>
IIntellisenseProvider Owner { get; set; }
/// <summary>
/// This property provides the XmlSchemaType for the editor
/// </summary>
XmlSchemaType SchemaType { get; set; }
/// <summary>
/// Return the editor you want to use to edit your values.
/// </summary>
Control Editor { get; }
/// <summary>
/// The setter is called just before editing to pass in the current value from the
/// XmlDocument. At the end of editing, the getter is called to pull the new value
/// back out of the editor for storing in the XmlDocument.
/// </summary>
string XmlValue { get; set;}
}
/// <summary>
/// This is a custom builder for editing color values using the ColorDialog.
/// You can specify this builder using the following annotation in your schema:
/// vs:builder="XmlNotepad.ColorBuilder"
/// where xmlns:vs="http://schemas.microsoft.com/Visual-Studio-Intellisense"
/// </summary>
class ColorBuilder : IXmlBuilder {
ColorDialog cd = new ColorDialog();
ISite site;
IIntellisenseProvider owner;
public IIntellisenseProvider Owner {
get { return this.owner; }
set { this.owner = value; }
}
public ISite Site {
get { return this.site; }
set { this.site = value; }
}
public string Caption { get { return SR.ColorPickerLabel; } }
public bool EditValue(IWin32Window owner, XmlSchemaType type, string input, out string output) {
output = input;
ColorConverter cc = new ColorConverter();
Color c = Color.Black;
try {
c = (Color)cc.ConvertFromString(input);
} catch {
}
cd.Color = c;
cd.AnyColor = true;
if (cd.ShowDialog(owner) == DialogResult.OK) {
output = cc.ConvertToString(cd.Color);
return true;
} else {
return false;
}
}
}
/// <summary>
/// This is a custom builder for editing anyUri types via Open File Dialog.
/// You can specify this builder using the following annotation in your schema:
/// vs:builder="XmlNotepad.UriBuilder"
/// where xmlns:vs="http://schemas.microsoft.com/Visual-Studio-Intellisense"
/// </summary>
class UriBuilder : IXmlBuilder {
OpenFileDialog fd = new OpenFileDialog();
ISite site;
public UriBuilder() {
fd.Filter = "All files (*.*)|*.*";
}
IIntellisenseProvider owner;
public IIntellisenseProvider Owner {
get { return this.owner; }
set { this.owner = value; }
}
public ISite Site {
get { return this.site; }
set { this.site = value; }
}
public string Caption { get { return SR.UriBrowseLabel; } }
public bool EditValue(IWin32Window owner, XmlSchemaType type, string input, out string output) {
output = input;
if (!string.IsNullOrEmpty(input)) {
fd.FileName = GetAbsolute(input);
}
if (fd.ShowDialog(owner) == DialogResult.OK) {
output = GetRelative(fd.FileName);
return true;
} else {
return false;
}
}
string GetRelative(string s) {
Uri baseUri = this.owner.BaseUri;
if (baseUri != null) {
try {
Uri uri = new Uri(s, UriKind.RelativeOrAbsolute);
return baseUri.MakeRelative(uri);
} catch (UriFormatException) {
return s;
}
}
return s;
}
string GetAbsolute(string s) {
Uri baseUri = this.owner.BaseUri;
if (baseUri != null) {
try {
Uri uri = new Uri(s, UriKind.RelativeOrAbsolute);
Uri resolved = new Uri(baseUri, uri);
if (resolved.IsFile) return resolved.LocalPath;
return resolved.AbsoluteUri;
} catch (UriFormatException) {
return s;
}
}
return s;
}
}
/// <summary>
/// This is a custom editor for editing date/time values using the DateTimePicker.
/// This editor is provided by default when you use xs:time, xs:dateTime or xs:date
/// simple types in your schema, or you can specify this editor using the following
/// annotation in your schema: vs:editor="XmlNotepad.DateTimeEditor"
/// where xmlns:vs="http://schemas.microsoft.com/Visual-Studio-Intellisense"
/// </summary>
public class DateTimeEditor : IXmlEditor, IDisposable {
XmlSchemaType type;
DateTimePicker picker = new DateTimePicker();
string format = "yyyy-MM-dd";
ISite site;
IIntellisenseProvider owner;
public IIntellisenseProvider Owner {
get { return this.owner; }
set { this.owner = value; }
}
public ISite Site {
get { return this.site; }
set { this.site = value; }
}
/// <summary>
/// This property provides the XmlSchemaType for the editor
/// </summary>
public XmlSchemaType SchemaType {
get { return this.type; }
set {
this.type = value;
if (type != null) {
DateTimeFormatInfo dtInfo = DateTimeFormatInfo.CurrentInfo;
switch (type.TypeCode){
case XmlTypeCode.DateTime:
format = SR.DateTimeFormat;
picker.Format = DateTimePickerFormat.Custom;
picker.CustomFormat = dtInfo.ShortDatePattern + " " + dtInfo.LongTimePattern;
picker.ShowUpDown = false;
break;
case XmlTypeCode.Time:
picker.Format = DateTimePickerFormat.Time;
format = SR.TimeFormat;
picker.ShowUpDown = true;
break;
default:
picker.Format = DateTimePickerFormat.Short;
format = SR.DateFormat;
picker.ShowUpDown = false;
break;
}
// Todo: set picker.MinDate and MaxDate based on the XmlSchemaFacet information, if any.
}
}
}
public Control Editor {
get { return picker; }
}
public string XmlValue {
get {
return XmlConvert.ToString(picker.Value, format);
}
set {
try {
picker.Text = value;
} catch {
// ignore exceptions.
}
}
}
~DateTimeEditor() {
Dispose(false);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing){
if (picker != null) {
picker.Dispose();
picker = null;
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.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 Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RouteFiltersOperations operations.
/// </summary>
internal partial class RouteFiltersOperations : IServiceOperations<NetworkClient>, IRouteFiltersOperations
{
/// <summary>
/// Initializes a new instance of the RouteFiltersOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RouteFiltersOperations(NetworkClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkClient
/// </summary>
public NetworkClient Client { get; private set; }
/// <summary>
/// Deletes the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='expand'>
/// Expands referenced express route bgp peering resources.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteFilter>> GetWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteFilter>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilter>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a route filter in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the create or update route filter operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<RouteFilter>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<RouteFilter> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates a route filter in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the update route filter operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<RouteFilter>> UpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<RouteFilter> _response = await BeginUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all route filters in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteFilter>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteFilter>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilter>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all route filters in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteFilter>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/routeFilters").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteFilter>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilter>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a route filter in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the create or update route filter operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteFilter>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (routeFilterParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("routeFilterParameters", routeFilterParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(routeFilterParameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(routeFilterParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteFilter>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilter>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilter>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updates a route filter in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the update route filter operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteFilter>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (routeFilterParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("routeFilterParameters", routeFilterParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(routeFilterParameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(routeFilterParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteFilter>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilter>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all route filters in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteFilter>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroupNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteFilter>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilter>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all route filters in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteFilter>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteFilter>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilter>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
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.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Xml;
using Microsoft.Test.ModuleCore;
namespace CoreXml.Test.XLinq
{
public partial class XNodeReaderFunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
//[TestCase(Name = "ReadToDescendant", Desc = "ReadToDescendant")]
public partial class TCReadToDescendant : BridgeHelpers
{
#region XMLSTR
private string _xmlStr = @"<?xml version='1.0'?>
<root><!--Comment-->
<elem><!-- Comment -->
<child1 att='1'><?pi target?>
<child2 xmlns='child2'>
<child3/>
blahblahblah<![CDATA[ blah ]]>
<child4/>
</child2>
<?pi target1?>
</child1>
</elem>
<elem att='1'>
<child1 att='1'>
<child2 xmlns='child2'>
<child3/>
blahblahblah
<child4/>
</child2>
<?pi target1?>
</child1>
</elem>
<elem xmlns='elem'>
<child1 att='1'>
<child2 xmlns='child2'>
<child3/>
blahblahblah2
<child4/>
</child2>
</child1>
</elem>
<elem xmlns='elem' att='1'>
<child1 att='1'>
<child2 xmlns='child2'>
<child3/>
blahblahblah2
<child4/>
</child2>
</child1>
</elem>
<e:elem xmlns:e='elem2'>
<e:child1 att='1'>
<e:child2 xmlns='child2'>
<e:child3/>
blahblahblah2
<e:child4/>
</e:child2>
</e:child1>
</e:elem>
<e:elem xmlns:e='elem2' att='1'>
<e:child1 att='1'>
<e:child2 xmlns='child2'>
<e:child3/>
blahblahblah2
<e:child4/>
</e:child2>
</e:child1>
</e:elem>
</root>";
#endregion
//[Variation("Simple positive test", Priority = 0, Params = new object[] { "NNS" })]
//[Variation("Simple positive test", Priority = 0, Params = new object[] { "DNS" })]
//[Variation("Simple positive test", Priority = 0, Params = new object[] { "NS" })]
public void v()
{
string type = Variation.Params[0].ToString();
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "root");
switch (type)
{
case "NNS":
DataReader.ReadToDescendant("elem");
if (DataReader.HasAttributes)
{
TestLog.WriteLine("Positioned on wrong element");
TestLog.WriteIgnore(DataReader.ReadInnerXml() + "\n");
throw new TestException(TestResult.Failed, "");
}
while (DataReader.Read()) ;
DataReader.Dispose();
return;
case "DNS":
DataReader.ReadToDescendant("elem", "elem");
if (DataReader.HasAttributes)
{
if (DataReader.GetAttribute("xmlns") == null)
{
TestLog.WriteLine("Positioned on wrong element, not on DNS");
throw new TestException(TestResult.Failed, "");
}
}
while (DataReader.Read()) ;
DataReader.Dispose();
return;
case "NS":
DataReader.ReadToDescendant("e:elem");
if (DataReader.HasAttributes)
{
if (DataReader.GetAttribute("xmlns:e") == null)
{
TestLog.WriteLine("Positioned on wrong element, not on NS");
throw new TestException(TestResult.Failed, "");
}
}
while (DataReader.Read()) ;
DataReader.Dispose();
return;
default:
throw new TestFailedException("Error in Test type");
}
}
//[Variation("Read on a deep tree at least more than 4K boundary", Priority = 2)]
public void v2()
{
ManagedNodeWriter mnw = new ManagedNodeWriter();
mnw.PutPattern("X");
int count = 0;
do
{
mnw.PutPattern("E/");
count++;
}
while (mnw.GetNodes().Length < 4096);
mnw.PutText("<a/>");
mnw.Finish();
XmlReader DataReader = GetReader(new StringReader(mnw.GetNodes()));
PositionOnElement(DataReader, "ELEMENT_1");
DataReader.ReadToDescendant("a");
TestLog.Compare(DataReader.Depth, count, "Depth is not correct");
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Nodetype is not correct");
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Read on descendant with same names", Priority = 1, Params = new object[] { "NNS" })]
//[Variation("Read on descendant with same names", Priority = 1, Params = new object[] { "DNS" })]
//[Variation("Read on descendant with same names", Priority = 1, Params = new object[] { "NS" })]
public void v3()
{
string type = Variation.Params[0].ToString();
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "root");
// Doing a sequential read.
switch (type)
{
case "NNS":
DataReader.ReadToDescendant("elem");
int depth = DataReader.Depth;
if (DataReader.HasAttributes)
{
TestLog.WriteLine("Positioned on wrong element");
throw new TestException(TestResult.Failed, "");
}
TestLog.Compare(DataReader.ReadToDescendant("elem"), false, "There are no more descendants");
TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type");
while (DataReader.Read()) ;
DataReader.Dispose();
return;
case "DNS":
DataReader.ReadToDescendant("elem", "elem");
if (DataReader.HasAttributes)
{
if (DataReader.GetAttribute("xmlns") == null)
{
TestLog.WriteLine("Positioned on wrong element, not on DNS");
throw new TestException(TestResult.Failed, "");
}
}
TestLog.Compare(DataReader.ReadToDescendant("elem", "elem"), false, "There are no more descendants");
TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type");
while (DataReader.Read()) ;
DataReader.Dispose();
return;
case "NS":
DataReader.ReadToDescendant("e:elem");
if (DataReader.HasAttributes)
{
if (DataReader.GetAttribute("xmlns:e") == null)
{
TestLog.WriteLine("Positioned on wrong element, not on DNS");
throw new TestException(TestResult.Failed, "");
}
}
TestLog.Compare(DataReader.ReadToDescendant("e:elem"), false, "There are no more descendants");
TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type");
while (DataReader.Read()) ;
DataReader.Dispose();
return;
default:
throw new TestFailedException("Error in Test type");
}
}
//[Variation("If name not found, stop at end element of the subtree", Priority = 1)]
public void v4()
{
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "elem");
TestLog.Compare(DataReader.ReadToDescendant("abc"), false, "Reader returned true for an invalid name");
TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type");
DataReader.Read();
TestLog.Compare(DataReader.ReadToDescendant("abc", "elem"), false, "reader returned true for an invalid name,ns combination");
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Positioning on a level and try to find the name which is on a level higher", Priority = 1)]
public void v5()
{
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "child3");
TestLog.Compare(DataReader.ReadToDescendant("child1"), false, "Reader returned true for an invalid name");
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type");
TestLog.Compare(DataReader.LocalName, "child3", "Wrong name");
PositionOnElement(DataReader, "child3");
TestLog.Compare(DataReader.ReadToDescendant("child2", "child2"), false, "Reader returned true for an invalid name,ns");
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type for name,ns");
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Read to Descendant on one level and again to level below it", Priority = 1)]
public void v6()
{
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "root");
TestLog.Compare(DataReader.ReadToDescendant("elem"), true, "Cant find elem");
TestLog.Compare(DataReader.ReadToDescendant("child1"), true, "Cant find child1");
TestLog.Compare(DataReader.ReadToDescendant("child2"), true, "Cant find child2");
TestLog.Compare(DataReader.ReadToDescendant("child3"), true, "Cant find child3");
TestLog.Compare(DataReader.ReadToDescendant("child4"), false, "Shouldn't find child4");
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element");
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Read to Descendant on one level and again to level below it, with namespace", Priority = 1)]
public void v7()
{
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "root");
TestLog.Compare(DataReader.ReadToDescendant("elem", "elem"), true, "Cant find elem");
TestLog.Compare(DataReader.ReadToDescendant("child1", "elem"), true, "Cant find child1");
TestLog.Compare(DataReader.ReadToDescendant("child2", "child2"), true, "Cant find child2");
TestLog.Compare(DataReader.ReadToDescendant("child3", "child2"), true, "Cant find child3");
TestLog.Compare(DataReader.ReadToDescendant("child4", "child2"), false, "Shouldn't find child4");
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element");
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Read to Descendant on one level and again to level below it, with prefix", Priority = 1)]
public void v8()
{
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "root");
TestLog.Compare(DataReader.ReadToDescendant("e:elem"), true, "Cant find elem");
TestLog.Compare(DataReader.ReadToDescendant("e:child1"), true, "Cant find child1");
TestLog.Compare(DataReader.ReadToDescendant("e:child2"), true, "Cant find child2");
TestLog.Compare(DataReader.ReadToDescendant("e:child3"), true, "Cant find child3");
TestLog.Compare(DataReader.ReadToDescendant("e:child4"), false, "Shouldn't find child4");
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element");
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Multiple Reads to children and then next siblings, NNS", Priority = 2)]
public void v9()
{
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "root");
TestLog.Compare(DataReader.ReadToDescendant("elem"), true, "Read fails elem");
TestLog.Compare(DataReader.ReadToDescendant("child3"), true, "Read fails child3");
TestLog.Compare(DataReader.ReadToNextSibling("child4"), true, "Read fails child4");
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Multiple Reads to children and then next siblings, DNS", Priority = 2)]
public void v10()
{
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "root");
TestLog.Compare(DataReader.ReadToDescendant("elem", "elem"), true, "Read fails elem");
TestLog.Compare(DataReader.ReadToDescendant("child3", "child2"), true, "Read fails child3");
TestLog.Compare(DataReader.ReadToNextSibling("child4", "child2"), true, "Read fails child4");
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Multiple Reads to children and then next siblings, NS", Priority = 2)]
public void v11()
{
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "root");
TestLog.Compare(DataReader.ReadToDescendant("e:elem"), true, "Read fails elem");
TestLog.Compare(DataReader.ReadToDescendant("e:child3"), true, "Read fails child3");
TestLog.Compare(DataReader.ReadToNextSibling("e:child4"), true, "Read fails child4");
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Call from different nodetypes", Priority = 1)]
public void v12()
{
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
while (DataReader.Read())
{
if (DataReader.NodeType != XmlNodeType.Element)
{
TestLog.Compare(DataReader.ReadToDescendant("child1"), false, "Fails on node");
}
else
{
if (DataReader.HasAttributes)
{
while (DataReader.MoveToNextAttribute())
{
TestLog.Compare(DataReader.ReadToDescendant("abc"), false, "Fails on attribute node");
}
}
}
}
DataReader.Dispose();
}
//[Variation("Only child has namespaces and read to it", Priority = 2)]
public void v14()
{
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "root");
TestLog.Compare(DataReader.ReadToDescendant("child2", "child2"), true, "Fails on attribute node");
DataReader.Dispose();
}
//[Variation("Pass null to both arguments throws ArgumentException", Priority = 2)]
public void v15()
{
XmlReader DataReader = GetReader(new StringReader("<root><b/></root>"));
DataReader.Read();
try
{
DataReader.ReadToDescendant(null);
}
catch (ArgumentNullException)
{
}
try
{
DataReader.ReadToDescendant("b", null);
}
catch (ArgumentNullException)
{
}
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Different names, same uri works correctly", Priority = 2)]
public void v17()
{
XmlReader DataReader = GetReader(new StringReader("<root><child1 xmlns='foo'/>blah<child1 xmlns='bar'>blah</child1></root>"));
DataReader.Read();
DataReader.ReadToDescendant("child1", "bar");
TestLog.Compare(DataReader.IsEmptyElement, false, "Not on the correct node");
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("On Root Node", Priority = 0, Params = new object[] { "NNS" })]
//[Variation("On Root Node", Priority = 0, Params = new object[] { "DNS" })]
//[Variation("On Root Node", Priority = 0, Params = new object[] { "NS" })]
public void v18()
{
string type = Variation.Params[0].ToString();
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
switch (type)
{
case "NNS":
DataReader.ReadToDescendant("elem");
if (DataReader.HasAttributes)
{
TestLog.WriteLine("Positioned on wrong element");
TestLog.WriteIgnore(DataReader.ReadInnerXml() + "\n");
throw new TestException(TestResult.Failed, "");
}
while (DataReader.Read()) ;
DataReader.Dispose();
return;
case "DNS":
DataReader.ReadToDescendant("elem", "elem");
if (DataReader.HasAttributes)
{
if (DataReader.GetAttribute("xmlns") == null)
{
TestLog.WriteLine("Positioned on wrong element, not on DNS");
throw new TestException(TestResult.Failed, "");
}
}
while (DataReader.Read()) ;
DataReader.Dispose();
return;
case "NS":
DataReader.ReadToDescendant("e:elem");
if (DataReader.HasAttributes)
{
if (DataReader.GetAttribute("xmlns:e") == null)
{
TestLog.WriteLine("Positioned on wrong element, not on NS");
throw new TestException(TestResult.Failed, "");
}
}
while (DataReader.Read()) ;
DataReader.Dispose();
return;
default:
throw new TestFailedException("Error in Test type");
}
}
//[Variation("427176 Assertion failed when call XmlReader.ReadToDescendant() for non-existing node", Priority = 1)]
public void v19()
{
XmlReader DataReader = GetReader(new StringReader("<a>b</a>"));
TestLog.Compare(DataReader.ReadToDescendant("foo"), false, "Should fail without assert");
DataReader.Dispose();
}
}
}
}
}
| |
using System;
using System.Text;
using Xunit;
namespace System.Text.EncodingTests
{
//System.Test.UnicodeEncoding.GetBytes(System.String,System.Int32,System.Int32,System.Byte[],System.Int32) [v-zuolan]
public class UnicodeEncodingGetBytes2
{
#region Positive Tests
// PosTest1:Invoke the method
[Fact]
public void PosTest1()
{
String chars = GetString(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
actualValue = uEncoding.GetBytes(chars, 0, 10, bytes, 5);
Assert.Equal(20, actualValue);
}
// PosTest2:Invoke the method and set charCount as 1 and byteIndex as 0
[Fact]
public void PosTest2()
{
String chars = GetString(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
actualValue = uEncoding.GetBytes(chars, 0, 1, bytes, 0);
Assert.Equal(2, actualValue);
}
// PosTest3:Invoke the method and set charIndex as 20
[Fact]
public void PosTest3()
{
String chars = GetString(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
actualValue = uEncoding.GetBytes(chars, 0, 0, bytes, 30);
Assert.Equal(0, actualValue);
}
#endregion
#region Negative Tests
// NegTest1:Invoke the method and set chars as null
[Fact]
public void NegTest1()
{
String chars = null;
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentNullException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, 0, bytes, 0);
});
}
// NegTest2:Invoke the method and set bytes as null
[Fact]
public void NegTest2()
{
String chars = GetString(10);
Byte[] bytes = null;
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentNullException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, 0, bytes, 0);
});
}
// NegTest3:Invoke the method and the destination buffer is not enough
[Fact]
public void NegTest3()
{
String chars = GetString(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, 10, bytes, 15);
});
}
// NegTest4:Invoke the method and the destination buffer is not enough
[Fact]
public void NegTest4()
{
String chars = GetString(10);
Byte[] bytes = new Byte[10];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, 10, bytes, 0);
});
}
// NegTest5:Invoke the method and set charIndex as -1
[Fact]
public void NegTest5()
{
String chars = GetString(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetBytes(chars, -1, 1, bytes, 0);
});
}
// NegTest6:Invoke the method and set charIndex as 15
[Fact]
public void NegTest6()
{
String chars = GetString(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 15, 1, bytes, 0);
});
}
// NegTest7:Invoke the method and set charCount as -1
[Fact]
public void NegTest7()
{
String chars = GetString(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, -1, bytes, 0);
});
}
// NegTest8:Invoke the method and set charCount as 12
[Fact]
public void NegTest8()
{
String chars = GetString(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, 12, bytes, 0);
});
}
// NegTest9:Invoke the method and set byteIndex as -1
[Fact]
public void NegTest9()
{
String chars = GetString(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, 1, bytes, -1);
});
}
// NegTest10:Invoke the method and set charIndex as 31
[Fact]
public void NegTest10()
{
String chars = GetString(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, 0, bytes, 31);
});
}
#endregion
#region Helper Method
//Create a None-Surrogate-Char String.
public String GetString(int length)
{
if (length <= 0) return "";
String tempStr = null;
int i = 0;
while (i < length)
{
Char temp = TestLibrary.Generator.GetChar(-55);
if (!Char.IsSurrogate(temp))
{
tempStr = tempStr + temp.ToString();
i++;
}
}
return tempStr;
}
public String ToString(String myString)
{
String str = "{";
Char[] chars = myString.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
str = str + @"\u" + String.Format("{0:X04}", (int)chars[i]);
if (i != chars.Length - 1) str = str + ",";
}
str = str + "}";
return str;
}
#endregion
}
}
| |
/*
* CP865.cs - Nordic (DOS) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "ibm-865.ucm".
namespace I18N.West
{
using System;
using I18N.Common;
public class CP865 : ByteEncoding
{
public CP865()
: base(865, ToChars, "Nordic (DOS)",
"IBM863", "IBM865", "IBM865",
false, false, false, false, 1252)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005',
'\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
'\u0018', '\u0019', '\u001C', '\u001B', '\u007F', '\u001D',
'\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023',
'\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029',
'\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B',
'\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041',
'\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
'\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D',
'\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
'\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059',
'\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
'\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065',
'\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B',
'\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071',
'\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
'\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D',
'\u007E', '\u001A', '\u00C7', '\u00FC', '\u00E9', '\u00E2',
'\u00E4', '\u00E0', '\u00E5', '\u00E7', '\u00EA', '\u00EB',
'\u00E8', '\u00EF', '\u00EE', '\u00EC', '\u00C4', '\u00C5',
'\u00C9', '\u00E6', '\u00C6', '\u00F4', '\u00F6', '\u00F2',
'\u00FB', '\u00F9', '\u00FF', '\u00D6', '\u00DC', '\u00F8',
'\u00A3', '\u00D8', '\u20A7', '\u0192', '\u00E1', '\u00ED',
'\u00F3', '\u00FA', '\u00F1', '\u00D1', '\u00AA', '\u00BA',
'\u00BF', '\u2310', '\u00AC', '\u00BD', '\u00BC', '\u00A1',
'\u00AB', '\u00A4', '\u2591', '\u2592', '\u2593', '\u2502',
'\u2524', '\u2561', '\u2562', '\u2556', '\u2555', '\u2563',
'\u2551', '\u2557', '\u255D', '\u255C', '\u255B', '\u2510',
'\u2514', '\u2534', '\u252C', '\u251C', '\u2500', '\u253C',
'\u255E', '\u255F', '\u255A', '\u2554', '\u2569', '\u2566',
'\u2560', '\u2550', '\u256C', '\u2567', '\u2568', '\u2564',
'\u2565', '\u2559', '\u2558', '\u2552', '\u2553', '\u256B',
'\u256A', '\u2518', '\u250C', '\u2588', '\u2584', '\u258C',
'\u2590', '\u2580', '\u03B1', '\u00DF', '\u0393', '\u03C0',
'\u03A3', '\u03C3', '\u03BC', '\u03C4', '\u03A6', '\u0398',
'\u03A9', '\u03B4', '\u221E', '\u03C6', '\u03B5', '\u2229',
'\u2261', '\u00B1', '\u2265', '\u2264', '\u2320', '\u2321',
'\u00F7', '\u2248', '\u00B0', '\u2219', '\u00B7', '\u221A',
'\u207F', '\u00B2', '\u25A0', '\u00A0',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 26) switch(ch)
{
case 0x001B:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x0020:
case 0x0021:
case 0x0022:
case 0x0023:
case 0x0024:
case 0x0025:
case 0x0026:
case 0x0027:
case 0x0028:
case 0x0029:
case 0x002A:
case 0x002B:
case 0x002C:
case 0x002D:
case 0x002E:
case 0x002F:
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
case 0x003A:
case 0x003B:
case 0x003C:
case 0x003D:
case 0x003E:
case 0x003F:
case 0x0040:
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
case 0x005B:
case 0x005C:
case 0x005D:
case 0x005E:
case 0x005F:
case 0x0060:
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
case 0x007B:
case 0x007C:
case 0x007D:
case 0x007E:
break;
case 0x001A: ch = 0x7F; break;
case 0x001C: ch = 0x1A; break;
case 0x007F: ch = 0x1C; break;
case 0x00A0: ch = 0xFF; break;
case 0x00A1: ch = 0xAD; break;
case 0x00A3: ch = 0x9C; break;
case 0x00A4: ch = 0xAF; break;
case 0x00A7: ch = 0x15; break;
case 0x00AA: ch = 0xA6; break;
case 0x00AB: ch = 0xAE; break;
case 0x00AC: ch = 0xAA; break;
case 0x00B0: ch = 0xF8; break;
case 0x00B1: ch = 0xF1; break;
case 0x00B2: ch = 0xFD; break;
case 0x00B6: ch = 0x14; break;
case 0x00B7: ch = 0xFA; break;
case 0x00BA: ch = 0xA7; break;
case 0x00BC: ch = 0xAC; break;
case 0x00BD: ch = 0xAB; break;
case 0x00BF: ch = 0xA8; break;
case 0x00C4: ch = 0x8E; break;
case 0x00C5: ch = 0x8F; break;
case 0x00C6: ch = 0x92; break;
case 0x00C7: ch = 0x80; break;
case 0x00C9: ch = 0x90; break;
case 0x00D1: ch = 0xA5; break;
case 0x00D6: ch = 0x99; break;
case 0x00D8: ch = 0x9D; break;
case 0x00DC: ch = 0x9A; break;
case 0x00DF: ch = 0xE1; break;
case 0x00E0: ch = 0x85; break;
case 0x00E1: ch = 0xA0; break;
case 0x00E2: ch = 0x83; break;
case 0x00E4: ch = 0x84; break;
case 0x00E5: ch = 0x86; break;
case 0x00E6: ch = 0x91; break;
case 0x00E7: ch = 0x87; break;
case 0x00E8: ch = 0x8A; break;
case 0x00E9: ch = 0x82; break;
case 0x00EA: ch = 0x88; break;
case 0x00EB: ch = 0x89; break;
case 0x00EC: ch = 0x8D; break;
case 0x00ED: ch = 0xA1; break;
case 0x00EE: ch = 0x8C; break;
case 0x00EF: ch = 0x8B; break;
case 0x00F1: ch = 0xA4; break;
case 0x00F2: ch = 0x95; break;
case 0x00F3: ch = 0xA2; break;
case 0x00F4: ch = 0x93; break;
case 0x00F6: ch = 0x94; break;
case 0x00F7: ch = 0xF6; break;
case 0x00F8: ch = 0x9B; break;
case 0x00F9: ch = 0x97; break;
case 0x00FA: ch = 0xA3; break;
case 0x00FB: ch = 0x96; break;
case 0x00FC: ch = 0x81; break;
case 0x00FF: ch = 0x98; break;
case 0x0192: ch = 0x9F; break;
case 0x0393: ch = 0xE2; break;
case 0x0398: ch = 0xE9; break;
case 0x03A3: ch = 0xE4; break;
case 0x03A6: ch = 0xE8; break;
case 0x03A9: ch = 0xEA; break;
case 0x03B1: ch = 0xE0; break;
case 0x03B4: ch = 0xEB; break;
case 0x03B5: ch = 0xEE; break;
case 0x03BC: ch = 0xE6; break;
case 0x03C0: ch = 0xE3; break;
case 0x03C3: ch = 0xE5; break;
case 0x03C4: ch = 0xE7; break;
case 0x03C6: ch = 0xED; break;
case 0x2022: ch = 0x07; break;
case 0x203C: ch = 0x13; break;
case 0x207F: ch = 0xFC; break;
case 0x20A7: ch = 0x9E; break;
case 0x2190: ch = 0x1B; break;
case 0x2191: ch = 0x18; break;
case 0x2192: ch = 0x1A; break;
case 0x2193: ch = 0x19; break;
case 0x2194: ch = 0x1D; break;
case 0x2195: ch = 0x12; break;
case 0x21A8: ch = 0x17; break;
case 0x2219: ch = 0xF9; break;
case 0x221A: ch = 0xFB; break;
case 0x221E: ch = 0xEC; break;
case 0x221F: ch = 0x1C; break;
case 0x2229: ch = 0xEF; break;
case 0x2248: ch = 0xF7; break;
case 0x2261: ch = 0xF0; break;
case 0x2264: ch = 0xF3; break;
case 0x2265: ch = 0xF2; break;
case 0x2302: ch = 0x7F; break;
case 0x2310: ch = 0xA9; break;
case 0x2320: ch = 0xF4; break;
case 0x2321: ch = 0xF5; break;
case 0x2500: ch = 0xC4; break;
case 0x2502: ch = 0xB3; break;
case 0x250C: ch = 0xDA; break;
case 0x2510: ch = 0xBF; break;
case 0x2514: ch = 0xC0; break;
case 0x2518: ch = 0xD9; break;
case 0x251C: ch = 0xC3; break;
case 0x2524: ch = 0xB4; break;
case 0x252C: ch = 0xC2; break;
case 0x2534: ch = 0xC1; break;
case 0x253C: ch = 0xC5; break;
case 0x2550: ch = 0xCD; break;
case 0x2551: ch = 0xBA; break;
case 0x2552: ch = 0xD5; break;
case 0x2553: ch = 0xD6; break;
case 0x2554: ch = 0xC9; break;
case 0x2555: ch = 0xB8; break;
case 0x2556: ch = 0xB7; break;
case 0x2557: ch = 0xBB; break;
case 0x2558: ch = 0xD4; break;
case 0x2559: ch = 0xD3; break;
case 0x255A: ch = 0xC8; break;
case 0x255B: ch = 0xBE; break;
case 0x255C: ch = 0xBD; break;
case 0x255D: ch = 0xBC; break;
case 0x255E: ch = 0xC6; break;
case 0x255F: ch = 0xC7; break;
case 0x2560: ch = 0xCC; break;
case 0x2561: ch = 0xB5; break;
case 0x2562: ch = 0xB6; break;
case 0x2563: ch = 0xB9; break;
case 0x2564: ch = 0xD1; break;
case 0x2565: ch = 0xD2; break;
case 0x2566: ch = 0xCB; break;
case 0x2567: ch = 0xCF; break;
case 0x2568: ch = 0xD0; break;
case 0x2569: ch = 0xCA; break;
case 0x256A: ch = 0xD8; break;
case 0x256B: ch = 0xD7; break;
case 0x256C: ch = 0xCE; break;
case 0x2580: ch = 0xDF; break;
case 0x2584: ch = 0xDC; break;
case 0x2588: ch = 0xDB; break;
case 0x258C: ch = 0xDD; break;
case 0x2590: ch = 0xDE; break;
case 0x2591: ch = 0xB0; break;
case 0x2592: ch = 0xB1; break;
case 0x2593: ch = 0xB2; break;
case 0x25A0: ch = 0xFE; break;
case 0x25AC: ch = 0x16; break;
case 0x25B2: ch = 0x1E; break;
case 0x25BA: ch = 0x10; break;
case 0x25BC: ch = 0x1F; break;
case 0x25C4: ch = 0x11; break;
case 0x25CB: ch = 0x09; break;
case 0x25D8: ch = 0x08; break;
case 0x25D9: ch = 0x0A; break;
case 0x263A: ch = 0x01; break;
case 0x263B: ch = 0x02; break;
case 0x263C: ch = 0x0F; break;
case 0x2640: ch = 0x0C; break;
case 0x2642: ch = 0x0B; break;
case 0x2660: ch = 0x06; break;
case 0x2663: ch = 0x05; break;
case 0x2665: ch = 0x03; break;
case 0x2666: ch = 0x04; break;
case 0x266A: ch = 0x0D; break;
case 0x266B: ch = 0x0E; break;
case 0xFFE8: ch = 0xB3; break;
case 0xFFE9: ch = 0x1B; break;
case 0xFFEA: ch = 0x18; break;
case 0xFFEB: ch = 0x1A; break;
case 0xFFEC: ch = 0x19; break;
case 0xFFED: ch = 0xFE; break;
case 0xFFEE: ch = 0x09; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 26) switch(ch)
{
case 0x001B:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x0020:
case 0x0021:
case 0x0022:
case 0x0023:
case 0x0024:
case 0x0025:
case 0x0026:
case 0x0027:
case 0x0028:
case 0x0029:
case 0x002A:
case 0x002B:
case 0x002C:
case 0x002D:
case 0x002E:
case 0x002F:
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
case 0x003A:
case 0x003B:
case 0x003C:
case 0x003D:
case 0x003E:
case 0x003F:
case 0x0040:
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
case 0x005B:
case 0x005C:
case 0x005D:
case 0x005E:
case 0x005F:
case 0x0060:
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
case 0x007B:
case 0x007C:
case 0x007D:
case 0x007E:
break;
case 0x001A: ch = 0x7F; break;
case 0x001C: ch = 0x1A; break;
case 0x007F: ch = 0x1C; break;
case 0x00A0: ch = 0xFF; break;
case 0x00A1: ch = 0xAD; break;
case 0x00A3: ch = 0x9C; break;
case 0x00A4: ch = 0xAF; break;
case 0x00A7: ch = 0x15; break;
case 0x00AA: ch = 0xA6; break;
case 0x00AB: ch = 0xAE; break;
case 0x00AC: ch = 0xAA; break;
case 0x00B0: ch = 0xF8; break;
case 0x00B1: ch = 0xF1; break;
case 0x00B2: ch = 0xFD; break;
case 0x00B6: ch = 0x14; break;
case 0x00B7: ch = 0xFA; break;
case 0x00BA: ch = 0xA7; break;
case 0x00BC: ch = 0xAC; break;
case 0x00BD: ch = 0xAB; break;
case 0x00BF: ch = 0xA8; break;
case 0x00C4: ch = 0x8E; break;
case 0x00C5: ch = 0x8F; break;
case 0x00C6: ch = 0x92; break;
case 0x00C7: ch = 0x80; break;
case 0x00C9: ch = 0x90; break;
case 0x00D1: ch = 0xA5; break;
case 0x00D6: ch = 0x99; break;
case 0x00D8: ch = 0x9D; break;
case 0x00DC: ch = 0x9A; break;
case 0x00DF: ch = 0xE1; break;
case 0x00E0: ch = 0x85; break;
case 0x00E1: ch = 0xA0; break;
case 0x00E2: ch = 0x83; break;
case 0x00E4: ch = 0x84; break;
case 0x00E5: ch = 0x86; break;
case 0x00E6: ch = 0x91; break;
case 0x00E7: ch = 0x87; break;
case 0x00E8: ch = 0x8A; break;
case 0x00E9: ch = 0x82; break;
case 0x00EA: ch = 0x88; break;
case 0x00EB: ch = 0x89; break;
case 0x00EC: ch = 0x8D; break;
case 0x00ED: ch = 0xA1; break;
case 0x00EE: ch = 0x8C; break;
case 0x00EF: ch = 0x8B; break;
case 0x00F1: ch = 0xA4; break;
case 0x00F2: ch = 0x95; break;
case 0x00F3: ch = 0xA2; break;
case 0x00F4: ch = 0x93; break;
case 0x00F6: ch = 0x94; break;
case 0x00F7: ch = 0xF6; break;
case 0x00F8: ch = 0x9B; break;
case 0x00F9: ch = 0x97; break;
case 0x00FA: ch = 0xA3; break;
case 0x00FB: ch = 0x96; break;
case 0x00FC: ch = 0x81; break;
case 0x00FF: ch = 0x98; break;
case 0x0192: ch = 0x9F; break;
case 0x0393: ch = 0xE2; break;
case 0x0398: ch = 0xE9; break;
case 0x03A3: ch = 0xE4; break;
case 0x03A6: ch = 0xE8; break;
case 0x03A9: ch = 0xEA; break;
case 0x03B1: ch = 0xE0; break;
case 0x03B4: ch = 0xEB; break;
case 0x03B5: ch = 0xEE; break;
case 0x03BC: ch = 0xE6; break;
case 0x03C0: ch = 0xE3; break;
case 0x03C3: ch = 0xE5; break;
case 0x03C4: ch = 0xE7; break;
case 0x03C6: ch = 0xED; break;
case 0x2022: ch = 0x07; break;
case 0x203C: ch = 0x13; break;
case 0x207F: ch = 0xFC; break;
case 0x20A7: ch = 0x9E; break;
case 0x2190: ch = 0x1B; break;
case 0x2191: ch = 0x18; break;
case 0x2192: ch = 0x1A; break;
case 0x2193: ch = 0x19; break;
case 0x2194: ch = 0x1D; break;
case 0x2195: ch = 0x12; break;
case 0x21A8: ch = 0x17; break;
case 0x2219: ch = 0xF9; break;
case 0x221A: ch = 0xFB; break;
case 0x221E: ch = 0xEC; break;
case 0x221F: ch = 0x1C; break;
case 0x2229: ch = 0xEF; break;
case 0x2248: ch = 0xF7; break;
case 0x2261: ch = 0xF0; break;
case 0x2264: ch = 0xF3; break;
case 0x2265: ch = 0xF2; break;
case 0x2302: ch = 0x7F; break;
case 0x2310: ch = 0xA9; break;
case 0x2320: ch = 0xF4; break;
case 0x2321: ch = 0xF5; break;
case 0x2500: ch = 0xC4; break;
case 0x2502: ch = 0xB3; break;
case 0x250C: ch = 0xDA; break;
case 0x2510: ch = 0xBF; break;
case 0x2514: ch = 0xC0; break;
case 0x2518: ch = 0xD9; break;
case 0x251C: ch = 0xC3; break;
case 0x2524: ch = 0xB4; break;
case 0x252C: ch = 0xC2; break;
case 0x2534: ch = 0xC1; break;
case 0x253C: ch = 0xC5; break;
case 0x2550: ch = 0xCD; break;
case 0x2551: ch = 0xBA; break;
case 0x2552: ch = 0xD5; break;
case 0x2553: ch = 0xD6; break;
case 0x2554: ch = 0xC9; break;
case 0x2555: ch = 0xB8; break;
case 0x2556: ch = 0xB7; break;
case 0x2557: ch = 0xBB; break;
case 0x2558: ch = 0xD4; break;
case 0x2559: ch = 0xD3; break;
case 0x255A: ch = 0xC8; break;
case 0x255B: ch = 0xBE; break;
case 0x255C: ch = 0xBD; break;
case 0x255D: ch = 0xBC; break;
case 0x255E: ch = 0xC6; break;
case 0x255F: ch = 0xC7; break;
case 0x2560: ch = 0xCC; break;
case 0x2561: ch = 0xB5; break;
case 0x2562: ch = 0xB6; break;
case 0x2563: ch = 0xB9; break;
case 0x2564: ch = 0xD1; break;
case 0x2565: ch = 0xD2; break;
case 0x2566: ch = 0xCB; break;
case 0x2567: ch = 0xCF; break;
case 0x2568: ch = 0xD0; break;
case 0x2569: ch = 0xCA; break;
case 0x256A: ch = 0xD8; break;
case 0x256B: ch = 0xD7; break;
case 0x256C: ch = 0xCE; break;
case 0x2580: ch = 0xDF; break;
case 0x2584: ch = 0xDC; break;
case 0x2588: ch = 0xDB; break;
case 0x258C: ch = 0xDD; break;
case 0x2590: ch = 0xDE; break;
case 0x2591: ch = 0xB0; break;
case 0x2592: ch = 0xB1; break;
case 0x2593: ch = 0xB2; break;
case 0x25A0: ch = 0xFE; break;
case 0x25AC: ch = 0x16; break;
case 0x25B2: ch = 0x1E; break;
case 0x25BA: ch = 0x10; break;
case 0x25BC: ch = 0x1F; break;
case 0x25C4: ch = 0x11; break;
case 0x25CB: ch = 0x09; break;
case 0x25D8: ch = 0x08; break;
case 0x25D9: ch = 0x0A; break;
case 0x263A: ch = 0x01; break;
case 0x263B: ch = 0x02; break;
case 0x263C: ch = 0x0F; break;
case 0x2640: ch = 0x0C; break;
case 0x2642: ch = 0x0B; break;
case 0x2660: ch = 0x06; break;
case 0x2663: ch = 0x05; break;
case 0x2665: ch = 0x03; break;
case 0x2666: ch = 0x04; break;
case 0x266A: ch = 0x0D; break;
case 0x266B: ch = 0x0E; break;
case 0xFFE8: ch = 0xB3; break;
case 0xFFE9: ch = 0x1B; break;
case 0xFFEA: ch = 0x18; break;
case 0xFFEB: ch = 0x1A; break;
case 0xFFEC: ch = 0x19; break;
case 0xFFED: ch = 0xFE; break;
case 0xFFEE: ch = 0x09; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP865
public class ENCibm865 : CP865
{
public ENCibm865() : base() {}
}; // class ENCibm865
}; // namespace I18N.West
| |
// Copyright (C) 2014 dot42
//
// Original filename: Javax.Crypto.Interfaces.cs
//
// 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.
#pragma warning disable 1717
namespace Javax.Crypto.Interfaces
{
/// <summary>
/// <para>The interface to a <b>password-based-encryption</b> key. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/PBEKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/PBEKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IPBEKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serial version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = -1430015993304333921;
}
/// <summary>
/// <para>The interface to a <b>password-based-encryption</b> key. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/PBEKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/PBEKey", AccessFlags = 1537)]
public partial interface IPBEKey : global::Javax.Crypto.ISecretKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the iteration count, 0 if not specified.</para><para></para>
/// </summary>
/// <returns>
/// <para>the iteration count, 0 if not specified. </para>
/// </returns>
/// <java-name>
/// getIterationCount
/// </java-name>
[Dot42.DexImport("getIterationCount", "()I", AccessFlags = 1025)]
int GetIterationCount() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a copy of the salt data or null if not specified.</para><para></para>
/// </summary>
/// <returns>
/// <para>a copy of the salt data or null if not specified. </para>
/// </returns>
/// <java-name>
/// getSalt
/// </java-name>
[Dot42.DexImport("getSalt", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
byte[] GetSalt() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a copy to the password.</para><para></para>
/// </summary>
/// <returns>
/// <para>a copy to the password. </para>
/// </returns>
/// <java-name>
/// getPassword
/// </java-name>
[Dot42.DexImport("getPassword", "()[C", AccessFlags = 1025)]
char[] GetPassword() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for a Diffie-Hellman key. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHKey", AccessFlags = 1537)]
public partial interface IDHKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the parameters for this key.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters for this key. </para>
/// </returns>
/// <java-name>
/// getParams
/// </java-name>
[Dot42.DexImport("getParams", "()Ljavax/crypto/spec/DHParameterSpec;", AccessFlags = 1025)]
global::Javax.Crypto.Spec.DHParameterSpec GetParams() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for a private key in the Diffie-Hellman key exchange protocol. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHPrivateKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHPrivateKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IDHPrivateKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serialization version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = 2211791113380396553;
}
/// <summary>
/// <para>The interface for a private key in the Diffie-Hellman key exchange protocol. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHPrivateKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHPrivateKey", AccessFlags = 1537)]
public partial interface IDHPrivateKey : global::Javax.Crypto.Interfaces.IDHKey, global::Java.Security.IPrivateKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns this key's private value x. </para>
/// </summary>
/// <returns>
/// <para>this key's private value x. </para>
/// </returns>
/// <java-name>
/// getX
/// </java-name>
[Dot42.DexImport("getX", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetX() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for a public key in the Diffie-Hellman key exchange protocol. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHPublicKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHPublicKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IDHPublicKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serial version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = -6628103563352519193;
}
/// <summary>
/// <para>The interface for a public key in the Diffie-Hellman key exchange protocol. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHPublicKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHPublicKey", AccessFlags = 1537)]
public partial interface IDHPublicKey : global::Javax.Crypto.Interfaces.IDHKey, global::Java.Security.IPublicKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns this key's public value Y. </para>
/// </summary>
/// <returns>
/// <para>this key's public value Y. </para>
/// </returns>
/// <java-name>
/// getY
/// </java-name>
[Dot42.DexImport("getY", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetY() /* MethodBuilder.Create */ ;
}
}
| |
using System;
using System.ComponentModel;
using System.Xml.Serialization;
namespace Wyam.Feeds.Syndication.Atom
{
/// <summary>
/// http://tools.ietf.org/html/rfc4287#section-4.2.7
/// </summary>
[Serializable]
public class AtomLink : AtomCommonAttributes, IUriProvider
{
private AtomLinkRelation _relation = AtomLinkRelation.None;
private Uri _rel = null;
private string _type = null;
private Uri _href = null;
private string _hreflang = null;
private string _title = null;
private string _length = null;
private int _threadCount = 0;
private AtomDate _threadUpdated;
public AtomLink()
{
}
public AtomLink(string link)
{
Href = link;
}
[XmlIgnore]
[DefaultValue(AtomLinkRelation.None)]
public AtomLinkRelation Relation
{
get
{
// http://tools.ietf.org/html/rfc4685#section-4
if (ThreadCount > 0)
{
return AtomLinkRelation.Replies;
}
return _relation;
}
set
{
_relation = value;
_rel = null;
}
}
[XmlAttribute("rel")]
[DefaultValue(null)]
public string Rel
{
get
{
if (Relation == AtomLinkRelation.None)
{
return ConvertToString(_rel);
}
// TODO: use XmlEnum values
switch (_relation)
{
case AtomLinkRelation.NextArchive:
{
return "next-archive";
}
case AtomLinkRelation.PrevArchive:
{
return "prev-archive";
}
default:
{
return _relation.ToString().ToLowerInvariant();
}
}
}
set
{
if (string.IsNullOrEmpty(value))
{
_relation = AtomLinkRelation.None;
_rel = null;
}
try
{
// TODO: use XmlEnum values
_relation = (AtomLinkRelation)Enum.Parse(typeof(AtomLinkRelation), value.Replace("-", string.Empty), true);
}
catch
{
_relation = AtomLinkRelation.None;
_rel = ConvertToUri(value);
}
}
}
[XmlAttribute("type")]
[DefaultValue(null)]
public string Type
{
get
{
string value = _type;
if (ThreadCount > 0 && string.IsNullOrEmpty(value))
{
return AtomFeed.MimeType;
}
return value;
}
set
{
_type = string.IsNullOrEmpty(value) ? null : value;
}
}
[XmlAttribute("href")]
[DefaultValue(null)]
public string Href
{
get { return ConvertToString(_href); }
set { _href = ConvertToUri(value); }
}
[XmlAttribute("hreflang")]
[DefaultValue(null)]
public string HrefLang
{
get { return _hreflang; }
set { _hreflang = string.IsNullOrEmpty(value) ? null : value; }
}
[XmlAttribute("length")]
[DefaultValue(null)]
public string Length
{
get { return _length; }
set { _length = string.IsNullOrEmpty(value) ? null : value; }
}
[XmlAttribute("title")]
[DefaultValue(null)]
public string Title
{
get { return _title; }
set { _title = string.IsNullOrEmpty(value) ? null : value; }
}
/// <summary>
/// http://tools.ietf.org/html/rfc4685#section-4
/// </summary>
[XmlAttribute("count", Namespace=ThreadingNamespace)]
public int ThreadCount
{
get { return _threadCount; }
set { _threadCount = (value < 0) ? 0 : value; }
}
[XmlIgnore]
public bool ThreadCountSpecified
{
get { return Relation == AtomLinkRelation.Replies; }
set { }
}
/// <summary>
/// http://tools.ietf.org/html/rfc4685#section-4
/// </summary>
[XmlIgnore]
public AtomDate ThreadUpdated
{
get { return _threadUpdated; }
set { _threadUpdated = value; }
}
/// <summary>
/// Gets and sets the DateTime using ISO-8601 date format.
/// For serialization purposes only, use the ThreadUpdated property instead.
/// </summary>
[DefaultValue(null)]
[XmlAttribute("updated", Namespace=ThreadingNamespace)]
public string ThreadUpdatedIso8601
{
get { return _threadUpdated.ValueIso8601; }
set { _threadUpdated.ValueIso8601 = value; }
}
[XmlIgnore]
public bool ThreadUpdatedSpecified
{
get { return (Relation == AtomLinkRelation.Replies) && _threadUpdated.HasValue; }
set { }
}
Uri IUriProvider.Uri => _href;
public override string ToString()
{
return Href;
}
public override void AddNamespaces(XmlSerializerNamespaces namespaces)
{
if (ThreadCount > 0)
{
namespaces.Add(ThreadingPrefix, ThreadingNamespace);
}
base.AddNamespaces(namespaces);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using VerifyInsurance.Areas.HelpPage.ModelDescriptions;
using VerifyInsurance.Areas.HelpPage.Models;
namespace VerifyInsurance.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//
// System.Configuration.ConfigurationSection.cs
//
// Authors:
// Duncan Mak (duncan@ximian.com)
// Lluis Sanchez Gual (lluis@novell.com)
// Martin Baulig <martin.baulig@xamarin.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.
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
// Copyright (c) 2012 Xamarin Inc. (http://www.xamarin.com)
//
using System.Collections;
using System.Xml;
using System.IO;
#if !TARGET_JVM
using System.Security.Cryptography.Xml;
#endif
using System.Configuration.Internal;
namespace System.Configuration
{
public abstract class ConfigurationSection : ConfigurationElement
{
SectionInformation sectionInformation;
IConfigurationSectionHandler section_handler;
string externalDataXml;
protected ConfigurationSection ()
{
}
internal string ExternalDataXml {
get { return externalDataXml; }
}
internal IConfigurationSectionHandler SectionHandler {
get { return section_handler; }
set { section_handler = value; }
}
[MonoTODO]
public SectionInformation SectionInformation {
get {
if (sectionInformation == null)
sectionInformation = new SectionInformation ();
return sectionInformation;
}
}
private object _configContext;
internal object ConfigContext {
get {
return _configContext;
}
set {
_configContext = value;
}
}
[MonoTODO ("Provide ConfigContext. Likely the culprit of bug #322493")]
public virtual object GetRuntimeObject ()
{
if (SectionHandler != null) {
ConfigurationSection parentSection = sectionInformation != null ? sectionInformation.GetParentSection () : null;
object parent = parentSection != null ? parentSection.GetRuntimeObject () : null;
if (RawXml == null)
return parent;
try {
// This code requires some re-thinking...
XmlReader reader = new ConfigXmlTextReader (
new StringReader (RawXml),
Configuration.FilePath);
DoDeserializeSection (reader);
if (!String.IsNullOrEmpty (SectionInformation.ConfigSource)) {
string fileDir = SectionInformation.ConfigFilePath;
if (!String.IsNullOrEmpty (fileDir))
fileDir = Path.GetDirectoryName (fileDir);
else
fileDir = String.Empty;
string path = Path.Combine (fileDir, SectionInformation.ConfigSource);
if (File.Exists (path)) {
RawXml = File.ReadAllText (path);
SectionInformation.SetRawXml (RawXml);
}
}
} catch {
// ignore, it can fail - we deserialize only in order to get
// the configSource attribute
}
XmlDocument doc = new ConfigurationXmlDocument ();
doc.LoadXml (RawXml);
return SectionHandler.Create (parent, ConfigContext, doc.DocumentElement);
}
return this;
}
[MonoTODO]
protected internal override bool IsModified ()
{
return base.IsModified ();
}
[MonoTODO]
protected internal override void ResetModified ()
{
base.ResetModified ();
}
ConfigurationElement CreateElement (Type t)
{
ConfigurationElement elem = (ConfigurationElement) Activator.CreateInstance (t);
elem.Init ();
elem.Configuration = Configuration;
if (IsReadOnly ())
elem.SetReadOnly ();
return elem;
}
void DoDeserializeSection (XmlReader reader)
{
reader.MoveToContent ();
string protection_provider = null;
string config_source = null;
string localName;
while (reader.MoveToNextAttribute ()) {
localName = reader.LocalName;
if (localName == "configProtectionProvider")
protection_provider = reader.Value;
else if (localName == "configSource")
config_source = reader.Value;
}
/* XXX this stuff shouldn't be here */
{
if (protection_provider != null) {
ProtectedConfigurationProvider prov = ProtectedConfiguration.GetProvider (protection_provider, true);
XmlDocument doc = new ConfigurationXmlDocument ();
reader.MoveToElement ();
doc.Load (new StringReader (reader.ReadInnerXml ()));
XmlNode n = prov.Decrypt (doc);
reader = new XmlNodeReader (n);
SectionInformation.ProtectSection (protection_provider);
reader.MoveToContent ();
}
}
if (config_source != null)
SectionInformation.ConfigSource = config_source;
SectionInformation.SetRawXml (RawXml);
if (SectionHandler == null)
DeserializeElement (reader, false);
}
[MonoInternalNote ("find the proper location for the decryption stuff")]
public virtual void DeserializeSection (XmlReader reader)
{
try
{
DoDeserializeSection (reader);
}
catch (ConfigurationErrorsException ex)
{
throw new ConfigurationErrorsException(String.Format("Error deserializing configuration section {0}: {1}", this.SectionInformation.Name, ex.Message));
}
}
internal void DeserializeConfigSource (string basePath)
{
string config_source = SectionInformation.ConfigSource;
if (String.IsNullOrEmpty (config_source))
return;
if (Path.IsPathRooted (config_source))
throw new ConfigurationErrorsException ("The configSource attribute must be a relative physical path.");
if (HasLocalModifications ())
throw new ConfigurationErrorsException ("A section using 'configSource' may contain no other attributes or elements.");
string path = Path.Combine (basePath, config_source);
if (!File.Exists (path)) {
RawXml = null;
SectionInformation.SetRawXml (null);
throw new ConfigurationErrorsException (string.Format ("Unable to open configSource file '{0}'.", path));
}
RawXml = File.ReadAllText (path);
SectionInformation.SetRawXml (RawXml);
DeserializeElement (new ConfigXmlTextReader (new StringReader (RawXml), path), false);
}
public virtual string SerializeSection (ConfigurationElement parentElement, string name, ConfigurationSaveMode saveMode)
{
externalDataXml = null;
ConfigurationElement elem;
if (parentElement != null) {
elem = (ConfigurationElement) CreateElement (GetType());
elem.Unmerge (this, parentElement, saveMode);
}
else
elem = this;
/*
* FIXME: LAMESPEC
*
* Cache the current values of 'parentElement' and 'saveMode' for later use in
* ConfigurationElement.SerializeToXmlElement().
*
*/
elem.PrepareSave (parentElement, saveMode);
bool hasValues = elem.HasValues (parentElement, saveMode);
string ret;
using (StringWriter sw = new StringWriter ()) {
using (XmlTextWriter tw = new XmlTextWriter (sw)) {
tw.Formatting = Formatting.Indented;
if (hasValues)
elem.SerializeToXmlElement (tw, name);
else if ((saveMode == ConfigurationSaveMode.Modified) && elem.IsModified ()) {
// MS emits an empty section element.
tw.WriteStartElement (name);
tw.WriteEndElement ();
}
tw.Close ();
}
ret = sw.ToString ();
}
string config_source = SectionInformation.ConfigSource;
if (String.IsNullOrEmpty (config_source))
return ret;
externalDataXml = ret;
using (StringWriter sw = new StringWriter ()) {
bool haveName = !String.IsNullOrEmpty (name);
using (XmlTextWriter tw = new XmlTextWriter (sw)) {
if (haveName)
tw.WriteStartElement (name);
tw.WriteAttributeString ("configSource", config_source);
if (haveName)
tw.WriteEndElement ();
}
return sw.ToString ();
}
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Data.SqlServerCe;
using System.Text;
using MLifter.DAL.Interfaces;
using MLifter.DAL.Interfaces.DB;
using MLifter.DAL.Tools;
namespace MLifter.DAL.DB.MsSqlCe
{
/// <summary>
/// MsSqlCeStatisticConnector
/// </summary>
/// <remarks>Documented by Dev08, 2009-01-13</remarks>
class MsSqlCeStatisticConnector : IDbStatisticConnector
{
#region Initialization of MsSqlCeStatisticConnector
internal int RunningSession = -1;
private static Dictionary<ConnectionStringStruct, MsSqlCeStatisticConnector> instance = new Dictionary<ConnectionStringStruct, MsSqlCeStatisticConnector>();
public static MsSqlCeStatisticConnector GetInstance(ParentClass parent)
{
lock (instance)
{
ConnectionStringStruct connection = parent.CurrentUser.ConnectionString;
if (!instance.ContainsKey(connection))
instance.Add(connection, new MsSqlCeStatisticConnector(parent));
return instance[connection];
}
}
private ParentClass Parent;
private MsSqlCeStatisticConnector(ParentClass parentClass)
{
Parent = parentClass;
Parent.DictionaryClosed += new EventHandler(parent_DictionaryClosed);
}
void parent_DictionaryClosed(object sender, EventArgs e)
{
IParent parent = sender as IParent;
instance.Remove(parent.Parent.CurrentUser.ConnectionString);
}
#endregion
#region New IDbStatisticConnector Members (with extened LearningSession table)
/// <summary>
/// Gets the wrong cards.
/// </summary>
/// <param name="sessionId">The session id.</param>
/// <returns></returns>
/// <remarks>Documented by Dev08, 2009-01-28</remarks>
public int? GetWrongCards(int sessionId)
{
object wrongCardsCache = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.StatisticWrongCards, sessionId)];
if (wrongCardsCache == null || RunningSession == sessionId)
{
SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser);
cmd.CommandText = "SELECT sum_wrong FROM \"LearningSessions\" WHERE id = @sessId AND user_id=@uid AND lm_id=@lmid";
cmd.Parameters.Add("@sessId", sessionId);
cmd.Parameters.Add("@uid", Parent.CurrentUser.Id);
cmd.Parameters.Add("@lmid", Parent.GetParentDictionary().Id);
int? wrongCards = MSSQLCEConn.ExecuteScalar<int>(cmd);
//Save to Cache
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.StatisticWrongCards, sessionId, Cache.DefaultStatisticValidationTime)] = wrongCards;
return wrongCards;
}
return wrongCardsCache as int?;
}
/// <summary>
/// Gets the correct cards.
/// </summary>
/// <param name="sessionId">The session id.</param>
/// <returns></returns>
/// <remarks>Documented by Dev08, 2009-01-28</remarks>
public int? GetCorrectCards(int sessionId)
{
object correctCardsCache = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.StatisticCorrectCards, sessionId)];
if (correctCardsCache == null || RunningSession == sessionId)
{
SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser);
cmd.CommandText = "SELECT sum_right FROM \"LearningSessions\" WHERE id = @sessId AND user_id=@uid AND lm_id=@lmid";
cmd.Parameters.Add("@sessId", sessionId);
cmd.Parameters.Add("@uid", Parent.CurrentUser.Id);
cmd.Parameters.Add("@lmid", Parent.GetParentDictionary().Id);
int? correctCards = MSSQLCEConn.ExecuteScalar<int>(cmd);
//Save to Cache
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.StatisticCorrectCards, sessionId, Cache.DefaultStatisticValidationTime)] = correctCards;
return correctCards;
}
return correctCardsCache as int?;
}
/// <summary>
/// Gets the content of boxes.
/// </summary>
/// <param name="sessionId">The session id.</param>
/// <returns></returns>
/// <remarks>Documented by Dev08, 2009-01-28</remarks>
public List<int> GetContentOfBoxes(int sessionId)
{
object contentOfBoxesCache = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.StatisticContentOfBoxes, sessionId)];
if (contentOfBoxesCache == null || RunningSession == sessionId)
{
SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser);
cmd.CommandText = "SELECT box1_content, box2_content, box3_content, box4_content, box5_content, box6_content, box7_content, box8_content, box9_content, box10_content " +
"FROM LearningSessions WHERE id = @sessionId AND user_id=@uid AND lm_id=@lmid";
cmd.Parameters.Add("@sessionId", sessionId);
cmd.Parameters.Add("@uid", Parent.CurrentUser.Id);
cmd.Parameters.Add("@lmid", Parent.GetParentDictionary().Id);
SqlCeDataReader reader = MSSQLCEConn.ExecuteReader(cmd);
reader.Read();
object box1_content = reader["box1_content"];
object box2_content = reader["box2_content"];
object box3_content = reader["box3_content"];
object box4_content = reader["box4_content"];
object box5_content = reader["box5_content"];
object box6_content = reader["box6_content"];
object box7_content = reader["box7_content"];
object box8_content = reader["box9_content"];
object box9_content = reader["box9_content"];
object box10_content = reader["box10_content"];
reader.Close();
List<int> output = new List<int>();
output.Add(box1_content != DBNull.Value ? Convert.ToInt32(box1_content) : 0);
output.Add(box2_content != DBNull.Value ? Convert.ToInt32(box2_content) : 0);
output.Add(box3_content != DBNull.Value ? Convert.ToInt32(box3_content) : 0);
output.Add(box4_content != DBNull.Value ? Convert.ToInt32(box4_content) : 0);
output.Add(box5_content != DBNull.Value ? Convert.ToInt32(box5_content) : 0);
output.Add(box6_content != DBNull.Value ? Convert.ToInt32(box6_content) : 0);
output.Add(box7_content != DBNull.Value ? Convert.ToInt32(box7_content) : 0);
output.Add(box8_content != DBNull.Value ? Convert.ToInt32(box8_content) : 0);
output.Add(box9_content != DBNull.Value ? Convert.ToInt32(box9_content) : 0);
output.Add(box10_content != DBNull.Value ? Convert.ToInt32(box10_content) : 0);
//Save to Cache
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.StatisticContentOfBoxes, sessionId, Cache.DefaultStatisticValidationTime)] = output;
return output;
}
return contentOfBoxesCache as List<int>;
}
/// <summary>
/// Gets the start time stamp.
/// </summary>
/// <param name="sessionId">The session id.</param>
/// <returns></returns>
/// <remarks>Documented by Dev08, 2009-01-28</remarks>
public DateTime? GetStartTimeStamp(int sessionId)
{
object startTimeStamp = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.StatisticStartTime, sessionId)];
if (startTimeStamp == null || RunningSession == sessionId)
{
SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser);
cmd.CommandText = "SELECT starttime FROM \"LearningSessions\" WHERE \"LearningSessions\".id = @sessId AND user_id=@uid AND lm_id=@lmid";
cmd.Parameters.Add("@sessId", sessionId);
cmd.Parameters.Add("@uid", Parent.CurrentUser.Id);
cmd.Parameters.Add("@lmid", Parent.GetParentDictionary().Id);
DateTime? dt = MSSQLCEConn.ExecuteScalar<DateTime>(cmd);
//Save to Cache
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.StatisticStartTime, sessionId, Cache.DefaultStatisticValidationTime)] = dt;
return dt;
}
return startTimeStamp as DateTime?;
}
/// <summary>
/// Gets the end time stamp.
/// </summary>
/// <param name="sessionId">The session id.</param>
/// <returns></returns>
/// <remarks>Documented by Dev08, 2009-01-28</remarks>
public DateTime? GetEndTimeStamp(int sessionId)
{
if (RunningSession == sessionId)
return DateTime.Now;
object endTimeStamp = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.StatisticEndTime, sessionId)];
if (endTimeStamp == null || RunningSession == sessionId)
{
SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser);
cmd.CommandText = "SELECT endtime FROM \"LearningSessions\" WHERE \"LearningSessions\".id = @sessId AND user_id=@uid AND lm_id=@lmid";
cmd.Parameters.Add("@sessId", sessionId);
cmd.Parameters.Add("@uid", Parent.CurrentUser.Id);
cmd.Parameters.Add("@lmid", Parent.GetParentDictionary().Id);
object dt = MSSQLCEConn.ExecuteScalar<DateTime>(cmd);
DateTime? dateTime;
if (dt == null || !(dt is DateTime)) //either null or not DateTime
dateTime = DateTime.Now;
else
{
dateTime = (DateTime)dt;
}
//Save to Cache
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.StatisticEndTime, sessionId, Cache.DefaultStatisticValidationTime)] = dateTime;
return dateTime;
}
return endTimeStamp as DateTime?;
}
#endregion
/// <summary>
/// Gets the content of a specific the box. (replacement for the stored procedure GetBoxContent)
/// </summary>
/// <param name="sessionId">The session id.</param>
/// <param name="boxNumber">The box number (from 1 to 10).</param>
/// <returns></returns>
/// <remarks>Documented by Dev08, 2009-01-13</remarks>
private int GetBoxContent(int sessionId, int boxNumber)
{
SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser);
cmd.CommandText = "SELECT COUNT(*) FROM " +
"(SELECT DISTINCT ON (\"LearnLog\".cards_id) \"LearnLog\".new_box FROM " +
"\"LearnLog\" WHERE \"LearnLog\".session_id IN (SELECT id FROM \"LearningSessions\" WHERE \"LearningSessions\".lm_id = " +
"(SELECT lm_id FROM \"LearningSessions\" WHERE \"LearningSessions\".id = @endSessionId AND user_id=@uid AND lm_id=@lmid)) AND " +
"\"LearnLog\".session_id <= endSessionId ORDER BY cards_id, timestamp DESC) AS boxes WHERE new_box = @current_box;";
cmd.Parameters.Add("@endSessionId", sessionId);
cmd.Parameters.Add("@current_box", boxNumber);
cmd.Parameters.Add("@uid", Parent.CurrentUser.Id);
cmd.Parameters.Add("@lmid", Parent.GetParentDictionary().Id);
return Convert.ToInt32(MSSQLCEConn.ExecuteScalar(cmd));
}
}
}
| |
using System;
using System.IO;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.Serialization;
namespace SpiffLib
{
/// <summary>
///
/// </summary>
[Serializable]
public class Palette : ISerializable {
private Color[] m_aclr;
private Hashtable m_htbl = new Hashtable();
private bool m_fClearHash = false;
/// <summary>
///
/// </summary>
public string FileName;
/// <summary>
///
/// </summary>
/// <param name="strFileJasc"></param>
public Palette(string strFile)
{
if (!LoadJasc(strFile)) {
if (!LoadPhotoshopAct(strFile)) {
throw new Exception(strFile + " is not a Jasc or Photoshop .ACT format palette!");
}
}
FileName = strFile;
}
/// <summary>
///
/// </summary>
/// <param name="aclr"></param>
public Palette(Color[] aclr) {
m_aclr = (Color[])aclr.Clone();
}
/// <summary>
///
/// </summary>
public Palette(int cColors) {
m_aclr = new Color[cColors];
}
/// <summary>
///
/// </summary>
public Palette() {
m_aclr = new Color[0];
}
public Palette(SerializationInfo info, StreamingContext ctx) {
m_aclr = (Color[])info.GetValue("Colors", typeof(Color[]));
}
public void GetObjectData(SerializationInfo info, StreamingContext context) {
info.AddValue("Colors", m_aclr);
}
/// <summary>
///
/// </summary>
/// <param name="cEntriesUpTo"></param>
/// <param name="clrPad"></param>
public void Pad(int cEntriesUpTo, Color clrPad) {
Color[] aclrNew = new Color[cEntriesUpTo];
for (int iclr = 0; iclr < aclrNew.Length; iclr++) {
if (iclr < m_aclr.Length) {
aclrNew[iclr] = m_aclr[iclr];
} else {
aclrNew[iclr] = clrPad;
}
}
m_aclr = aclrNew;
m_fClearHash = true;
}
/// <summary>
///
/// </summary>
/// <param name="strFile"></param>
/// <returns></returns>
public static Palette OpenDialog(string strFile) {
OpenFileDialog frmOpen = new OpenFileDialog();
frmOpen.Filter = "Jasc Palette File (*.pal)|*.pal|Photoshop Act File (*.act)|*.act";
frmOpen.Title = "Palette File";
frmOpen.FileName = strFile;
if (frmOpen.ShowDialog() == DialogResult.Cancel)
return null;
try {
return new Palette(frmOpen.FileName);
} catch {
return null;
}
}
/// <summary>
///
/// </summary>
/// <param name="strFile"></param>
/// <returns></returns>
public bool SaveDialog() {
SaveFileDialog frmSave = new SaveFileDialog();
frmSave.Filter = "Jasc Palette File (*.pal)|*.pal|Photoshop Act File (*.act)|*.act";
frmSave.Title = "Palette File";
if (frmSave.ShowDialog() == DialogResult.Cancel)
return false;
try {
SaveJasc(frmSave.FileName);
return true;
} catch {
return false;
}
}
/// <summary>
///
/// </summary>
/// <param name="strFile"></param>
public void SaveBin(string strFile) {
// Write binary palette
Stream stm = new FileStream(strFile, FileMode.Create, FileAccess.Write, FileShare.None);
BinaryWriter bwtr = new BinaryWriter(stm);
bwtr.Write(Misc.SwapUShort((ushort)m_aclr.Length));
foreach (Color clr in m_aclr) {
bwtr.Write(clr.R);
bwtr.Write(clr.G);
bwtr.Write(clr.B);
}
bwtr.Close();
}
/// <summary>
///
/// </summary>
/// <param name="strFile"></param>
/// <returns></returns>
public bool LoadJasc(string strFile) {
m_htbl.Clear(); // in case of Palette reuse
StreamReader stmr = new StreamReader(strFile);
if (stmr.ReadLine() != "JASC-PAL" || stmr.ReadLine() != "0100") {
stmr.Close();
return false;
}
m_aclr = new Color[int.Parse(stmr.ReadLine())];
for (int i = 0; i < m_aclr.Length; i++) {
string[] astr = stmr.ReadLine().Split(' ');
m_aclr[i] = Color.FromArgb(int.Parse(astr[0]), int.Parse(astr[1]), int.Parse(astr[2]));
}
stmr.Close();
return true;
}
/// <summary>
///
/// </summary>
/// <param name="strFile"></param>
public void SaveJasc(string strFile) {
// Write Jasc palette
Stream stm = new FileStream(strFile, FileMode.Create, FileAccess.Write, FileShare.None);
TextWriter twtr = new StreamWriter(stm);
twtr.WriteLine("JASC-PAL");
twtr.WriteLine("0100");
twtr.WriteLine(m_aclr.Length);
foreach(Color clr in m_aclr)
twtr.WriteLine(clr.R.ToString() + " " + clr.G.ToString() + " " + clr.B.ToString());
twtr.Close();
}
/// <summary>
///
/// </summary>
/// <param name="strFile"></param>
/// <returns></returns>
public bool LoadPhotoshopAct(string strFile) {
m_htbl.Clear(); // in case of Palette reuse
FileStream stm = new FileStream(strFile, FileMode.Open, FileAccess.Read);
if (stm.Length != 768) {
stm.Close();
return false;
}
m_aclr = new Color[256];
for (int i = 0; i < 256; i++) {
byte bRed = (byte)stm.ReadByte();
byte bGreen = (byte)stm.ReadByte();
byte bBlue = (byte)stm.ReadByte();
m_aclr[i] = Color.FromArgb(bRed, bGreen, bBlue);
}
stm.Close();
return true;
}
/// <summary>
/// Save palette in Photoshop Color Table (.ACT) format. This format is extremely
/// simple. 256 entries, 3 bytes each (r, g, b). No count, no header. The output
/// file is always exactly 768 bytes long.
/// </summary>
/// <param name="strFile"></param>
public void SavePhotoshopAct(string strFile) {
// Write binary Photoshop Color Table (.ACT)
Stream stm = new FileStream(strFile, FileMode.Create, FileAccess.Write, FileShare.None);
BinaryWriter bwtr = new BinaryWriter(stm);
foreach (Color clr in m_aclr) {
bwtr.Write(clr.R);
bwtr.Write(clr.G);
bwtr.Write(clr.B);
}
// Pad out to 256 entries
for (int i = m_aclr.Length; i < 256; i++) {
bwtr.Write(0);
bwtr.Write(0);
bwtr.Write(0);
}
bwtr.Close();
}
/// <summary>
///
/// </summary>
/// <param name="clr"></param>
/// <returns></returns>
public int FindClosestEntry(Color clr) {
// If not sure of consistency with palette, clear the hash table
if (m_fClearHash)
m_htbl.Clear();
// Is this mapping available already?
int key = clr.GetHashCode();
if (m_htbl.ContainsKey(key))
return (int)m_htbl[key];
// Find the entry, the long way
int nLowest = 256 * 256 * 3;
int iLowest = 0;
int nR = clr.R;
int nG = clr.G;
int nB = clr.B;
for (int iclr = 0; iclr < m_aclr.Length; iclr++) {
Color clrPal = m_aclr[iclr];
int dR = clrPal.R - nR;
int dG = clrPal.G - nG;
int dB = clrPal.B - nB;
int nD = dR * dR + dG * dG + dB * dB;
if (nD < nLowest) {
nLowest = nD;
iLowest = iclr;
}
}
// Add it to the hash table and return it
m_htbl.Add(key, iLowest);
return iLowest;
}
/// <summary>
/// clr = pal[iclr];
/// </summary>
public Color this[int iclr] {
get {
return m_aclr[iclr];
}
set {
m_fClearHash = true;
m_aclr[iclr] = value;
}
}
/// <summary>
///
/// </summary>
public Color[] Colors {
get {
return (Color[])m_aclr.Clone();
}
set {
m_fClearHash = true;
m_aclr = (Color[])value.Clone();
}
}
/// <summary>
///
/// </summary>
public int Length {
get {
return m_aclr.Length;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Moq;
using NUnit.Framework;
using Nybus.Logging;
using Ploeh.AutoFixture;
// ReSharper disable InvokeAsExtensionMethod
namespace Tests.Logging
{
[TestFixture]
public class LoggerExtensionsTests
{
[TestFixture]
public abstract class LogTestBase
{
protected IFixture Fixture;
protected Mock<ILogger> MockLogger;
[SetUp]
public void InitializeBase()
{
Fixture = new Fixture();
Fixture.Behaviors.Add(new OmitOnRecursionBehavior());
MockLogger = new Mock<ILogger>();
}
}
[TestFixture]
public class LogTests : LogTestBase
{
public IEnumerable<LogLevel> GetAllLogLevels()
{
yield return LogLevel.Verbose;
yield return LogLevel.Debug;
yield return LogLevel.Information;
yield return LogLevel.Warning;
yield return LogLevel.Error;
yield return LogLevel.Critical;
}
[Test]
[TestCaseSource(nameof(GetAllLogLevels))]
public void Log_Object_Error_uses_provided_formatter(LogLevel level)
{
var state = new
{
text = Fixture.Create<string>()
};
var exception = Fixture.Create<Exception>();
var formattedState = Fixture.Create<string>();
bool isFormatted = false;
LoggerExtensions.Log(MockLogger.Object, level, state, exception, (a, e) =>
{
isFormatted = true;
return formattedState;
});
MockLogger.Verify(p=> p.Log(level, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.text)) && (string)d[LoggerExtensions.MessageKey] == formattedState), exception));
Assert.That(isFormatted, Is.True);
}
[Test]
[TestCaseSource(nameof(GetAllLogLevels))]
public void Log_string_adds_message(LogLevel level)
{
var message = Fixture.Create<string>();
LoggerExtensions.Log(MockLogger.Object, level, message);
MockLogger.Verify(p => p.Log(level, It.Is<IDictionary<string, object>>(d => (string) d[LoggerExtensions.MessageKey] == message), null));
}
[Test]
[TestCaseSource(nameof(GetAllLogLevels))]
public void Log_exception_adds_message(LogLevel level)
{
var exception = Fixture.Create<Exception>();
LoggerExtensions.Log(MockLogger.Object, level, exception);
MockLogger.Verify(p => p.Log(level, It.Is<IDictionary<string, object>>(d => (string) d[LoggerExtensions.MessageKey] == exception.ToString()), exception));
}
[Test]
[TestCaseSource(nameof(GetAllLogLevels))]
public void Log_object_uses_provided_formatter(LogLevel level)
{
var state = new
{
text = Fixture.Create<string>()
};
var formattedState = Fixture.Create<string>();
bool isFormatted = false;
LoggerExtensions.Log(MockLogger.Object, level, state, a =>
{
isFormatted = true;
return formattedState;
});
MockLogger.Verify(p => p.Log(level, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.text)) && (string)d[LoggerExtensions.MessageKey] == formattedState), null));
Assert.That(isFormatted, Is.True);
}
[Test]
[TestCaseSource(nameof(GetAllLogLevels))]
public void Log_object_does_not_add_message_when_no_formatter_is_specified(LogLevel level)
{
var state = new
{
text = Fixture.Create<string>()
};
LoggerExtensions.Log(MockLogger.Object, level, state, null);
MockLogger.Verify(p => p.Log(level, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.text)) && !d.ContainsKey(LoggerExtensions.MessageKey)), null));
}
}
[TestFixture]
public class LogVerboseTests : LogTestBase
{
[Test]
public void String_is_forwarded_as_message()
{
string message = Fixture.Create<string>();
LoggerExtensions.LogVerbose(MockLogger.Object, message);
MockLogger.Verify(p => p.Log(LogLevel.Verbose, It.Is<IDictionary<string, object>>(d => d.ContainsKey(LoggerExtensions.MessageKey)), null));
}
[Test]
public void String_exception_is_forwarded_as_message()
{
string message = Fixture.Create<string>();
Exception exception = Fixture.Create<Exception>();
LoggerExtensions.LogVerbose(MockLogger.Object, message, exception);
MockLogger.Verify(p => p.Log(LogLevel.Verbose, It.Is<IDictionary<string, object>>(d => d.ContainsKey(LoggerExtensions.MessageKey)), exception));
}
[Test]
public void Object_exception_is_forwarded_in_dictionary()
{
var state = new
{
text = Fixture.Create<string>(),
data = Fixture.Create<string>()
};
var formattedState = Fixture.Create<string>();
Exception exception = Fixture.Create<Exception>();
LoggerExtensions.LogVerbose(MockLogger.Object, state, exception, (a, e) => formattedState);
MockLogger.Verify(p => p.Log(LogLevel.Verbose, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.data)) && d.ContainsKey(nameof(state.text)) && (string) d[LoggerExtensions.MessageKey] == formattedState), exception));
}
[Test]
public void Exception_is_forwarded()
{
Exception exception = Fixture.Create<Exception>();
LoggerExtensions.LogVerbose(MockLogger.Object, exception);
MockLogger.Verify(p => p.Log(LogLevel.Verbose, It.Is<IDictionary<string, object>>(d => (string) d[LoggerExtensions.MessageKey] == exception.ToString()), exception));
}
[Test]
public void Object_is_forwarded_in_dictionary()
{
var state = new
{
text = Fixture.Create<string>(),
data = Fixture.Create<string>()
};
var formattedState = Fixture.Create<string>();
LoggerExtensions.LogVerbose(MockLogger.Object, state, a => formattedState);
MockLogger.Verify(p => p.Log(LogLevel.Verbose, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.data)) && d.ContainsKey(nameof(state.text)) && (string)d[LoggerExtensions.MessageKey] == formattedState), null));
}
}
[TestFixture]
public class LogWarningTests : LogTestBase
{
[Test]
public void String_is_forwarded_as_message()
{
string message = Fixture.Create<string>();
LoggerExtensions.LogWarning(MockLogger.Object, message);
MockLogger.Verify(p => p.Log(LogLevel.Warning, It.Is<IDictionary<string, object>>(d => d.ContainsKey(LoggerExtensions.MessageKey)), null));
}
[Test]
public void String_exception_is_forwarded_as_message()
{
string message = Fixture.Create<string>();
Exception exception = Fixture.Create<Exception>();
LoggerExtensions.LogWarning(MockLogger.Object, message, exception);
MockLogger.Verify(p => p.Log(LogLevel.Warning, It.Is<IDictionary<string, object>>(d => d.ContainsKey(LoggerExtensions.MessageKey)), exception));
}
[Test]
public void Object_exception_is_forwarded_in_dictionary()
{
var state = new
{
text = Fixture.Create<string>(),
data = Fixture.Create<string>()
};
Exception exception = Fixture.Create<Exception>();
var formattedState = Fixture.Create<string>();
LoggerExtensions.LogWarning(MockLogger.Object, state, exception, (a, e) => formattedState);
MockLogger.Verify(p => p.Log(LogLevel.Warning, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.data)) && d.ContainsKey(nameof(state.text)) && (string)d[LoggerExtensions.MessageKey] == formattedState), exception));
}
[Test]
public void Exception_is_forwarded()
{
Exception exception = Fixture.Create<Exception>();
LoggerExtensions.LogWarning(MockLogger.Object, exception);
MockLogger.Verify(p => p.Log(LogLevel.Warning, It.Is<IDictionary<string, object>>(d => (string) d[LoggerExtensions.MessageKey] == exception.ToString()), exception));
}
[Test]
public void Object_is_forwarded_in_dictionary()
{
var state = new
{
text = Fixture.Create<string>(),
data = Fixture.Create<string>()
};
var formattedState = Fixture.Create<string>();
LoggerExtensions.LogWarning(MockLogger.Object, state, a => formattedState);
MockLogger.Verify(p => p.Log(LogLevel.Warning, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.data)) && d.ContainsKey(nameof(state.text)) && (string)d[LoggerExtensions.MessageKey] == formattedState), null));
}
}
[TestFixture]
public class LogDebugTests : LogTestBase
{
[Test]
public void String_is_forwarded_as_message()
{
string message = Fixture.Create<string>();
LoggerExtensions.LogDebug(MockLogger.Object, message);
MockLogger.Verify(p => p.Log(LogLevel.Debug, It.Is<IDictionary<string, object>>(d => d.ContainsKey(LoggerExtensions.MessageKey)), null));
}
[Test]
public void String_exception_is_forwarded_as_message()
{
string message = Fixture.Create<string>();
Exception exception = Fixture.Create<Exception>();
LoggerExtensions.LogDebug(MockLogger.Object, message, exception);
MockLogger.Verify(p => p.Log(LogLevel.Debug, It.Is<IDictionary<string, object>>(d => d.ContainsKey(LoggerExtensions.MessageKey)), exception));
}
[Test]
public void Object_exception_is_forwarded_in_dictionary()
{
var state = new
{
text = Fixture.Create<string>(),
data = Fixture.Create<string>()
};
Exception exception = Fixture.Create<Exception>();
var formattedState = Fixture.Create<string>();
LoggerExtensions.LogDebug(MockLogger.Object, state, exception, (a,e) => formattedState);
MockLogger.Verify(p => p.Log(LogLevel.Debug, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.data)) && d.ContainsKey(nameof(state.text)) && (string)d[LoggerExtensions.MessageKey] == formattedState), exception));
}
[Test]
public void Exception_is_forwarded()
{
Exception exception = Fixture.Create<Exception>();
LoggerExtensions.LogDebug(MockLogger.Object, exception);
MockLogger.Verify(p => p.Log(LogLevel.Debug, It.Is<IDictionary<string, object>>(d => (string) d[LoggerExtensions.MessageKey] == exception.ToString()), exception));
}
[Test]
public void Object_is_forwarded_in_dictionary()
{
var state = new
{
text = Fixture.Create<string>(),
message = Fixture.Create<string>()
};
var formattedState = Fixture.Create<string>();
LoggerExtensions.LogDebug(MockLogger.Object, state, a => formattedState);
MockLogger.Verify(p => p.Log(LogLevel.Debug, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.message)) && d.ContainsKey(nameof(state.text)) && (string)d[LoggerExtensions.MessageKey]== formattedState), null));
}
}
[TestFixture]
public class LogInformationTests : LogTestBase
{
[Test]
public void String_is_forwarded_as_message()
{
string message = Fixture.Create<string>();
LoggerExtensions.LogInformation(MockLogger.Object, message);
MockLogger.Verify(p => p.Log(LogLevel.Information, It.Is<IDictionary<string, object>>(d => d.ContainsKey(LoggerExtensions.MessageKey)), null));
}
[Test]
public void String_exception_is_forwarded_as_message()
{
string message = Fixture.Create<string>();
Exception exception = Fixture.Create<Exception>();
LoggerExtensions.LogInformation(MockLogger.Object, message, exception);
MockLogger.Verify(p => p.Log(LogLevel.Information, It.Is<IDictionary<string, object>>(d => d.ContainsKey(LoggerExtensions.MessageKey)), exception));
}
[Test]
public void Object_exception_is_forwarded_in_dictionary()
{
var state = new
{
text = Fixture.Create<string>(),
data = Fixture.Create<string>()
};
var formattedState = Fixture.Create<string>();
Exception exception = Fixture.Create<Exception>();
LoggerExtensions.LogInformation(MockLogger.Object, state, exception,(a,e)=>formattedState);
MockLogger.Verify(p => p.Log(LogLevel.Information, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.data)) && d.ContainsKey(nameof(state.text)) && (string) d[LoggerExtensions.MessageKey] == formattedState), exception));
}
[Test]
public void Exception_is_forwarded()
{
Exception exception = Fixture.Create<Exception>();
LoggerExtensions.LogInformation(MockLogger.Object, exception);
MockLogger.Verify(p => p.Log(LogLevel.Information, It.Is<IDictionary<string, object>>(d => (string) d[LoggerExtensions.MessageKey] == exception.ToString()), exception));
}
[Test]
public void Object_is_forwarded_in_dictionary()
{
var state = new
{
text = Fixture.Create<string>(),
data = Fixture.Create<string>()
};
var formattedState = Fixture.Create<string>();
LoggerExtensions.LogInformation(MockLogger.Object, state, a => formattedState);
MockLogger.Verify(p => p.Log(LogLevel.Information, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.data)) && d.ContainsKey(nameof(state.text))), null));
}
}
[TestFixture]
public class LogErrorTests : LogTestBase
{
[Test]
public void String_is_forwarded_as_message()
{
string message = Fixture.Create<string>();
LoggerExtensions.LogError(MockLogger.Object, message);
MockLogger.Verify(p => p.Log(LogLevel.Error, It.Is<IDictionary<string, object>>(d => d.ContainsKey(LoggerExtensions.MessageKey)), null));
}
[Test]
public void String_exception_is_forwarded_as_message()
{
string message = Fixture.Create<string>();
Exception exception = Fixture.Create<Exception>();
LoggerExtensions.LogError(MockLogger.Object, message, exception);
MockLogger.Verify(p => p.Log(LogLevel.Error, It.Is<IDictionary<string, object>>(d => d.ContainsKey(LoggerExtensions.MessageKey)), exception));
}
[Test]
public void Object_exception_is_forwarded_in_dictionary()
{
var state = new
{
text = Fixture.Create<string>(),
data = Fixture.Create<string>()
};
Exception exception = Fixture.Create<Exception>();
var formattedState = Fixture.Create<string>();
LoggerExtensions.LogError(MockLogger.Object, state, exception, (a,e)=>formattedState);
MockLogger.Verify(p => p.Log(LogLevel.Error, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.data)) && d.ContainsKey(nameof(state.text)) && (string) d[LoggerExtensions.MessageKey] == formattedState), exception));
}
[Test]
public void Exception_is_forwarded()
{
Exception exception = Fixture.Create<Exception>();
LoggerExtensions.LogError(MockLogger.Object, exception);
MockLogger.Verify(p => p.Log(LogLevel.Error, It.Is<IDictionary<string, object>>(d => (string) d[LoggerExtensions.MessageKey] == exception.ToString()), exception));
}
[Test]
public void Object_is_forwarded_in_dictionary()
{
var state = new
{
text = Fixture.Create<string>(),
data = Fixture.Create<string>()
};
var formattedState = Fixture.Create<string>();
LoggerExtensions.LogError(MockLogger.Object, state, a => formattedState);
MockLogger.Verify(p => p.Log(LogLevel.Error, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.data)) && d.ContainsKey(nameof(state.text)) && (string) d[LoggerExtensions.MessageKey] == formattedState), null));
}
}
[TestFixture]
public class LogCriticalTests : LogTestBase
{
[Test]
public void String_is_forwarded_as_message()
{
string message = Fixture.Create<string>();
LoggerExtensions.LogCritical(MockLogger.Object, message);
MockLogger.Verify(p => p.Log(LogLevel.Critical, It.Is<IDictionary<string, object>>(d => d.ContainsKey(LoggerExtensions.MessageKey)), null));
}
[Test]
public void String_exception_is_forwarded_as_message()
{
string message = Fixture.Create<string>();
Exception exception = Fixture.Create<Exception>();
LoggerExtensions.LogCritical(MockLogger.Object, message, exception);
MockLogger.Verify(p => p.Log(LogLevel.Critical, It.Is<IDictionary<string, object>>(d => d.ContainsKey(LoggerExtensions.MessageKey)), exception));
}
[Test]
public void Object_exception_is_forwarded_in_dictionary()
{
var state = new
{
text = Fixture.Create<string>(),
data = Fixture.Create<string>()
};
Exception exception = Fixture.Create<Exception>();
var formattedState = Fixture.Create<string>();
LoggerExtensions.LogCritical(MockLogger.Object, state, exception, (a,e)=>formattedState);
MockLogger.Verify(p => p.Log(LogLevel.Critical, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.data)) && d.ContainsKey(nameof(state.text)) && (string)d[LoggerExtensions.MessageKey] == formattedState), exception));
}
[Test]
public void Exception_is_forwarded()
{
Exception exception = Fixture.Create<Exception>();
LoggerExtensions.LogCritical(MockLogger.Object, exception);
MockLogger.Verify(p => p.Log(LogLevel.Critical, It.Is<IDictionary<string, object>>(d => (string) d[LoggerExtensions.MessageKey] == exception.ToString()), exception));
}
[Test]
public void Object_is_forwarded_in_dictionary()
{
var state = new
{
text = Fixture.Create<string>(),
data = Fixture.Create<string>()
};
var formattedState = Fixture.Create<string>();
LoggerExtensions.LogCritical(MockLogger.Object, state, a => formattedState);
MockLogger.Verify(p => p.Log(LogLevel.Critical, It.Is<IDictionary<string, object>>(d => d.ContainsKey(nameof(state.data)) && d.ContainsKey(nameof(state.text)) && (string)d[LoggerExtensions.MessageKey] == formattedState), null));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using Sodium;
namespace Tests.sodium
{
[TestFixture]
public class BehaviorTester
{
[TearDown]
public void TearDown()
{
GC.Collect();
Thread.Sleep(100);
}
[Test]
public void TestHold()
{
var e = new EventSink<int>();
Behavior<int> b = e.Hold(0);
var @out = new List<int>();
Listener l = b.Updates().Listen(new Handler<int> { Run = x => @out.Add(x) });
e.Send(2);
e.Send(9);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 2, 9 }, @out.Select(x => (int)x));
}
[Test]
public void TestSnapshot()
{
var b = new BehaviorSink<int>(0);
var trigger = new EventSink<long>();
var @out = new List<string>();
var l = trigger.Snapshot(b, (x, y) => x + " " + y)
.Listen(new Handler<string> { Run = x => @out.Add(x) });
trigger.Send(100L);
b.Send(2);
trigger.Send(200L);
b.Send(9);
b.Send(1);
trigger.Send(300L);
l.Unlisten();
CollectionAssert.AreEqual(new[] { "100 0", "200 2", "300 1" }, @out);
}
[Test]
public void TestValues()
{
var b = new BehaviorSink<int>(9);
var @out = new List<int>();
var l = b.Value().Listen(x => @out.Add(x));
b.Send(2);
b.Send(7);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 9, 2, 7 }, @out);
}
[Test]
public void TestConstantBehavior()
{
var b = new Behavior<int>(12);
var @out = new List<int>();
Listener l = b.Value().Listen(x => { @out.Add(x); });
l.Unlisten();
CollectionAssert.AreEqual(new[] { 12 }, @out);
}
[Test]
public void TestValuesThenMap()
{
var b = new BehaviorSink<int>(9);
var @out = new List<int>();
Listener l = b.Value().Map<int>(x => x + 100).Listen(x => { @out.Add(x); });
b.Send(2);
b.Send(7);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 109, 102, 107 }, @out);
}
/**
* This is used for tests where value() produces a single initial value on listen,
* and then we double that up by causing that single initial event to be repeated.
* This needs testing separately, because the code must be done carefully to achieve
* this.
*/
private static Event<int> DoubleUp(Event<int> ev)
{
return Event<int>.Merge(ev, ev);
}
[Test]
public void TestValuesTwiceThenMap()
{
var b = new BehaviorSink<int>(9);
var @out = new List<int>();
Listener l = DoubleUp(b.Value()).Map<int>(x => x + 100).Listen(x => { @out.Add(x); });
b.Send(2);
b.Send(7);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 109, 109, 102, 102, 107, 107 }, @out);
}
[Test]
public void TestValuesThenCoalesce()
{
var b = new BehaviorSink<int>(9);
var @out = new List<int>();
Listener l = b.Value().Coalesce((fst, snd) => snd).Listen(x => { @out.Add(x); });
b.Send(2);
b.Send(7);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 9, 2, 7 }, @out);
}
[Test]
public void TestValuesTwiceThenCoalesce()
{
var b = new BehaviorSink<int>(9);
var @out = new List<int>();
Listener l = DoubleUp(b.Value()).Coalesce((fst, snd) => fst + snd).Listen(x => { @out.Add(x); });
b.Send(2);
b.Send(7);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 18, 4, 14 }, @out);
}
[Test]
public void TestValuesThenSnapshot()
{
var bi = new BehaviorSink<int>(9);
var bc = new BehaviorSink<char>('a');
var @out = new List<char>();
Listener l = bi.Value().Snapshot(bc).Listen(x => { @out.Add(x); });
bc.Send('b');
bi.Send(2);
bc.Send('c');
bi.Send(7);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 'a', 'b', 'c' }, @out);
}
[Test]
public void TestValuesTwiceThenSnapshot()
{
var bi = new BehaviorSink<int>(9);
var bc = new BehaviorSink<char>('a');
var @out = new List<char>();
Listener l = DoubleUp(bi.Value()).Snapshot(bc).Listen(x => { @out.Add(x); });
bc.Send('b');
bi.Send(2);
bc.Send('c');
bi.Send(7);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 'a', 'a', 'b', 'b', 'c', 'c' }, @out);
}
[Test]
public void TestValuesThenMerge()
{
var bi = new BehaviorSink<int>(9);
var bj = new BehaviorSink<int>(2);
var @out = new List<int>();
Listener l = Event<int>.MergeWith((x, y) => x + y, bi.Value(), bj.Value())
.Listen(x => { @out.Add(x); });
bi.Send(1);
bj.Send(4);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 11, 1, 4 }, @out);
}
[Test]
public void TestValuesThenFilter()
{
var b = new BehaviorSink<int>(9);
var @out = new List<int>();
Listener l = b.Value().Filter(a => true).Listen(x => { @out.Add(x); });
b.Send(2);
b.Send(7);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 9, 2, 7 }, @out);
}
[Test]
public void TestValuesTwiceThenFilter()
{
var b = new BehaviorSink<int>(9);
var @out = new List<int>();
Listener l = DoubleUp(b.Value()).Filter(a => true).Listen(x => { @out.Add(x); });
b.Send(2);
b.Send(7);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 9, 9, 2, 2, 7, 7 }, @out);
}
[Test]
public void TestValuesThenOnce()
{
var b = new BehaviorSink<int>(9);
var @out = new List<int>();
Listener l = b.Value().Once().Listen(x => { @out.Add(x); });
b.Send(2);
b.Send(7);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 9 }, @out);
}
[Test]
public void TestValuesTwiceThenOnce()
{
var b = new BehaviorSink<int>(9);
var @out = new List<int>();
Listener l = DoubleUp(b.Value()).Once().Listen(x => { @out.Add(x); });
b.Send(2);
b.Send(7);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 9 }, @out);
}
[Test]
public void TestValuesLateListen()
{
var b = new BehaviorSink<int>(9);
var @out = new List<int>();
Event<int> value = b.Value();
b.Send(8);
Listener l = value.Listen(x => { @out.Add(x); });
b.Send(2);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 8, 2 }, @out);
}
[Test]
public void TestMapB()
{
var b = new BehaviorSink<int>(6);
var @out = new List<String>();
Listener l = b.Map(x => x.ToString())
.Value().Listen(x => { @out.Add(x); });
b.Send(8);
l.Unlisten();
CollectionAssert.AreEqual(new[] { "6", "8" }, @out);
}
[Test]
public void TestMapBLateListen()
{
var b = new BehaviorSink<int>(6);
var @out = new List<String>();
Behavior<String> bm = b.Map(x => x.ToString());
b.Send(2);
Listener l = bm.Value().Listen(x => { @out.Add(x); });
b.Send(8);
l.Unlisten();
CollectionAssert.AreEqual(new[] { "2", "8" }, @out);
}
[Test]
public void TestTransaction()
{
var calledBack = new bool[1];
Transaction.Run(trans => trans.Prioritized(Node.Null, trans2 => { calledBack[0] = true; }));
Assert.That(calledBack[0], Is.True);
}
[Test]
public void TestApply()
{
var bf = new BehaviorSink<Func<long, String>>(b => "1 " + b);
var ba = new BehaviorSink<long>(5L);
var @out = new List<String>();
Listener l = Behavior<long>.Apply(bf, ba).Value().Listen(x => { @out.Add(x); });
bf.Send(b => "12 " + b);
ba.Send(6L);
l.Unlisten();
CollectionAssert.AreEqual(new[] { "1 5", "12 5", "12 6" }, @out);
}
[Test]
public void TestLift()
{
var a = new BehaviorSink<int>(1);
var b = new BehaviorSink<long>(5L);
var @out = new List<String>();
Listener l = Behavior<int>.Lift(
(x, y) => x + " " + y,
a,
b
).Value().Listen(x => { @out.Add(x); });
a.Send(12);
b.Send(6L);
l.Unlisten();
CollectionAssert.AreEqual(new[] { "1 5", "12 5", "12 6" }, @out);
}
[Test]
public void TestLiftGlitch()
{
var a = new BehaviorSink<int>(1);
Behavior<int> a3 = a.Map<int>(x => x * 3);
Behavior<int> a5 = a.Map<int>(x => x * 5);
Behavior<String> b = Behavior<int>.Lift((x, y) => x + " " + y, a3, a5);
var @out = new List<String>();
Listener l = b.Value().Listen(x => { @out.Add(x); });
a.Send(2);
l.Unlisten();
CollectionAssert.AreEqual(new[] { "3 5", "6 10" }, @out);
}
[Test]
public void TestHoldIsDelayed()
{
var e = new EventSink<int>();
Behavior<int> h = e.Hold(0);
Event<String> pair = e.Snapshot(h, (a, b) => a + " " + b);
var @out = new List<String>();
Listener l = pair.Listen(x => { @out.Add(x); });
e.Send(2);
e.Send(3);
l.Unlisten();
CollectionAssert.AreEqual(new[] { "2 0", "3 2" }, @out);
}
class SB
{
public SB(string a, string b, Behavior<string> sw)
{
A = a;
B = b;
Sw = sw;
}
public readonly string A;
public readonly string B;
public readonly Behavior<string> Sw;
}
[Test]
public void TestSwitchB()
{
var esb = new EventSink<SB>();
// Split each field @out of SB so we can update multiple behaviours in a
// single transaction.
Behavior<string> ba = esb.Map(s => s.A).FilterNotNull().Hold("A");
Behavior<string> bb = esb.Map(s => s.B).FilterNotNull().Hold("a");
Behavior<Behavior<string>> bsw = esb.Map(s => s.Sw).FilterNotNull().Hold(ba);
Behavior<string> bo = Behavior<string>.SwitchB(bsw);
var @out = new List<string>();
Listener l = bo.Value().Listen(c => { @out.Add(c); });
esb.Send(new SB("B", "b", null));
esb.Send(new SB("C", "c", bb));
esb.Send(new SB("D", "d", null));
esb.Send(new SB("E", "e", ba));
esb.Send(new SB("F", "f", null));
esb.Send(new SB(null, null, bb));
esb.Send(new SB(null, null, ba));
esb.Send(new SB("G", "g", bb));
esb.Send(new SB("H", "h", ba));
esb.Send(new SB("I", "i", ba));
l.Unlisten();
CollectionAssert.AreEqual(new[] { "A", "B", "c", "d", "E", "F", "f", "F", "g", "H", "I" }, @out);
}
class SE
{
public SE(char a, char b, Event<char> sw)
{
A = a;
B = b;
Sw = sw;
}
public readonly char A;
public readonly char B;
public readonly Event<char> Sw;
}
[Test]
public void TestSwitchE()
{
var ese = new EventSink<SE>();
Event<char> ea = ese.Map(s => s.A).FilterNotNull();
Event<char> eb = ese.Map(s => s.B).FilterNotNull();
Behavior<Event<char>> bsw = ese.Map(s => s.Sw).FilterNotNull().Hold(ea);
var @out = new List<char>();
Event<char> eo = Behavior<char>.SwitchE(bsw);
Listener l = eo.Listen(@out.Add);
ese.Send(new SE('A', 'a', null));
ese.Send(new SE('B', 'b', null));
ese.Send(new SE('C', 'c', eb));
ese.Send(new SE('D', 'd', null));
ese.Send(new SE('E', 'e', ea));
ese.Send(new SE('F', 'f', null));
ese.Send(new SE('G', 'g', eb));
ese.Send(new SE('H', 'h', ea));
ese.Send(new SE('I', 'i', ea));
l.Unlisten();
CollectionAssert.AreEqual(new[] { 'A', 'B', 'C', 'd', 'e', 'F', 'G', 'h', 'I' }, @out);
}
[Test]
public void TestLoopBehavior()
{
var ea = new EventSink<int>();
Behavior<int> sum_out = Transaction.Run(() =>
{
var sum = new BehaviorLoop<int>();
Behavior<int> sumOut = ea.Snapshot<int, int>(sum, (x, y) => x + y).Hold(0);
sum.Loop(sumOut);
return sumOut;
});
var @out = new List<int>();
Listener l = sum_out.Value().Listen(x => { @out.Add(x); });
ea.Send(2);
ea.Send(3);
ea.Send(1);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 0, 2, 5, 6 }, @out);
Assert.That((int)sum_out.Sample(), Is.EqualTo(6));
}
[Test]
public void TestCollect()
{
var ea = new EventSink<int>();
var @out = new List<int>();
Behavior<int> sum = ea.Hold(100).Collect(
(int)0,
//(a,s) => new Tuple2(a+s, a+s)
(a, s) => new Tuple<int, int>(a + s, a + s));
Listener l = sum.Value().Listen(x => { @out.Add(x); });
ea.Send(5);
ea.Send(7);
ea.Send(1);
ea.Send(2);
ea.Send(3);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 100, 105, 112, 113, 115, 118 }, @out);
}
[Test]
public void TestAccum()
{
var ea = new EventSink<int>();
var @out = new List<int>();
Behavior<int> sum = ea.Accum<int>(100, (a, s) => a + s);
Listener l = sum.Value().Listen(x => { @out.Add(x); });
ea.Send(5);
ea.Send(7);
ea.Send(1);
ea.Send(2);
ea.Send(3);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 100, 105, 112, 113, 115, 118 }, @out);
}
[Test]
public void TestLoopValueSnapshot()
{
var @out = new List<string>();
Event<String> eSnap = Transaction.Run(() =>
{
var a = new Behavior<string>("lettuce");
var b = new BehaviorLoop<string>();
Event<String> eSnap_ = a.Value().Snapshot(b, (aa, bb) => aa + " " + bb);
b.Loop(new Behavior<String>("cheese"));
return eSnap_;
});
Listener l = eSnap.Listen((x) => { @out.Add(x); });
l.Unlisten();
CollectionAssert.AreEqual(new[] { "lettuce cheese" }, @out);
}
[Test]
public void TestLoopValueHold()
{
var @out = new List<string>();
Behavior<String> value = Transaction.Run(() =>
{
var a = new BehaviorLoop<string>();
Behavior<String> value_ = a.Value().Hold("onion");
a.Loop(new Behavior<String>("cheese"));
return value_;
});
var eTick = new EventSink<string>();
Listener l = eTick.Snapshot(value).Listen(x => { @out.Add(x); });
eTick.Send(UnitEnum.Unit);
l.Unlisten();
CollectionAssert.AreEqual(new[] { "cheese" }, @out);
}
[Test]
public void TestLiftLoop()
{
var @out = new List<string>();
var b = new BehaviorSink<string>("kettle");
Behavior<String> c = Transaction.Run(() =>
{
var a = new BehaviorLoop<string>();
Behavior<String> c_ = Behavior<string>.Lift(
(aa, bb) => aa + " " + bb,
a, b);
a.Loop(new Behavior<String>("tea"));
return c_;
});
Listener l = c.Value().Listen(x => { @out.Add(x); });
b.Send("caddy");
l.Unlisten();
CollectionAssert.AreEqual(new[] { "tea kettle", "tea caddy" }, @out);
}
}
}
| |
//#define ASTARDEBUG //Draws a ray for each node visited
using UnityEngine;
using System;
using System.Collections.Generic;
namespace Pathfinding {
/** Finds all nodes within a specified distance from the start.
* This class will search outwards from the start point and find all nodes which it costs less than ConstantPath.maxGScore to reach, this is usually the same as the distance to them multiplied with 1000
*
* The path can be called like:
* \code
* //Here you create a new path and set how far it should search. Null is for the callback, but the seeker will handle that
* ConstantPath cpath = ConstantPath.Construct (transform.position, 2000, null);
* //Set the seeker to search for the path (where mySeeker is a variable referencing a Seeker component)
* mySeeker.StartPath (cpath, myCallbackFunction);
* \endcode
*
* Then when getting the callback, all nodes will be stored in the variable ConstantPath.allNodes (remember that you need to cast it from Path to ConstantPath first to get the variable).
*
* This list will be sorted by G score (cost/distance to reach the node), however only the last duplicate of a node in the list is guaranteed to be sorted in this way.
* \shadowimage{constantPath.png}
*
* \ingroup paths
* \astarpro
*
**/
public class ConstantPath : Path {
public GraphNode startNode;
public Vector3 startPoint;
public Vector3 originalStartPoint;
/** Contains all nodes the path found.
* \note Due to the nature of the search, there might be duplicates of some nodes in the array.
* This list will be sorted by G score (cost/distance to reach the node), however only the last duplicate of a node in the list is guaranteed to be sorted in this way.
*/
public List<GraphNode> allNodes;
/** Controls when the path should terminate.
* This is set up automatically in the constructor to an instance of the Pathfinding.EndingConditionDistance class with a \a maxGScore is specified in the constructor.
* If you want to use another ending condition.
* \see Pathfinding.PathEndingCondition for examples
*/
public PathEndingCondition endingCondition;
public override bool FloodingPath {
get {
return true;
}
}
/** Constructs a ConstantPath starting from the specified point.
* \param start From where the path will be started from (the closest node to that point will be used)
* \param maxGScore Searching will be stopped when a node has a G score greater than this
* \param callback Will be called when the path has completed, leave this to null if you use a Seeker to handle calls
*
* Searching will be stopped when a node has a G score (cost to reach it) greater than \a maxGScore */
public static ConstantPath Construct (Vector3 start, int maxGScore, OnPathDelegate callback = null) {
var p = PathPool.GetPath<ConstantPath>();
p.Setup(start, maxGScore, callback);
return p;
}
/** Sets up a ConstantPath starting from the specified point */
protected void Setup (Vector3 start, int maxGScore, OnPathDelegate callback) {
this.callback = callback;
startPoint = start;
originalStartPoint = startPoint;
endingCondition = new EndingConditionDistance(this, maxGScore);
}
public override void OnEnterPool () {
base.OnEnterPool();
if (allNodes != null) Util.ListPool<GraphNode>.Release(allNodes);
}
/** Reset the path to default values.
* Clears the #allNodes list.
* \note This does not reset the #endingCondition.
*
* Also sets #heuristic to Heuristic.None as it is the default value for this path type
*/
public override void Reset () {
base.Reset();
allNodes = Util.ListPool<GraphNode>.Claim();
endingCondition = null;
originalStartPoint = Vector3.zero;
startPoint = Vector3.zero;
startNode = null;
heuristic = Heuristic.None;
}
public override void Prepare () {
nnConstraint.tags = enabledTags;
NNInfo startNNInfo = AstarPath.active.GetNearest(startPoint, nnConstraint);
startNode = startNNInfo.node;
if (startNode == null) {
Error();
LogError("Could not find close node to the start point");
return;
}
}
/** Initializes the path.
* Sets up the open list and adds the first node to it */
public override void Initialize () {
PathNode startRNode = pathHandler.GetPathNode(startNode);
startRNode.node = startNode;
startRNode.pathID = pathHandler.PathID;
startRNode.parent = null;
startRNode.cost = 0;
startRNode.G = GetTraversalCost(startNode);
startRNode.H = CalculateHScore(startNode);
startNode.Open(this, startRNode, pathHandler);
searchedNodes++;
startRNode.flag1 = true;
allNodes.Add(startNode);
//any nodes left to search?
if (pathHandler.HeapEmpty()) {
CompleteState = PathCompleteState.Complete;
return;
}
currentR = pathHandler.PopNode();
}
public override void Cleanup () {
int c = allNodes.Count;
for (int i = 0; i < c; i++) pathHandler.GetPathNode(allNodes[i]).flag1 = false;
}
public override void CalculateStep (long targetTick) {
int counter = 0;
//Continue to search while there hasn't ocurred an error and the end hasn't been found
while (CompleteState == PathCompleteState.NotCalculated) {
searchedNodes++;
//--- Here's the important stuff
//Close the current node, if the current node satisfies the ending condition, the path is finished
if (endingCondition.TargetFound(currentR)) {
CompleteState = PathCompleteState.Complete;
break;
}
if (!currentR.flag1) {
//Add Node to allNodes
allNodes.Add(currentR.node);
currentR.flag1 = true;
}
#if ASTARDEBUG
Debug.DrawRay((Vector3)currentR.node.position, Vector3.up*5, Color.cyan);
#endif
//--- Here the important stuff ends
AstarProfiler.StartFastProfile(4);
//Debug.DrawRay ((Vector3)currentR.node.Position, Vector3.up*2,Color.red);
//Loop through all walkable neighbours of the node and add them to the open list.
currentR.node.Open(this, currentR, pathHandler);
AstarProfiler.EndFastProfile(4);
//any nodes left to search?
if (pathHandler.HeapEmpty()) {
CompleteState = PathCompleteState.Complete;
break;
}
//Select the node with the lowest F score and remove it from the open list
AstarProfiler.StartFastProfile(7);
currentR = pathHandler.PopNode();
AstarProfiler.EndFastProfile(7);
//Check for time every 500 nodes, roughly every 0.5 ms usually
if (counter > 500) {
//Have we exceded the maxFrameTime, if so we should wait one frame before continuing the search since we don't want the game to lag
if (DateTime.UtcNow.Ticks >= targetTick) {
//Return instead of yield'ing, a separate function handles the yield (CalculatePaths)
return;
}
counter = 0;
if (searchedNodes > 1000000) {
throw new Exception("Probable infinite loop. Over 1,000,000 nodes searched");
}
}
counter++;
}
}
}
/** Target is found when the path is longer than a specified value.
* Actually this is defined as when the current node's G score is >= a specified amount (EndingConditionDistance.maxGScore).\n
* The G score is the cost from the start node to the current node, so an area with a higher penalty (weight) will add more to the G score.
* However the G score is usually just the shortest distance from the start to the current node.
*
* \see Pathfinding.ConstantPath which uses this ending condition
*/
public class EndingConditionDistance : PathEndingCondition {
/** Max G score a node may have */
public int maxGScore = 100;
//public EndingConditionDistance () {}
public EndingConditionDistance (Path p, int maxGScore) : base(p) {
this.maxGScore = maxGScore;
}
public override bool TargetFound (PathNode node) {
return node.G >= maxGScore;
}
}
}
| |
//
// Image.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
using Xwt.Backends;
using System.Reflection;
using System.IO;
using System.Collections.Generic;
namespace Xwt.Drawing
{
public class Image: XwtObject, IDisposable
{
internal Size requestedSize;
internal NativeImageRef NativeRef;
internal double requestedAlpha = 1;
internal StyleSet styles;
internal static int[] SupportedScales = { 2 };
internal Image ()
{
}
internal Image (object backend): base (backend)
{
Init ();
}
internal Image (object backend, Toolkit toolkit): base (backend, toolkit)
{
Init ();
}
/// <summary>
/// Creates a new image that is a copy of another image
/// </summary>
/// <param name="image">Image.</param>
public Image (Image image): base (image.Backend, image.ToolkitEngine)
{
NativeRef = image.NativeRef;
requestedSize = image.requestedSize;
requestedAlpha = image.requestedAlpha;
styles = image.styles;
Init ();
}
internal void Init ()
{
if (NativeRef == null) {
NativeRef = new NativeImageRef (Backend, ToolkitEngine);
} else
NativeRef.AddReference ();
}
~Image ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (NativeRef != null)
NativeRef.ReleaseReference (disposing);
}
internal ImageDescription GetImageDescription (Toolkit toolkit)
{
InitForToolkit (toolkit);
return new ImageDescription () {
Alpha = requestedAlpha,
Size = Size,
Backend = Backend,
Styles = styles
};
}
internal void InitForToolkit (Toolkit t)
{
if (ToolkitEngine != t && NativeRef != null) {
var nr = NativeRef.LoadForToolkit (t);
ToolkitEngine = t;
Backend = nr.Backend;
}
}
/// <summary>
/// Loads an image from a resource
/// </summary>
/// <returns>An image</returns>
/// <param name="resource">Resource name</param>
/// <remarks>
/// This method will look for alternative versions of the image with different resolutions.
/// For example, if a resource is named "foo.png", this method will load
/// other resources with the name "foo@XXX.png", where XXX can be any arbitrary string. For example "foo@2x.png".
/// Each of those resources will be considered different versions of the same image.
/// </remarks>
public static Image FromResource (string resource)
{
if (resource == null)
throw new ArgumentNullException ("resource");
return FromResource (Assembly.GetCallingAssembly (), resource);
}
/// <summary>
/// Loads an image from a resource
/// </summary>
/// <returns>An image</returns>
/// <param name="type">Type which identifies the assembly from which to load the image</param>
/// <param name="resource">Resource name</param>
/// <remarks>
/// This method will look for alternative versions of the image with different resolutions.
/// For example, if a resource is named "foo.png", this method will load
/// other resources with the name "foo@XXX.png", where XXX can be any arbitrary string. For example "foo@2x.png".
/// Each of those resources will be considered different versions of the same image.
/// </remarks>
public static Image FromResource (Type type, string resource)
{
if (type == null)
throw new ArgumentNullException ("type");
if (resource == null)
throw new ArgumentNullException ("resource");
return FromResource (type.Assembly, resource);
}
/// <summary>
/// Loads an image from a resource
/// </summary>
/// <returns>An image</returns>
/// <param name="assembly">The assembly from which to load the image</param>
/// <param name="resource">Resource name</param>
/// <remarks>
/// This method will look for alternative versions of the image with different resolutions.
/// For example, if a resource is named "foo.png", this method will load
/// other resources with the name "foo@XXX.png", where XXX can be any arbitrary string. For example "foo@2x.png".
/// Each of those resources will be considered different versions of the same image.
/// </remarks>
public static Image FromResource (Assembly assembly, string resource)
{
if (assembly == null)
throw new ArgumentNullException ("assembly");
if (resource == null)
throw new ArgumentNullException ("resource");
var toolkit = Toolkit.CurrentEngine;
if (toolkit == null)
throw new ToolkitNotInitializedException ();
var loader = new ResourceImageLoader (toolkit, assembly);
return LoadImage (loader, resource, null);
}
/// <summary>
/// Converts an native image object (NSImage on macOS) to an Image
/// </summary>
public static Image FromNativeImage(object nativeImage) {
return new Image(nativeImage);
}
static Image LoadImage (ImageLoader loader, string fileName, ImageTagSet tagFilter)
{
var toolkit = Toolkit.CurrentEngine;
if (toolkit == null)
throw new ToolkitNotInitializedException ();
var img = loader.LoadImage (fileName);
var reqSize = toolkit.ImageBackendHandler.GetSize (img);
var ext = GetExtension (fileName);
var name = fileName.Substring (0, fileName.Length - ext.Length);
var altImages = new List<Tuple<string,ImageTagSet,bool,object>> ();
var tags = Context.RegisteredStyles;
foreach (var r in loader.GetAlternativeFiles (fileName, name, ext)) {
int scale;
ImageTagSet fileTags;
if (ParseImageHints (name, r, ext, out scale, out fileTags) && (tagFilter == null || tagFilter.Equals (fileTags))) {
var rim = loader.LoadImage (r);
if (rim != null)
altImages.Add (new Tuple<string, ImageTagSet, bool, object> (r, fileTags, scale > 1, rim));
}
}
if (altImages.Count > 0) {
altImages.Insert (0, new Tuple<string, ImageTagSet, bool, object> (fileName, ImageTagSet.Empty, false, img));
var list = new List<Tuple<Image,string[]>> ();
foreach (var imageGroup in altImages.GroupBy (t => t.Item2)) {
Image altImg;
if (ext == ".9.png")
altImg = CreateComposedNinePatch (toolkit, imageGroup);
else {
var ib = toolkit.ImageBackendHandler.CreateMultiResolutionImage (imageGroup.Select (i => i.Item4));
altImg = loader.WrapImage (fileName, imageGroup.Key, ib, reqSize);
}
list.Add (new Tuple<Image,string[]> (altImg, imageGroup.Key.AsArray));
}
if (list.Count == 1)
return list [0].Item1;
else {
return new ThemedImage (list, reqSize);
}
} else {
var res = loader.WrapImage (fileName, ImageTagSet.Empty, img, reqSize);
if (ext == ".9.png")
res = new NinePatchImage (res.ToBitmap ());
return res;
}
}
static bool ParseImageHints (string baseName, string fileName, string ext, out int scale, out ImageTagSet tags)
{
scale = 1;
tags = ImageTagSet.Empty;
if (!fileName.StartsWith (baseName, StringComparison.Ordinal) || fileName.Length <= baseName.Length + 1 || (fileName [baseName.Length] != '@' && fileName [baseName.Length] != '~'))
return false;
fileName = fileName.Substring (0, fileName.Length - ext.Length);
int i = baseName.Length;
if (fileName [i] == '~') {
// For example: foo~dark@2x
i++;
var i2 = fileName.IndexOf ('@', i);
if (i2 != -1) {
int i3 = fileName.IndexOf ('x', i2 + 2);
if (i3 == -1 || !int.TryParse (fileName.Substring (i2 + 1, i3 - i2 - 1), out scale))
return false;
} else
i2 = fileName.Length;
tags = new ImageTagSet (fileName.Substring (i, i2 - i));
return true;
}
else {
// For example: foo@2x~dark
i++;
var i2 = fileName.IndexOf ('~', i + 1);
if (i2 == -1)
i2 = fileName.Length;
i2--;
if (i2 < 0 || fileName [i2] != 'x')
return false;
var s = fileName.Substring (i, i2 - i);
if (!int.TryParse (s, out scale)) {
tags = null;
return false;
}
if (i2 + 2 < fileName.Length)
tags = new ImageTagSet (fileName.Substring (i2 + 2));
return true;
}
}
public static Image CreateMultiSizeIcon (IEnumerable<Image> images)
{
if (Toolkit.CurrentEngine == null)
throw new ToolkitNotInitializedException ();
var allImages = images.ToArray ();
if (allImages.Length == 1)
return allImages [0];
if (allImages.Any (i => i is ThemedImage)) {
// If one of the images is themed, then the whole resulting image will be themed.
// To create the new image, we group images with the same theme but different size, and we create a multi-size icon for those.
// The resulting image is the combination of those multi-size icons.
var allThemes = allImages.OfType<ThemedImage> ().SelectMany (i => i.Images).Select (i => new ImageTagSet (i.Item2)).Distinct ().ToArray ();
List<Tuple<Image, string []>> newImages = new List<Tuple<Image, string []>> ();
foreach (var ts in allThemes) {
List<Image> multiSizeImages = new List<Image> ();
foreach (var i in allImages) {
if (i is ThemedImage)
multiSizeImages.Add (((ThemedImage)i).GetImage (ts.AsArray));
else
multiSizeImages.Add (i);
}
var img = CreateMultiSizeIcon (multiSizeImages);
newImages.Add (new Tuple<Image, string []> (img, ts.AsArray));
}
return new ThemedImage (newImages);
} else {
var img = new Image (Toolkit.CurrentEngine.ImageBackendHandler.CreateMultiSizeIcon (allImages.Select (ExtensionMethods.GetBackend)));
if (allImages.All (i => i.NativeRef.HasNativeSource)) {
var sources = allImages.Select (i => i.NativeRef.NativeSource).ToArray ();
img.NativeRef.SetSources (sources);
}
return img;
}
}
public static Image CreateMultiResolutionImage (IEnumerable<Image> images)
{
if (Toolkit.CurrentEngine == null)
throw new ToolkitNotInitializedException ();
return new Image (Toolkit.CurrentEngine.ImageBackendHandler.CreateMultiResolutionImage (images.Select (ExtensionMethods.GetBackend)));
}
public static Image FromFile (string file)
{
var toolkit = Toolkit.CurrentEngine;
if (toolkit == null)
throw new ToolkitNotInitializedException ();
var loader = new FileImageLoader (toolkit);
return LoadImage (loader, file, null);
}
static Image CreateComposedNinePatch (Toolkit toolkit, IEnumerable<Tuple<string,ImageTagSet,bool,object>> altImages)
{
var npImage = new NinePatchImage ();
foreach (var fi in altImages) {
int i = fi.Item1.LastIndexOf ('@');
double scaleFactor;
if (i == -1)
scaleFactor = 1;
else {
int j = fi.Item1.IndexOf ('x', ++i);
if (!double.TryParse (fi.Item1.Substring (i, j - i), out scaleFactor)) {
toolkit.ImageBackendHandler.Dispose (fi.Item4);
continue;
}
}
npImage.AddFrame (new Image (fi.Item4, toolkit).ToBitmap (), scaleFactor);
}
return npImage;
}
public static Image FromStream (Stream stream)
{
var toolkit = Toolkit.CurrentEngine;
if (toolkit == null)
throw new ToolkitNotInitializedException ();
return new Image (toolkit.ImageBackendHandler.LoadFromStream (stream), toolkit);
}
public static Image FromCustomLoader (IImageLoader loader, string fileName)
{
return FromCustomLoader (loader, fileName, null);
}
internal static Image FromCustomLoader (IImageLoader loader, string fileName, ImageTagSet tags)
{
var toolkit = Toolkit.CurrentEngine;
if (toolkit == null)
throw new ToolkitNotInitializedException ();
var ld = new StreamImageLoader (toolkit, loader);
return LoadImage (ld, fileName, tags);
}
static string GetExtension (string fileName)
{
if (fileName.EndsWith (".9.png", StringComparison.Ordinal))
return ".9.png";
else
return Path.GetExtension (fileName);
}
public static Size GetSize (string file)
{
var toolkit = Toolkit.CurrentEngine;
if (toolkit == null)
throw new ToolkitNotInitializedException ();
return toolkit.ImageBackendHandler.GetSize (file);
}
public void Save (string file, ImageFileType fileType)
{
using (var f = File.OpenWrite (file))
Save (f, fileType);
}
public void Save (Stream stream, ImageFileType fileType)
{
ToolkitEngine.ImageBackendHandler.SaveToStream (ToBitmap ().Backend, stream, fileType);
}
/// <summary>
/// Gets a value indicating whether this image has fixed size.
/// </summary>
/// <value><c>true</c> if this image has fixed size; otherwise, <c>false</c>.</value>
/// <remarks>
/// Some kinds of images such as vector images or multiple-size icons don't have a fixed size,
/// and a specific size has to be chosen before they can be used. A size can be chosen by using
/// the WithSize method.
/// </remarks>
public bool HasFixedSize {
get { return !Size.IsZero; }
}
/// <summary>
/// Gets the size of the image
/// </summary>
/// <value>The size of the image, or Size.Zero if the image doesn't have an intrinsic size</value>
public Size Size {
get {
return !requestedSize.IsZero ? requestedSize : GetDefaultSize ();
}
internal set {
requestedSize = value;
}
}
/// <summary>
/// Gets the width of the image
/// </summary>
/// <value>The width.</value>
public double Width {
get { return Size.Width; }
}
/// <summary>
/// Gets the height of the image
/// </summary>
/// <value>The height.</value>
public double Height {
get { return Size.Height; }
}
/// <summary>
/// Applies an alpha filter to the image
/// </summary>
/// <returns>A new image with the alpha filter applied</returns>
/// <param name="alpha">Alpha to apply</param>
/// <remarks>This is a lightweight operation. The alpha filter is applied when the image is rendered.
/// The method doesn't make a copy of the image data.</remarks>
public Image WithAlpha (double alpha)
{
return new Image (this) {
requestedSize = requestedSize,
requestedAlpha = alpha
};
}
/// <summary>
/// Retuns a copy of the image with a specific size
/// </summary>
/// <returns>A new image with the new size</returns>
/// <param name="width">Width.</param>
/// <param name="height">Height.</param>
/// <remarks>
/// This is a lightweight operation. The image is scaled when it is rendered.
/// The method doesn't make a copy of the image data.
/// </remarks>
public Image WithSize (double width, double height)
{
return new Image (this) {
requestedSize = new Size (width, height)
};
}
/// <summary>
/// Retuns a copy of the image with a specific size
/// </summary>
/// <returns>A new image with the new size</returns>
/// <param name="size">The size.</param>
/// <remarks>
/// This is a lightweight operation. The image is scaled when it is rendered.
/// The method doesn't make a copy of the image data.
/// </remarks>
public Image WithSize (Size size)
{
return new Image (this) {
requestedSize = size
};
}
/// <summary>
/// Retuns a copy of the image with a specific size
/// </summary>
/// <returns>A new image with the new size</returns>
/// <param name="squaredSize">Width and height of the image (the image is expected to be squared)</param>
/// <remarks>
/// This is a lightweight operation. The image is scaled when it is rendered.
/// The method doesn't make a copy of the image data.
/// </remarks>
public Image WithSize (double squaredSize)
{
return new Image (this) {
requestedSize = new Size (squaredSize, squaredSize)
};
}
/// <summary>
/// Retuns a copy of the image with a specific size
/// </summary>
/// <returns>A new image with the new size</returns>
/// <param name="size">New size</param>
/// <remarks>
/// This is a lightweight operation. The image is scaled when it is rendered.
/// The method doesn't make a copy of the image data.
/// </remarks>
public Image WithSize (IconSize size)
{
Size s;
switch (size) {
case IconSize.Small: s = new Size (16, 16); break;
case IconSize.Medium: s = new Size (24, 24); break;
case IconSize.Large: s = new Size (32, 32); break;
default: throw new ArgumentOutOfRangeException ("size");
}
return new Image (this) {
requestedSize = s
};
}
internal Size GetFixedSize ()
{
var size = Size;
if (size.IsZero)
throw new InvalidOperationException ("Image size has not been set and the image doesn't have a default size");
return size;
}
/// <summary>
/// Retuns a copy of the image with a set of specific styles
/// </summary>
/// <returns>A new image with the new styles</returns>
/// <param name="styles">Styles to apply</param>
/// <remarks>
/// This is a lightweight operation.
/// The method doesn't make a copy of the image data.
/// </remarks>
public Image WithStyles (params string[] styles)
{
return new Image (this) {
styles = StyleSet.Empty.AddRange (styles)
};
}
/// <summary>
/// Retuns a copy of the image with a size that fits the provided size limits
/// </summary>
/// <returns>The image</returns>
/// <param name="maxWidth">Max width.</param>
/// <param name="maxHeight">Max height.</param>
/// <remarks>
/// This is a lightweight operation. The image is scaled when it is rendered.
/// The method doesn't make a copy of the image data.
/// </remarks>
public Image WithBoxSize (double maxWidth, double maxHeight)
{
var size = GetFixedSize ();
var ratio = Math.Min (maxWidth / size.Width, maxHeight / size.Height);
return new Image (this) {
requestedSize = new Size (size.Width * ratio, size.Height * ratio)
};
}
/// <summary>
/// Retuns a copy of the image with a size that fits the provided size limits
/// </summary>
/// <returns>The image</returns>
/// <param name="maxSize">Max width and height (the image is expected to be squared)</param>
/// <remarks>
/// This is a lightweight operation. The image is scaled when it is rendered.
/// The method doesn't make a copy of the image data.
/// </remarks>
public Image WithBoxSize (double maxSize)
{
return WithBoxSize (maxSize, maxSize);
}
/// <summary>
/// Retuns a copy of the image with a size that fits the provided size limits
/// </summary>
/// <returns>The image</returns>
/// <param name="size">Max width and height</param>
/// <remarks>
/// This is a lightweight operation. The image is scaled when it is rendered.
/// The method doesn't make a copy of the image data.
/// </remarks>
public Image WithBoxSize (Size size)
{
return WithBoxSize (size.Width, size.Height);
}
/// <summary>
/// Retuns a scaled copy of the image
/// </summary>
/// <returns>The image</returns>
/// <param name="scale">Scale to apply to the image size</param>
/// <remarks>
/// This is a lightweight operation. The image is scaled when it is rendered.
/// The method doesn't make a copy of the image data.
/// </remarks>
public Image Scale (double scale)
{
if (!HasFixedSize)
throw new InvalidOperationException ("Image must have a size in order to be scaled");
double w = Size.Width * scale;
double h = Size.Height * scale;
return new Image (this) {
requestedSize = new Size (w, h)
};
}
/// <summary>
/// Retuns a scaled copy of the image
/// </summary>
/// <returns>The image</returns>
/// <param name="scaleX">Scale to apply to the width of the image</param>
/// <param name="scaleY">Scale to apply to the height of the image</param>
/// <remarks>
/// This is a lightweight operation. The image is scaled when it is rendered.
/// The method doesn't make a copy of the image data.
/// </remarks>
public Image Scale (double scaleX, double scaleY)
{
if (!HasFixedSize)
throw new InvalidOperationException ("Image must have a size in order to be scaled");
double w = Size.Width * scaleX;
double h = Size.Height * scaleY;
return new Image (this) {
requestedSize = new Size (w, h)
};
}
/// <summary>
/// Converts the image to a bitmap
/// </summary>
/// <returns>The bitmap.</returns>
/// <param name="format">Bitmap format</param>
public BitmapImage ToBitmap (ImageFormat format = ImageFormat.ARGB32)
{
return ToBitmap (1d);
}
/// <summary>
/// Converts the image to a bitmap
/// </summary>
/// <returns>The bitmap.</returns>
/// <param name="renderTarget">Widget to be used as reference for determining the resolution of the bitmap</param>
/// <param name="format">Bitmap format</param>
public BitmapImage ToBitmap (Widget renderTarget, ImageFormat format = ImageFormat.ARGB32)
{
if (renderTarget.ParentWindow == null)
throw new InvalidOperationException ("renderTarget is not bound to a window");
return ToBitmap (renderTarget.ParentWindow.Screen.ScaleFactor, format);
}
/// <summary>
/// Converts the image to a bitmap
/// </summary>
/// <returns>The bitmap.</returns>
/// <param name="renderTarget">Window to be used as reference for determining the resolution of the bitmap</param>
/// <param name="format">Bitmap format</param>
public BitmapImage ToBitmap (WindowFrame renderTarget, ImageFormat format = ImageFormat.ARGB32)
{
return ToBitmap (renderTarget.Screen.ScaleFactor, format);
}
/// <summary>
/// Converts the image to a bitmap
/// </summary>
/// <returns>The bitmap.</returns>
/// <param name="renderTarget">Screen to be used as reference for determining the resolution of the bitmap</param>
/// <param name="format">Bitmap format</param>
public BitmapImage ToBitmap (Screen renderTarget, ImageFormat format = ImageFormat.ARGB32)
{
return ToBitmap (renderTarget.ScaleFactor, format);
}
/// <summary>
/// Converts the image to a bitmap
/// </summary>
/// <returns>The bitmap.</returns>
/// <param name="scaleFactor">Scale factor of the bitmap</param>
/// <param name="format">Bitmap format</param>
public BitmapImage ToBitmap (double scaleFactor, ImageFormat format = ImageFormat.ARGB32)
{
var s = GetFixedSize ();
var idesc = new ImageDescription {
Alpha = requestedAlpha,
Size = s,
Styles = styles,
Backend = Backend
};
var bmp = ToolkitEngine.ImageBackendHandler.ConvertToBitmap (idesc, scaleFactor, format);
return new BitmapImage (bmp, s, ToolkitEngine);
}
protected virtual Size GetDefaultSize ()
{
return ToolkitEngine.ImageBackendHandler.GetSize (Backend);
}
}
class NativeImageRef
{
object backend;
int referenceCount = 1;
Toolkit toolkit;
NativeImageSource[] sources;
public struct NativeImageSource {
// Source file or resource name
public string Source;
// Assembly that contains the resource
public Assembly ResourceAssembly;
public Func<Stream[]> ImageLoader;
public IImageLoader CustomImageLoader;
public ImageDrawCallback DrawCallback;
public string StockId;
public ImageTagSet Tags;
}
public object Backend {
get { return backend; }
}
public Toolkit Toolkit {
get { return toolkit; }
}
public NativeImageSource NativeSource {
get { return sources[0]; }
}
public bool HasNativeSource {
get { return sources != null; }
}
public void SetSources (NativeImageSource[] sources)
{
this.sources = sources;
}
public void SetFileSource (string file, ImageTagSet tags)
{
sources = new [] {
new NativeImageSource {
Source = file,
Tags = tags
}
};
}
public void SetResourceSource (Assembly asm, string name, ImageTagSet tags)
{
sources = new [] {
new NativeImageSource {
Source = name,
ResourceAssembly = asm,
Tags = tags
}
};
}
public void SetStreamSource (Func<Stream[]> imageLoader)
{
sources = new [] {
new NativeImageSource {
ImageLoader = imageLoader
}
};
}
public void SetCustomLoaderSource (IImageLoader imageLoader, string fileName, ImageTagSet tags)
{
sources = new [] {
new NativeImageSource {
CustomImageLoader = imageLoader,
Source = fileName,
Tags = tags
}
};
}
public void SetCustomDrawSource (ImageDrawCallback drawCallback)
{
sources = new [] {
new NativeImageSource {
DrawCallback = drawCallback
}
};
}
public void SetStockSource (string stockID)
{
sources = new [] {
new NativeImageSource {
StockId = stockID
}
};
}
public int ReferenceCount {
get { return referenceCount; }
}
public NativeImageRef (object backend, Toolkit toolkit)
{
this.backend = backend;
this.toolkit = toolkit;
NextRef = this;
if (toolkit.ImageBackendHandler.DisposeHandleOnUiThread)
ResourceManager.RegisterResource (backend, toolkit.ImageBackendHandler.Dispose);
}
public NativeImageRef LoadForToolkit (Toolkit targetToolkit)
{
if (Toolkit == targetToolkit)
return this;
NativeImageRef newRef = null;
var r = NextRef;
while (r != this) {
if (r.toolkit == targetToolkit) {
newRef = r;
break;
}
r = r.NextRef;
}
if (newRef != null)
return newRef;
object newBackend = null;
if (sources != null) {
var frames = new List<object> ();
foreach (var s in sources) {
if (s.ImageLoader != null) {
var streams = s.ImageLoader ();
try {
if (streams.Length == 1) {
newBackend = targetToolkit.ImageBackendHandler.LoadFromStream (streams [0]);
} else {
var backends = new object [streams.Length];
for (int n = 0; n < backends.Length; n++) {
backends [n] = targetToolkit.ImageBackendHandler.LoadFromStream (streams [n]);
}
newBackend = targetToolkit.ImageBackendHandler.CreateMultiResolutionImage (backends);
}
} finally {
foreach (var st in streams)
st.Dispose ();
}
} else if (s.CustomImageLoader != null) {
targetToolkit.Invoke (() => newBackend = Image.FromCustomLoader (s.CustomImageLoader, s.Source, s.Tags).GetBackend());
} else if (s.ResourceAssembly != null) {
targetToolkit.Invoke (() => newBackend = Image.FromResource (s.ResourceAssembly, s.Source).GetBackend());
}
else if (s.Source != null)
targetToolkit.Invoke (() => newBackend = Image.FromFile (s.Source).GetBackend());
else if (s.DrawCallback != null)
newBackend = targetToolkit.ImageBackendHandler.CreateCustomDrawn (s.DrawCallback);
else if (s.StockId != null)
newBackend = targetToolkit.GetStockIcon (s.StockId).GetBackend ();
else
throw new NotSupportedException ();
frames.Add (newBackend);
}
newBackend = targetToolkit.ImageBackendHandler.CreateMultiSizeIcon (frames);
} else {
using (var s = new MemoryStream ()) {
toolkit.ImageBackendHandler.SaveToStream (backend, s, ImageFileType.Png);
s.Position = 0;
newBackend = targetToolkit.ImageBackendHandler.LoadFromStream (s);
}
}
newRef = new NativeImageRef (newBackend, targetToolkit);
newRef.NextRef = NextRef;
NextRef = newRef;
return newRef;
}
public void AddReference ()
{
System.Threading.Interlocked.Increment (ref referenceCount);
}
public void ReleaseReference (bool disposing)
{
if (System.Threading.Interlocked.Decrement (ref referenceCount) == 0) {
if (disposing) {
if (toolkit.ImageBackendHandler.DisposeHandleOnUiThread)
ResourceManager.FreeResource (backend);
else
toolkit.ImageBackendHandler.Dispose (backend);
} else
ResourceManager.FreeResource (backend);
}
}
/// <summary>
/// Reference to the next native image, for a different toolkit
/// </summary>
public NativeImageRef NextRef { get; set; }
}
class ImageTagSet
{
string tags;
string[] tagsArray;
public static readonly ImageTagSet Empty = new ImageTagSet (new string[0]);
public ImageTagSet (string [] tagsArray)
{
this.tagsArray = tagsArray;
Array.Sort (tagsArray);
}
public bool IsEmpty {
get {
return tagsArray.Length == 0;
}
}
public ImageTagSet (string tags)
{
tagsArray = tags.Split (new [] { '~' }, StringSplitOptions.RemoveEmptyEntries);
Array.Sort (AsArray);
}
public string AsString {
get {
if (tags == null)
tags = string.Join ("~", tagsArray);
return tags;
}
}
public string [] AsArray {
get {
return tagsArray;
}
}
public override bool Equals (object obj)
{
var other = obj as ImageTagSet;
if (other == null || tagsArray.Length != other.tagsArray.Length)
return false;
for (int n = 0; n < tagsArray.Length; n++)
if (tagsArray [n] != other.tagsArray [n])
return false;
return true;
}
public override int GetHashCode ()
{
unchecked {
int c = 0;
foreach (var s in tagsArray)
c %= s.GetHashCode ();
return c;
}
}
}
abstract class ImageLoader
{
public abstract object LoadImage (string fileName);
public abstract IEnumerable<string> GetAlternativeFiles (string fileName, string baseName, string ext);
public abstract Image WrapImage (string fileName, ImageTagSet tags, object img, Size reqSize);
}
class ResourceImageLoader : ImageLoader
{
Assembly assembly;
Toolkit toolkit;
public ResourceImageLoader (Toolkit toolkit, Assembly assembly)
{
this.assembly = assembly;
this.toolkit = toolkit;
}
public override object LoadImage (string fileName)
{
var img = toolkit.ImageBackendHandler.LoadFromResource (assembly, fileName);
if (img == null)
throw new InvalidOperationException ("Resource not found: " + fileName);
return img;
}
public override IEnumerable<string> GetAlternativeFiles (string fileName, string baseName, string ext)
{
return assembly.GetManifestResourceNames ().Where (f =>
f.StartsWith (baseName, StringComparison.Ordinal) &&
f.EndsWith (ext, StringComparison.Ordinal));
}
public override Image WrapImage (string fileName, ImageTagSet tags, object img, Size reqSize)
{
var res = new Image (img, toolkit) {
requestedSize = reqSize
};
res.NativeRef.SetResourceSource (assembly, fileName, tags);
return res;
}
}
class FileImageLoader : ImageLoader
{
Toolkit toolkit;
public FileImageLoader (Toolkit toolkit)
{
this.toolkit = toolkit;
}
public override object LoadImage (string fileName)
{
var img = toolkit.ImageBackendHandler.LoadFromFile (fileName);
if (img == null)
throw new InvalidOperationException ("File not found: " + fileName);
return img;
}
public override IEnumerable<string> GetAlternativeFiles (string fileName, string baseName, string ext)
{
if (!Context.RegisteredStyles.Any ()) {
foreach (var s in Image.SupportedScales) {
var fn = baseName + "@" + s + "x" + ext;
if (File.Exists (fn))
yield return fn;
}
} else {
var files = Directory.GetFiles (Path.GetDirectoryName (fileName), Path.GetFileName (baseName) + "*" + ext);
foreach (var f in files)
yield return f;
}
}
public override Image WrapImage (string fileName, ImageTagSet tags, object img, Size reqSize)
{
var res = new Image (img, toolkit) {
requestedSize = reqSize
};
res.NativeRef.SetFileSource (fileName, tags);
return res;
}
}
class StreamImageLoader : ImageLoader
{
IImageLoader loader;
Toolkit toolkit;
public StreamImageLoader (Toolkit toolkit, IImageLoader loader)
{
this.toolkit = toolkit;
this.loader = loader;
}
public override IEnumerable<string> GetAlternativeFiles (string fileName, string baseName, string ext)
{
return loader.GetAlternativeFiles (fileName, baseName, ext);
}
public override object LoadImage (string fileName)
{
using (var s = loader.LoadImage (fileName))
return toolkit.ImageBackendHandler.LoadFromStream (s);
}
public override Image WrapImage (string fileName, ImageTagSet tags, object img, Size reqSize)
{
var res = new Image (img, toolkit) {
requestedSize = reqSize
};
res.NativeRef.SetCustomLoaderSource (loader, fileName, tags);
return res;
}
}
}
| |
// 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.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using Windows.Web.Http.Headers;
using RTHttpMethod = Windows.Web.Http.HttpMethod;
using RTHttpRequestMessage = Windows.Web.Http.HttpRequestMessage;
using RTHttpResponseMessage = Windows.Web.Http.HttpResponseMessage;
using RTHttpBufferContent = Windows.Web.Http.HttpBufferContent;
using RTHttpStreamContent = Windows.Web.Http.HttpStreamContent;
using RTHttpVersion = Windows.Web.Http.HttpVersion;
using RTIHttpContent = Windows.Web.Http.IHttpContent;
using RTIInputStream = Windows.Storage.Streams.IInputStream;
using RTHttpBaseProtocolFilter = Windows.Web.Http.Filters.HttpBaseProtocolFilter;
namespace System.Net.Http
{
internal class HttpHandlerToFilter : HttpMessageHandler
{
private readonly static DiagnosticListener s_diagnosticListener = new DiagnosticListener(HttpHandlerLoggingStrings.DiagnosticListenerName);
private readonly RTHttpBaseProtocolFilter _next;
private int _filterMaxVersionSet;
internal HttpHandlerToFilter(RTHttpBaseProtocolFilter filter)
{
if (filter == null)
{
throw new ArgumentNullException(nameof(filter));
}
_next = filter;
_filterMaxVersionSet = 0;
}
protected internal override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancel)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
cancel.ThrowIfCancellationRequested();
Guid loggingRequestId = s_diagnosticListener.LogHttpRequest(request);
RTHttpRequestMessage rtRequest = await ConvertRequestAsync(request).ConfigureAwait(false);
RTHttpResponseMessage rtResponse = await _next.SendRequestAsync(rtRequest).AsTask(cancel).ConfigureAwait(false);
// Update in case of redirects
request.RequestUri = rtRequest.RequestUri;
HttpResponseMessage response = ConvertResponse(rtResponse);
response.RequestMessage = request;
s_diagnosticListener.LogHttpResponse(response, loggingRequestId);
return response;
}
private async Task<RTHttpRequestMessage> ConvertRequestAsync(HttpRequestMessage request)
{
RTHttpRequestMessage rtRequest = new RTHttpRequestMessage(new RTHttpMethod(request.Method.Method), request.RequestUri);
// We can only control the Version on the first request message since the WinRT API
// has this property designed as a filter/handler property. In addition the overall design
// of HTTP/2.0 is such that once the first request is using it, all the other requests
// to the same endpoint will use it as well.
if (Interlocked.Exchange(ref _filterMaxVersionSet, 1) == 0)
{
RTHttpVersion maxVersion;
if (request.Version == HttpVersion.Version20)
{
maxVersion = RTHttpVersion.Http20;
}
else if (request.Version == HttpVersion.Version11)
{
maxVersion = RTHttpVersion.Http11;
}
else if (request.Version == HttpVersion.Version10)
{
maxVersion = RTHttpVersion.Http10;
}
else
{
// TODO (#7878): We need to throw an exception here similar to .NET Desktop
// throw new ArgumentException(SR.GetString(SR.net_wrongversion), "value");
//
// But we need to do that checking in the HttpClientHandler object itself.
// and we have that bug as well for the WinHttpHandler version also.
maxVersion = RTHttpVersion.Http11;
}
// The default for WinRT HttpBaseProtocolFilter.MaxVersion is HttpVersion.Http20.
// So, we only have to change it if we don't want HTTP/2.0.
if (maxVersion != RTHttpVersion.Http20)
{
_next.MaxVersion = maxVersion;
}
}
// Headers
foreach (KeyValuePair<string, IEnumerable<string>> headerPair in request.Headers)
{
foreach (string value in headerPair.Value)
{
bool success = rtRequest.Headers.TryAppendWithoutValidation(headerPair.Key, value);
Debug.Assert(success);
}
}
// Properties
foreach (KeyValuePair<string, object> propertyPair in request.Properties)
{
rtRequest.Properties.Add(propertyPair.Key, propertyPair.Value);
}
// Content
if (request.Content != null)
{
rtRequest.Content = await CreateRequestContentAsync(request, rtRequest.Headers).ConfigureAwait(false);
}
return rtRequest;
}
private static async Task<RTIHttpContent> CreateRequestContentAsync(HttpRequestMessage request, HttpRequestHeaderCollection rtHeaderCollection)
{
HttpContent content = request.Content;
RTIHttpContent rtContent;
ArraySegment<byte> buffer;
// If we are buffered already, it is more efficient to send the data directly using the buffer with the
// WinRT HttpBufferContent class than using HttpStreamContent. This also avoids issues caused by
// a design limitation in the System.Runtime.WindowsRuntime System.IO.NetFxToWinRtStreamAdapter.
if (content.TryGetBuffer(out buffer))
{
rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count);
}
else
{
Stream contentStream = await content.ReadAsStreamAsync().ConfigureAwait(false);
if (contentStream is RTIInputStream)
{
rtContent = new RTHttpStreamContent((RTIInputStream)contentStream);
}
else if (contentStream is MemoryStream)
{
var memStream = contentStream as MemoryStream;
if (memStream.TryGetBuffer(out buffer))
{
rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count);
}
else
{
byte[] byteArray = memStream.ToArray();
rtContent = new RTHttpBufferContent(byteArray.AsBuffer(), 0, (uint) byteArray.Length);
}
}
else
{
rtContent = new RTHttpStreamContent(contentStream.AsInputStream());
}
}
// RTHttpBufferContent constructor automatically adds a Content-Length header. RTHttpStreamContent does not.
// Clear any 'Content-Length' header added by the RTHttp*Content objects. We need to clear that now
// and decide later whether we need 'Content-Length' or 'Transfer-Encoding: chunked' headers based on the
// .NET HttpRequestMessage and Content header collections.
rtContent.Headers.ContentLength = null;
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// Desktop System.Net allows both headers to be specified but ends up stripping out
// 'Content-Length' and using chunked semantics. The WinRT APIs throw an exception so
// we need to manually strip out the conflicting header to maintain app compatibility.
if (request.Headers.TransferEncodingChunked.HasValue && request.Headers.TransferEncodingChunked.Value)
{
content.Headers.ContentLength = null;
}
else
{
// Trigger delayed header generation via TryComputeLength. This code is needed due to an outstanding
// bug in HttpContentHeaders.ContentLength. See GitHub Issue #5523.
content.Headers.ContentLength = content.Headers.ContentLength;
}
foreach (KeyValuePair<string, IEnumerable<string>> headerPair in content.Headers)
{
foreach (string value in headerPair.Value)
{
if (!rtContent.Headers.TryAppendWithoutValidation(headerPair.Key, value))
{
// rtContent headers are restricted to a white-list of allowed headers, while System.Net.HttpClient's content headers
// will allow custom headers. If something is not successfully added to the content headers, try adding them to the standard headers.
bool success = rtHeaderCollection.TryAppendWithoutValidation(headerPair.Key, value);
Debug.Assert(success);
}
}
}
return rtContent;
}
private static HttpResponseMessage ConvertResponse(RTHttpResponseMessage rtResponse)
{
HttpResponseMessage response = new HttpResponseMessage((HttpStatusCode)rtResponse.StatusCode);
response.ReasonPhrase = rtResponse.ReasonPhrase;
// Version
if (rtResponse.Version == RTHttpVersion.Http11)
{
response.Version = HttpVersion.Version11;
}
else if (rtResponse.Version == RTHttpVersion.Http10)
{
response.Version = HttpVersion.Version10;
}
else if (rtResponse.Version == RTHttpVersion.Http20)
{
response.Version = HttpVersion.Version20;
}
else
{
response.Version = new Version(0,0);
}
bool success;
// Headers
foreach (KeyValuePair<string, string> headerPair in rtResponse.Headers)
{
if (headerPair.Key.Equals(HttpKnownHeaderNames.SetCookie, StringComparison.OrdinalIgnoreCase))
{
// The Set-Cookie header always comes back with all of the cookies concatenated together.
// For example if the response contains the following:
// Set-Cookie A=1
// Set-Cookie B=2
// Then we will have a single header KeyValuePair of Key=Set-Cookie, Value=A=1, B=2.
// However clients expect these headers to be separated(i.e.
// httpResponseMessage.Headers.GetValues("Set-Cookie") should return two cookies not one
// concatenated together).
success = response.Headers.TryAddWithoutValidation(headerPair.Key, CookieHelper.GetCookiesFromHeader(headerPair.Value));
}
else
{
success = response.Headers.TryAddWithoutValidation(headerPair.Key, headerPair.Value);
}
Debug.Assert(success);
}
// Content
if (rtResponse.Content != null)
{
var rtResponseStream = rtResponse.Content.ReadAsInputStreamAsync().AsTask().Result;
response.Content = new StreamContent(rtResponseStream.AsStreamForRead());
foreach (KeyValuePair<string, string> headerPair in rtResponse.Content.Headers)
{
success = response.Content.Headers.TryAddWithoutValidation(headerPair.Key, headerPair.Value);
Debug.Assert(success);
}
}
return response;
}
}
}
| |
// 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.Xml;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.BackEnd;
using Microsoft.Build.BackEnd.Logging;
using Microsoft.Build.Execution;
using Microsoft.Build.Shared;
using LegacyThreadingData = Microsoft.Build.Execution.LegacyThreadingData;
using Xunit;
namespace Microsoft.Build.UnitTests.BackEnd
{
public class NodeEndpointInProc_Tests
{
private delegate void EndpointOperationDelegate(NodeEndpointInProc endpoint);
private class MockHost : IBuildComponentHost, INodePacketFactory
{
private DataReceivedContext _dataReceivedContext;
private AutoResetEvent _dataReceivedEvent;
private BuildParameters _buildParameters;
/// <summary>
/// Retrieves the LegacyThreadingData associated with a particular component host
/// </summary>
private LegacyThreadingData _legacyThreadingData;
public MockHost()
{
_buildParameters = new BuildParameters();
_dataReceivedEvent = new AutoResetEvent(false);
_legacyThreadingData = new LegacyThreadingData();
}
public ILoggingService LoggingService
{
get
{
throw new NotImplementedException();
}
}
/// <summary>
/// Retrieves the LegacyThreadingData associated with a particular component host
/// </summary>
LegacyThreadingData IBuildComponentHost.LegacyThreadingData
{
get
{
return _legacyThreadingData;
}
}
public string Name
{
get
{
return "NodeEndpointInProc_Tests.MockHost";
}
}
public BuildParameters BuildParameters
{
get
{
return _buildParameters;
}
}
#region IBuildComponentHost Members
public IBuildComponent GetComponent(BuildComponentType type)
{
throw new NotImplementedException();
}
public void RegisterFactory(BuildComponentType type, BuildComponentFactoryDelegate factory)
{
}
#endregion
#region INodePacketFactory Members
public void RegisterPacketHandler(NodePacketType packetType, NodePacketFactoryMethod factory, INodePacketHandler handler)
{
throw new NotImplementedException();
}
public void UnregisterPacketHandler(NodePacketType packetType)
{
throw new NotImplementedException();
}
public void DeserializeAndRoutePacket(int nodeId, NodePacketType packetType, ITranslator translator)
{
throw new NotImplementedException();
}
public void RoutePacket(int nodeId, INodePacket packet)
{
_dataReceivedContext = new DataReceivedContext(Thread.CurrentThread, packet);
_dataReceivedEvent.Set();
}
public DataReceivedContext DataReceivedContext
{
get { return _dataReceivedContext; }
}
public WaitHandle DataReceivedEvent
{
get { return _dataReceivedEvent; }
}
#endregion
}
private class TestPacket : INodePacket
{
#region INodePacket Members
public NodePacketType Type
{
get { throw new NotImplementedException(); }
}
public void Translate(ITranslator translator)
{
throw new NotImplementedException();
}
#endregion
}
private struct LinkStatusContext
{
public readonly Thread thread;
public readonly LinkStatus status;
public LinkStatusContext(Thread thread, LinkStatus status)
{
this.thread = thread;
this.status = status;
}
}
private struct DataReceivedContext
{
public readonly Thread thread;
public readonly INodePacket packet;
public DataReceivedContext(Thread thread, INodePacket packet)
{
this.thread = thread;
this.packet = packet;
}
}
private Dictionary<INodeEndpoint, LinkStatusContext> _linkStatusTable;
private MockHost _host;
[Fact]
public void ConstructionWithValidHost()
{
NodeEndpointInProc.EndpointPair endpoints =
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Synchronous, _host);
endpoints =
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Asynchronous, _host);
}
[Fact]
public void ConstructionSynchronousWithInvalidHost()
{
Assert.Throws<ArgumentNullException>(() =>
{
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Synchronous, null);
}
);
}
[Fact]
public void ConstructionAsynchronousWithInvalidHost()
{
Assert.Throws<ArgumentNullException>(() =>
{
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Asynchronous, null);
}
);
}
/// <summary>
/// Verify that the links:
/// 1. are marked inactive
/// 2. and that attempting to send data while they are
/// inactive throws the expected exception.
/// </summary>
[Fact]
public void InactiveLinkTestSynchronous()
{
NodeEndpointInProc.EndpointPair endpoints =
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Synchronous, _host);
CallOpOnEndpoints(endpoints, VerifyLinkInactive);
CallOpOnEndpoints(endpoints, VerifySendDataInvalidOperation);
CallOpOnEndpoints(endpoints, VerifyDisconnectInvalidOperation);
// The following should not throw
endpoints.ManagerEndpoint.Listen(_host);
endpoints.NodeEndpoint.Connect(_host);
}
/// <summary>
/// Verify that the links are marked inactive and that attempting to send data while they are
/// inactive throws the expected exception.
/// </summary>
[Fact]
public void InactiveLinkTestAsynchronous()
{
NodeEndpointInProc.EndpointPair endpoints =
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Asynchronous, _host);
CallOpOnEndpoints(endpoints, VerifyLinkInactive);
CallOpOnEndpoints(endpoints, VerifySendDataInvalidOperation);
CallOpOnEndpoints(endpoints, VerifyDisconnectInvalidOperation);
// The following should not throw
endpoints.ManagerEndpoint.Listen(_host);
endpoints.NodeEndpoint.Connect(_host);
endpoints.ManagerEndpoint.Disconnect();
}
[Fact]
public void ConnectionTestSynchronous()
{
NodeEndpointInProc.EndpointPair endpoints =
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Synchronous, _host);
endpoints.ManagerEndpoint.OnLinkStatusChanged += LinkStatusChanged;
endpoints.NodeEndpoint.OnLinkStatusChanged += LinkStatusChanged;
// Call listen. This shouldn't have any effect on the link statuses.
endpoints.ManagerEndpoint.Listen(_host);
CallOpOnEndpoints(endpoints, VerifyLinkInactive);
// No link status callback should have occurred.
Assert.False(_linkStatusTable.ContainsKey(endpoints.NodeEndpoint));
Assert.False(_linkStatusTable.ContainsKey(endpoints.ManagerEndpoint));
// Now call connect on the node side. This should activate the link on both ends.
endpoints.NodeEndpoint.Connect(_host);
CallOpOnEndpoints(endpoints, VerifyLinkActive);
// We should have received callbacks informing us of the link change.
Assert.Equal(LinkStatus.Active, _linkStatusTable[endpoints.NodeEndpoint].status);
Assert.Equal(LinkStatus.Active, _linkStatusTable[endpoints.ManagerEndpoint].status);
}
[Fact]
public void DisconnectionTestSynchronous()
{
DisconnectionTestHelper(NodeEndpointInProc.EndpointMode.Synchronous);
}
[Fact]
public void DisconnectionTestAsynchronous()
{
DisconnectionTestHelper(NodeEndpointInProc.EndpointMode.Asynchronous);
}
[Fact]
public void SynchronousData()
{
// Create the endpoints
NodeEndpointInProc.EndpointPair endpoints =
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Synchronous, _host);
// Connect the endpoints
endpoints.ManagerEndpoint.Listen(_host);
endpoints.NodeEndpoint.Connect(_host);
// Create our test packets
INodePacket managerPacket = new TestPacket();
INodePacket nodePacket = new TestPacket();
// Send data from the manager. We expect to receive it from the node endpoint, and it should
// be on the same thread.
endpoints.ManagerEndpoint.SendData(managerPacket);
Assert.Equal(_host.DataReceivedContext.packet, managerPacket);
Assert.Equal(_host.DataReceivedContext.thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId);
// Send data from the node. We expect to receive it from the manager endpoint, and it should
// be on the same thread.
endpoints.NodeEndpoint.SendData(nodePacket);
Assert.Equal(_host.DataReceivedContext.packet, nodePacket);
Assert.Equal(_host.DataReceivedContext.thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId);
}
[Fact]
public void AsynchronousData()
{
// Create the endpoints
NodeEndpointInProc.EndpointPair endpoints =
NodeEndpointInProc.CreateInProcEndpoints(
NodeEndpointInProc.EndpointMode.Asynchronous, _host);
// Connect the endpoints
endpoints.ManagerEndpoint.Listen(_host);
endpoints.NodeEndpoint.Connect(_host);
// Create our test packets
INodePacket managerPacket = new TestPacket();
INodePacket nodePacket = new TestPacket();
// Send data from the manager. We expect to receive it from the node endpoint, and it should
// be on the same thread.
endpoints.ManagerEndpoint.SendData(managerPacket);
if (!_host.DataReceivedEvent.WaitOne(1000))
{
Assert.True(false, "Data not received before timeout expired.");
}
Assert.Equal(_host.DataReceivedContext.packet, managerPacket);
Assert.NotEqual(_host.DataReceivedContext.thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId);
// Send data from the node. We expect to receive it from the manager endpoint, and it should
// be on the same thread.
endpoints.NodeEndpoint.SendData(nodePacket);
if (!_host.DataReceivedEvent.WaitOne(1000))
{
Assert.True(false, "Data not received before timeout expired.");
}
Assert.Equal(_host.DataReceivedContext.packet, nodePacket);
Assert.NotEqual(_host.DataReceivedContext.thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId);
endpoints.ManagerEndpoint.Disconnect();
}
public NodeEndpointInProc_Tests()
{
_linkStatusTable = new Dictionary<INodeEndpoint, LinkStatusContext>();
_host = new MockHost();
}
private void CallOpOnEndpoints(NodeEndpointInProc.EndpointPair pair, EndpointOperationDelegate opDelegate)
{
opDelegate(pair.NodeEndpoint);
opDelegate(pair.ManagerEndpoint);
}
private void VerifyLinkInactive(NodeEndpointInProc endpoint)
{
Assert.Equal(LinkStatus.Inactive, endpoint.LinkStatus); // "Expected LinkStatus to be Inactive"
}
private void VerifyLinkActive(NodeEndpointInProc endpoint)
{
Assert.Equal(LinkStatus.Active, endpoint.LinkStatus); // "Expected LinkStatus to be Active"
}
private void VerifySendDataInvalidOperation(NodeEndpointInProc endpoint)
{
bool caught = false;
try
{
endpoint.SendData(new TestPacket());
}
catch (InternalErrorException)
{
caught = true;
}
Assert.True(caught); // "Did not receive InternalErrorException."
}
private void VerifyDisconnectInvalidOperation(NodeEndpointInProc endpoint)
{
bool caught = false;
try
{
endpoint.Disconnect();
}
catch (InternalErrorException)
{
caught = true;
}
Assert.True(caught); // "Did not receive InternalErrorException."
}
private void DisconnectionTestHelper(NodeEndpointInProc.EndpointMode mode)
{
NodeEndpointInProc.EndpointPair endpoints = SetupConnection(mode);
endpoints.ManagerEndpoint.Disconnect();
VerifyLinksAndCallbacksInactive(endpoints);
endpoints = SetupConnection(mode);
endpoints.NodeEndpoint.Disconnect();
VerifyLinksAndCallbacksInactive(endpoints);
}
private void VerifyLinksAndCallbacksInactive(NodeEndpointInProc.EndpointPair endpoints)
{
CallOpOnEndpoints(endpoints, VerifyLinkInactive);
Assert.Equal(LinkStatus.Inactive, _linkStatusTable[endpoints.NodeEndpoint].status);
Assert.Equal(LinkStatus.Inactive, _linkStatusTable[endpoints.ManagerEndpoint].status);
}
private NodeEndpointInProc.EndpointPair SetupConnection(NodeEndpointInProc.EndpointMode mode)
{
NodeEndpointInProc.EndpointPair endpoints =
NodeEndpointInProc.CreateInProcEndpoints(mode, _host);
endpoints.ManagerEndpoint.OnLinkStatusChanged += LinkStatusChanged;
endpoints.NodeEndpoint.OnLinkStatusChanged += LinkStatusChanged;
// Call listen. This shouldn't have any effect on the link statuses.
endpoints.ManagerEndpoint.Listen(_host);
endpoints.NodeEndpoint.Connect(_host);
return endpoints;
}
private void LinkStatusChanged(INodeEndpoint endpoint, LinkStatus status)
{
lock (_linkStatusTable)
{
_linkStatusTable[endpoint] = new LinkStatusContext(Thread.CurrentThread, status);
}
}
}
}
| |
/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using ZXing.Common;
using ZXing.PDF417.Internal.EC;
namespace ZXing.PDF417.Internal
{
/// <summary>
///
/// </summary>
/// <author>Guenther Grau</author>
public static class PDF417ScanningDecoder
{
private const int CODEWORD_SKEW_SIZE = 2;
private const int MAX_ERRORS = 3;
private const int MAX_EC_CODEWORDS = 512;
private static readonly ErrorCorrection errorCorrection = new ErrorCorrection();
/// <summary>
/// Decode the specified image, imageTopLeft, imageBottomLeft, imageTopRight, imageBottomRight, minCodewordWidth
/// and maxCodewordWidth.
/// TODO: don't pass in minCodewordWidth and maxCodewordWidth, pass in barcode columns for start and stop pattern
/// columns. That way width can be deducted from the pattern column.
/// This approach also allows to detect more details about the barcode, e.g. if a bar type (white or black) is wider
/// than it should be. This can happen if the scanner used a bad blackpoint.
/// </summary>
/// <param name="image">Image.</param>
/// <param name="imageTopLeft">Image top left.</param>
/// <param name="imageBottomLeft">Image bottom left.</param>
/// <param name="imageTopRight">Image top right.</param>
/// <param name="imageBottomRight">Image bottom right.</param>
/// <param name="minCodewordWidth">Minimum codeword width.</param>
/// <param name="maxCodewordWidth">Max codeword width.</param>
public static DecoderResult decode(BitMatrix image,
ResultPoint imageTopLeft,
ResultPoint imageBottomLeft,
ResultPoint imageTopRight,
ResultPoint imageBottomRight,
int minCodewordWidth,
int maxCodewordWidth)
{
BoundingBox boundingBox = BoundingBox.Create(image, imageTopLeft, imageBottomLeft, imageTopRight, imageBottomRight);
if (boundingBox == null)
return null;
DetectionResultRowIndicatorColumn leftRowIndicatorColumn = null;
DetectionResultRowIndicatorColumn rightRowIndicatorColumn = null;
DetectionResult detectionResult = null;
for (int i = 0; i < 2; i++)
{
if (imageTopLeft != null)
{
leftRowIndicatorColumn = getRowIndicatorColumn(image, boundingBox, imageTopLeft, true, minCodewordWidth, maxCodewordWidth);
}
if (imageTopRight != null)
{
rightRowIndicatorColumn = getRowIndicatorColumn(image, boundingBox, imageTopRight, false, minCodewordWidth, maxCodewordWidth);
}
detectionResult = merge(leftRowIndicatorColumn, rightRowIndicatorColumn);
if (detectionResult == null)
{
// TODO Based on Owen's Comments in <see cref="ZXing.ReaderException"/>, this method has been modified to continue silently
// if a barcode was not decoded where it was detected instead of throwing a new exception object.
return null;
}
if (i == 0 && detectionResult.Box != null &&
(detectionResult.Box.MinY < boundingBox.MinY || detectionResult.Box.MaxY > boundingBox.MaxY))
{
boundingBox = detectionResult.Box;
}
else
{
detectionResult.Box = boundingBox;
break;
}
}
int maxBarcodeColumn = detectionResult.ColumnCount + 1;
detectionResult.DetectionResultColumns[0] = leftRowIndicatorColumn;
detectionResult.DetectionResultColumns[maxBarcodeColumn] = rightRowIndicatorColumn;
bool leftToRight = leftRowIndicatorColumn != null;
for (int barcodeColumnCount = 1; barcodeColumnCount <= maxBarcodeColumn; barcodeColumnCount++)
{
int barcodeColumn = leftToRight ? barcodeColumnCount : maxBarcodeColumn - barcodeColumnCount;
if (detectionResult.DetectionResultColumns[barcodeColumn] != null)
{
// This will be the case for the opposite row indicator column, which doesn't need to be decoded again.
continue;
}
DetectionResultColumn detectionResultColumn;
if (barcodeColumn == 0 || barcodeColumn == maxBarcodeColumn)
{
detectionResultColumn = new DetectionResultRowIndicatorColumn(boundingBox, barcodeColumn == 0);
}
else
{
detectionResultColumn = new DetectionResultColumn(boundingBox);
}
detectionResult.DetectionResultColumns[barcodeColumn] = detectionResultColumn;
int startColumn = -1;
int previousStartColumn = startColumn;
// TODO start at a row for which we know the start position, then detect upwards and downwards from there.
for (int imageRow = boundingBox.MinY; imageRow <= boundingBox.MaxY; imageRow++)
{
startColumn = getStartColumn(detectionResult, barcodeColumn, imageRow, leftToRight);
if (startColumn < 0 || startColumn > boundingBox.MaxX)
{
if (previousStartColumn == -1)
{
continue;
}
startColumn = previousStartColumn;
}
Codeword codeword = detectCodeword(image, boundingBox.MinX, boundingBox.MaxX, leftToRight,
startColumn, imageRow, minCodewordWidth, maxCodewordWidth);
if (codeword != null)
{
detectionResultColumn.setCodeword(imageRow, codeword);
previousStartColumn = startColumn;
minCodewordWidth = Math.Min(minCodewordWidth, codeword.Width);
maxCodewordWidth = Math.Max(maxCodewordWidth, codeword.Width);
}
}
}
return createDecoderResult(detectionResult);
}
/// <summary>
/// Merge the specified leftRowIndicatorColumn and rightRowIndicatorColumn.
/// </summary>
/// <param name="leftRowIndicatorColumn">Left row indicator column.</param>
/// <param name="rightRowIndicatorColumn">Right row indicator column.</param>
private static DetectionResult merge(DetectionResultRowIndicatorColumn leftRowIndicatorColumn,
DetectionResultRowIndicatorColumn rightRowIndicatorColumn)
{
if (leftRowIndicatorColumn == null && rightRowIndicatorColumn == null)
{
return null;
}
BarcodeMetadata barcodeMetadata = getBarcodeMetadata(leftRowIndicatorColumn, rightRowIndicatorColumn);
if (barcodeMetadata == null)
{
return null;
}
BoundingBox boundingBox = BoundingBox.merge(adjustBoundingBox(leftRowIndicatorColumn),
adjustBoundingBox(rightRowIndicatorColumn));
return new DetectionResult(barcodeMetadata, boundingBox);
}
/// <summary>
/// Adjusts the bounding box.
/// </summary>
/// <returns>The bounding box.</returns>
/// <param name="rowIndicatorColumn">Row indicator column.</param>
private static BoundingBox adjustBoundingBox(DetectionResultRowIndicatorColumn rowIndicatorColumn)
{
if (rowIndicatorColumn == null)
{
return null;
}
int[] rowHeights = rowIndicatorColumn.getRowHeights();
if (rowHeights == null)
{
return null;
}
int maxRowHeight = getMax(rowHeights);
int missingStartRows = 0;
foreach (int rowHeight in rowHeights)
{
missingStartRows += maxRowHeight - rowHeight;
if (rowHeight > 0)
{
break;
}
}
Codeword[] codewords = rowIndicatorColumn.Codewords;
for (int row = 0; missingStartRows > 0 && codewords[row] == null; row++)
{
missingStartRows--;
}
int missingEndRows = 0;
for (int row = rowHeights.Length - 1; row >= 0; row--)
{
missingEndRows += maxRowHeight - rowHeights[row];
if (rowHeights[row] > 0)
{
break;
}
}
for (int row = codewords.Length - 1; missingEndRows > 0 && codewords[row] == null; row--)
{
missingEndRows--;
}
return rowIndicatorColumn.Box.addMissingRows(missingStartRows, missingEndRows, rowIndicatorColumn.IsLeft);
}
private static int getMax(int[] values)
{
int maxValue = -1;
for (var index = values.Length - 1; index >= 0; index--)
{
maxValue = Math.Max(maxValue, values[index]);
}
return maxValue;
}
/// <summary>
/// Gets the barcode metadata.
/// </summary>
/// <returns>The barcode metadata.</returns>
/// <param name="leftRowIndicatorColumn">Left row indicator column.</param>
/// <param name="rightRowIndicatorColumn">Right row indicator column.</param>
private static BarcodeMetadata getBarcodeMetadata(DetectionResultRowIndicatorColumn leftRowIndicatorColumn,
DetectionResultRowIndicatorColumn rightRowIndicatorColumn)
{
BarcodeMetadata leftBarcodeMetadata;
if (leftRowIndicatorColumn == null ||
(leftBarcodeMetadata = leftRowIndicatorColumn.getBarcodeMetadata()) == null)
{
return rightRowIndicatorColumn == null ? null : rightRowIndicatorColumn.getBarcodeMetadata();
}
BarcodeMetadata rightBarcodeMetadata;
if (rightRowIndicatorColumn == null ||
(rightBarcodeMetadata = rightRowIndicatorColumn.getBarcodeMetadata()) == null)
{
return leftBarcodeMetadata;
}
if (leftBarcodeMetadata.ColumnCount != rightBarcodeMetadata.ColumnCount &&
leftBarcodeMetadata.ErrorCorrectionLevel != rightBarcodeMetadata.ErrorCorrectionLevel &&
leftBarcodeMetadata.RowCount != rightBarcodeMetadata.RowCount)
{
return null;
}
return leftBarcodeMetadata;
}
/// <summary>
/// Gets the row indicator column.
/// </summary>
/// <returns>The row indicator column.</returns>
/// <param name="image">Image.</param>
/// <param name="boundingBox">Bounding box.</param>
/// <param name="startPoint">Start point.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
/// <param name="minCodewordWidth">Minimum codeword width.</param>
/// <param name="maxCodewordWidth">Max codeword width.</param>
private static DetectionResultRowIndicatorColumn getRowIndicatorColumn(BitMatrix image,
BoundingBox boundingBox,
ResultPoint startPoint,
bool leftToRight,
int minCodewordWidth,
int maxCodewordWidth)
{
DetectionResultRowIndicatorColumn rowIndicatorColumn = new DetectionResultRowIndicatorColumn(boundingBox, leftToRight);
for (int i = 0; i < 2; i++)
{
int increment = i == 0 ? 1 : -1;
int startColumn = (int) startPoint.X;
for (int imageRow = (int) startPoint.Y; imageRow <= boundingBox.MaxY &&
imageRow >= boundingBox.MinY; imageRow += increment)
{
Codeword codeword = detectCodeword(image, 0, image.Width, leftToRight, startColumn, imageRow,
minCodewordWidth, maxCodewordWidth);
if (codeword != null)
{
rowIndicatorColumn.setCodeword(imageRow, codeword);
if (leftToRight)
{
startColumn = codeword.StartX;
}
else
{
startColumn = codeword.EndX;
}
}
}
}
return rowIndicatorColumn;
}
/// <summary>
/// Adjusts the codeword count.
/// </summary>
/// <param name="detectionResult">Detection result.</param>
/// <param name="barcodeMatrix">Barcode matrix.</param>
private static bool adjustCodewordCount(DetectionResult detectionResult, BarcodeValue[][] barcodeMatrix)
{
int[] numberOfCodewords = barcodeMatrix[0][1].getValue();
int calculatedNumberOfCodewords = detectionResult.ColumnCount*
detectionResult.RowCount -
getNumberOfECCodeWords(detectionResult.ErrorCorrectionLevel);
if (numberOfCodewords.Length == 0)
{
if (calculatedNumberOfCodewords < 1 || calculatedNumberOfCodewords > PDF417Common.MAX_CODEWORDS_IN_BARCODE)
{
return false;
}
barcodeMatrix[0][1].setValue(calculatedNumberOfCodewords);
}
else if (numberOfCodewords[0] != calculatedNumberOfCodewords)
{
// The calculated one is more reliable as it is derived from the row indicator columns
barcodeMatrix[0][1].setValue(calculatedNumberOfCodewords);
}
return true;
}
/// <summary>
/// Creates the decoder result.
/// </summary>
/// <returns>The decoder result.</returns>
/// <param name="detectionResult">Detection result.</param>
private static DecoderResult createDecoderResult(DetectionResult detectionResult)
{
BarcodeValue[][] barcodeMatrix = createBarcodeMatrix(detectionResult);
if (!adjustCodewordCount(detectionResult, barcodeMatrix))
{
return null;
}
List<int> erasures = new List<int>();
int[] codewords = new int[detectionResult.RowCount*detectionResult.ColumnCount];
List<int[]> ambiguousIndexValuesList = new List<int[]>();
List<int> ambiguousIndexesList = new List<int>();
for (int row = 0; row < detectionResult.RowCount; row++)
{
for (int column = 0; column < detectionResult.ColumnCount; column++)
{
int[] values = barcodeMatrix[row][column + 1].getValue();
int codewordIndex = row*detectionResult.ColumnCount + column;
if (values.Length == 0)
{
erasures.Add(codewordIndex);
}
else if (values.Length == 1)
{
codewords[codewordIndex] = values[0];
}
else
{
ambiguousIndexesList.Add(codewordIndex);
ambiguousIndexValuesList.Add(values);
}
}
}
int[][] ambiguousIndexValues = new int[ambiguousIndexValuesList.Count][];
for (int i = 0; i < ambiguousIndexValues.Length; i++)
{
ambiguousIndexValues[i] = ambiguousIndexValuesList[i];
}
return createDecoderResultFromAmbiguousValues(detectionResult.ErrorCorrectionLevel, codewords,
erasures.ToArray(), ambiguousIndexesList.ToArray(), ambiguousIndexValues);
}
/// <summary>
/// This method deals with the fact, that the decoding process doesn't always yield a single most likely value. The
/// current error correction implementation doesn't deal with erasures very well, so it's better to provide a value
/// for these ambiguous codewords instead of treating it as an erasure. The problem is that we don't know which of
/// the ambiguous values to choose. We try decode using the first value, and if that fails, we use another of the
/// ambiguous values and try to decode again. This usually only happens on very hard to read and decode barcodes,
/// so decoding the normal barcodes is not affected by this.
/// </summary>
/// <returns>The decoder result from ambiguous values.</returns>
/// <param name="ecLevel">Ec level.</param>
/// <param name="codewords">Codewords.</param>
/// <param name="erasureArray">contains the indexes of erasures.</param>
/// <param name="ambiguousIndexes">array with the indexes that have more than one most likely value.</param>
/// <param name="ambiguousIndexValues">two dimensional array that contains the ambiguous values. The first dimension must
/// be the same Length as the ambiguousIndexes array.</param>
private static DecoderResult createDecoderResultFromAmbiguousValues(int ecLevel,
int[] codewords,
int[] erasureArray,
int[] ambiguousIndexes,
int[][] ambiguousIndexValues)
{
int[] ambiguousIndexCount = new int[ambiguousIndexes.Length];
int tries = 100;
while (tries-- > 0)
{
for (int i = 0; i < ambiguousIndexCount.Length; i++)
{
codewords[ambiguousIndexes[i]] = ambiguousIndexValues[i][ambiguousIndexCount[i]];
}
try
{
var result = decodeCodewords(codewords, ecLevel, erasureArray);
if (result != null)
return result;
}
catch (ReaderException)
{
// ignored, should not happen
}
if (ambiguousIndexCount.Length == 0)
{
return null;
}
for (int i = 0; i < ambiguousIndexCount.Length; i++)
{
if (ambiguousIndexCount[i] < ambiguousIndexValues[i].Length - 1)
{
ambiguousIndexCount[i]++;
break;
}
else
{
ambiguousIndexCount[i] = 0;
if (i == ambiguousIndexCount.Length - 1)
{
return null;
}
}
}
}
return null;
}
/// <summary>
/// Creates the barcode matrix.
/// </summary>
/// <returns>The barcode matrix.</returns>
/// <param name="detectionResult">Detection result.</param>
private static BarcodeValue[][] createBarcodeMatrix(DetectionResult detectionResult)
{
// Manually setup Jagged Array in C#
BarcodeValue[][] barcodeMatrix = new BarcodeValue[detectionResult.RowCount][];
for (int row = 0; row < barcodeMatrix.Length; row++)
{
barcodeMatrix[row] = new BarcodeValue[detectionResult.ColumnCount + 2];
for (int col = 0; col < barcodeMatrix[row].Length; col++)
{
barcodeMatrix[row][col] = new BarcodeValue();
}
}
int column = -1;
foreach (DetectionResultColumn detectionResultColumn in detectionResult.getDetectionResultColumns())
{
column++;
if (detectionResultColumn == null)
{
continue;
}
foreach (Codeword codeword in detectionResultColumn.Codewords)
{
if (codeword == null || codeword.RowNumber == -1)
{
continue;
}
barcodeMatrix[codeword.RowNumber][column].setValue(codeword.Value);
}
}
return barcodeMatrix;
}
/// <summary>
/// Tests to see if the Barcode Column is Valid
/// </summary>
/// <returns><c>true</c>, if barcode column is valid, <c>false</c> otherwise.</returns>
/// <param name="detectionResult">Detection result.</param>
/// <param name="barcodeColumn">Barcode column.</param>
private static bool isValidBarcodeColumn(DetectionResult detectionResult, int barcodeColumn)
{
return (barcodeColumn >= 0) && (barcodeColumn < detectionResult.DetectionResultColumns.Length);
}
/// <summary>
/// Gets the start column.
/// </summary>
/// <returns>The start column.</returns>
/// <param name="detectionResult">Detection result.</param>
/// <param name="barcodeColumn">Barcode column.</param>
/// <param name="imageRow">Image row.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
private static int getStartColumn(DetectionResult detectionResult,
int barcodeColumn,
int imageRow,
bool leftToRight)
{
int offset = leftToRight ? 1 : -1;
Codeword codeword = null;
if (isValidBarcodeColumn(detectionResult, barcodeColumn - offset))
{
codeword = detectionResult.DetectionResultColumns[barcodeColumn - offset].getCodeword(imageRow);
}
if (codeword != null)
{
return leftToRight ? codeword.EndX : codeword.StartX;
}
codeword = detectionResult.DetectionResultColumns[barcodeColumn].getCodewordNearby(imageRow);
if (codeword != null)
{
return leftToRight ? codeword.StartX : codeword.EndX;
}
if (isValidBarcodeColumn(detectionResult, barcodeColumn - offset))
{
codeword = detectionResult.DetectionResultColumns[barcodeColumn - offset].getCodewordNearby(imageRow);
}
if (codeword != null)
{
return leftToRight ? codeword.EndX : codeword.StartX;
}
int skippedColumns = 0;
while (isValidBarcodeColumn(detectionResult, barcodeColumn - offset))
{
barcodeColumn -= offset;
foreach (Codeword previousRowCodeword in detectionResult.DetectionResultColumns[barcodeColumn].Codewords)
{
if (previousRowCodeword != null)
{
return (leftToRight ? previousRowCodeword.EndX : previousRowCodeword.StartX) +
offset*
skippedColumns*
(previousRowCodeword.EndX - previousRowCodeword.StartX);
}
}
skippedColumns++;
}
return leftToRight ? detectionResult.Box.MinX : detectionResult.Box.MaxX;
}
/// <summary>
/// Detects the codeword.
/// </summary>
/// <returns>The codeword.</returns>
/// <param name="image">Image.</param>
/// <param name="minColumn">Minimum column.</param>
/// <param name="maxColumn">Max column.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
/// <param name="startColumn">Start column.</param>
/// <param name="imageRow">Image row.</param>
/// <param name="minCodewordWidth">Minimum codeword width.</param>
/// <param name="maxCodewordWidth">Max codeword width.</param>
private static Codeword detectCodeword(BitMatrix image,
int minColumn,
int maxColumn,
bool leftToRight,
int startColumn,
int imageRow,
int minCodewordWidth,
int maxCodewordWidth)
{
startColumn = adjustCodewordStartColumn(image, minColumn, maxColumn, leftToRight, startColumn, imageRow);
// we usually know fairly exact now how long a codeword is. We should provide minimum and maximum expected length
// and try to adjust the read pixels, e.g. remove single pixel errors or try to cut off exceeding pixels.
// min and maxCodewordWidth should not be used as they are calculated for the whole barcode an can be inaccurate
// for the current position
int[] moduleBitCount = getModuleBitCount(image, minColumn, maxColumn, leftToRight, startColumn, imageRow);
if (moduleBitCount == null)
{
return null;
}
int endColumn;
int codewordBitCount = PDF417Common.getBitCountSum(moduleBitCount);
if (leftToRight)
{
endColumn = startColumn + codewordBitCount;
}
else
{
for (int i = 0; i < (moduleBitCount.Length >> 1); i++)
{
int tmpCount = moduleBitCount[i];
moduleBitCount[i] = moduleBitCount[moduleBitCount.Length - 1 - i];
moduleBitCount[moduleBitCount.Length - 1 - i] = tmpCount;
}
endColumn = startColumn;
startColumn = endColumn - codewordBitCount;
}
// TODO implement check for width and correction of black and white bars
// use start (and maybe stop pattern) to determine if blackbars are wider than white bars. If so, adjust.
// should probably done only for codewords with a lot more than 17 bits.
// The following fixes 10-1.png, which has wide black bars and small white bars
// for (int i = 0; i < moduleBitCount.Length; i++) {
// if (i % 2 == 0) {
// moduleBitCount[i]--;
// } else {
// moduleBitCount[i]++;
// }
// }
// We could also use the width of surrounding codewords for more accurate results, but this seems
// sufficient for now
if (!checkCodewordSkew(codewordBitCount, minCodewordWidth, maxCodewordWidth))
{
// We could try to use the startX and endX position of the codeword in the same column in the previous row,
// create the bit count from it and normalize it to 8. This would help with single pixel errors.
return null;
}
int decodedValue = PDF417CodewordDecoder.getDecodedValue(moduleBitCount);
int codeword = PDF417Common.getCodeword(decodedValue);
if (codeword == -1)
{
return null;
}
return new Codeword(startColumn, endColumn, getCodewordBucketNumber(decodedValue), codeword);
}
/// <summary>
/// Gets the module bit count.
/// </summary>
/// <returns>The module bit count.</returns>
/// <param name="image">Image.</param>
/// <param name="minColumn">Minimum column.</param>
/// <param name="maxColumn">Max column.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
/// <param name="startColumn">Start column.</param>
/// <param name="imageRow">Image row.</param>
private static int[] getModuleBitCount(BitMatrix image,
int minColumn,
int maxColumn,
bool leftToRight,
int startColumn,
int imageRow)
{
int imageColumn = startColumn;
int[] moduleBitCount = new int[8];
int moduleNumber = 0;
int increment = leftToRight ? 1 : -1;
bool previousPixelValue = leftToRight;
while (((leftToRight && imageColumn < maxColumn) || (!leftToRight && imageColumn >= minColumn)) &&
moduleNumber < moduleBitCount.Length)
{
if (image[imageColumn, imageRow] == previousPixelValue)
{
moduleBitCount[moduleNumber]++;
imageColumn += increment;
}
else
{
moduleNumber++;
previousPixelValue = !previousPixelValue;
}
}
if (moduleNumber == moduleBitCount.Length ||
(((leftToRight && imageColumn == maxColumn) || (!leftToRight && imageColumn == minColumn)) && moduleNumber == moduleBitCount.Length - 1))
{
return moduleBitCount;
}
return null;
}
/// <summary>
/// Gets the number of EC code words.
/// </summary>
/// <returns>The number of EC code words.</returns>
/// <param name="barcodeECLevel">Barcode EC level.</param>
private static int getNumberOfECCodeWords(int barcodeECLevel)
{
return 2 << barcodeECLevel;
}
/// <summary>
/// Adjusts the codeword start column.
/// </summary>
/// <returns>The codeword start column.</returns>
/// <param name="image">Image.</param>
/// <param name="minColumn">Minimum column.</param>
/// <param name="maxColumn">Max column.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
/// <param name="codewordStartColumn">Codeword start column.</param>
/// <param name="imageRow">Image row.</param>
private static int adjustCodewordStartColumn(BitMatrix image,
int minColumn,
int maxColumn,
bool leftToRight,
int codewordStartColumn,
int imageRow)
{
int correctedStartColumn = codewordStartColumn;
int increment = leftToRight ? -1 : 1;
// there should be no black pixels before the start column. If there are, then we need to start earlier.
for (int i = 0; i < 2; i++)
{
while (((leftToRight && correctedStartColumn >= minColumn) || (!leftToRight && correctedStartColumn < maxColumn)) &&
leftToRight == image[correctedStartColumn, imageRow])
{
if (Math.Abs(codewordStartColumn - correctedStartColumn) > CODEWORD_SKEW_SIZE)
{
return codewordStartColumn;
}
correctedStartColumn += increment;
}
increment = -increment;
leftToRight = !leftToRight;
}
return correctedStartColumn;
}
/// <summary>
/// Checks the codeword for any skew.
/// </summary>
/// <returns><c>true</c>, if codeword is within the skew, <c>false</c> otherwise.</returns>
/// <param name="codewordSize">Codeword size.</param>
/// <param name="minCodewordWidth">Minimum codeword width.</param>
/// <param name="maxCodewordWidth">Max codeword width.</param>
private static bool checkCodewordSkew(int codewordSize, int minCodewordWidth, int maxCodewordWidth)
{
return minCodewordWidth - CODEWORD_SKEW_SIZE <= codewordSize &&
codewordSize <= maxCodewordWidth + CODEWORD_SKEW_SIZE;
}
/// <summary>
/// Decodes the codewords.
/// </summary>
/// <returns>The codewords.</returns>
/// <param name="codewords">Codewords.</param>
/// <param name="ecLevel">Ec level.</param>
/// <param name="erasures">Erasures.</param>
private static DecoderResult decodeCodewords(int[] codewords, int ecLevel, int[] erasures)
{
if (codewords.Length == 0)
{
return null;
}
int numECCodewords = 1 << (ecLevel + 1);
int correctedErrorsCount = correctErrors(codewords, erasures, numECCodewords);
if (correctedErrorsCount < 0)
{
return null;
}
if (!verifyCodewordCount(codewords, numECCodewords))
{
return null;
}
// Decode the codewords
DecoderResult decoderResult = DecodedBitStreamParser.decode(codewords, ecLevel.ToString());
if (decoderResult != null)
{
decoderResult.ErrorsCorrected = correctedErrorsCount;
decoderResult.Erasures = erasures.Length;
}
return decoderResult;
}
/// <summary>
/// Given data and error-correction codewords received, possibly corrupted by errors, attempts to
/// correct the errors in-place.
/// </summary>
/// <returns>The errors.</returns>
/// <param name="codewords">data and error correction codewords.</param>
/// <param name="erasures">positions of any known erasures.</param>
/// <param name="numECCodewords">number of error correction codewords that are available in codewords.</param>
private static int correctErrors(int[] codewords, int[] erasures, int numECCodewords)
{
if (erasures != null &&
erasures.Length > numECCodewords/2 + MAX_ERRORS ||
numECCodewords < 0 ||
numECCodewords > MAX_EC_CODEWORDS)
{
// Too many errors or EC Codewords is corrupted
return -1;
}
int errorCount;
if (!errorCorrection.decode(codewords, numECCodewords, erasures, out errorCount))
{
return -1;
}
return errorCount;
}
/// <summary>
/// Verifies that all is well with the the codeword array.
/// </summary>
/// <param name="codewords">Codewords.</param>
/// <param name="numECCodewords">Number EC codewords.</param>
private static bool verifyCodewordCount(int[] codewords, int numECCodewords)
{
if (codewords.Length < 4)
{
// Codeword array size should be at least 4 allowing for
// Count CW, At least one Data CW, Error Correction CW, Error Correction CW
return false;
}
// The first codeword, the Symbol Length Descriptor, shall always encode the total number of data
// codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad
// codewords, but excluding the number of error correction codewords.
int numberOfCodewords = codewords[0];
if (numberOfCodewords > codewords.Length)
{
return false;
}
if (numberOfCodewords == 0)
{
// Reset to the Length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords)
if (numECCodewords < codewords.Length)
{
codewords[0] = codewords.Length - numECCodewords;
}
else
{
return false;
}
}
return true;
}
/// <summary>
/// Gets the bit count for codeword.
/// </summary>
/// <returns>The bit count for codeword.</returns>
/// <param name="codeword">Codeword.</param>
private static int[] getBitCountForCodeword(int codeword)
{
int[] result = new int[8];
int previousValue = 0;
int i = result.Length - 1;
while (true)
{
if ((codeword & 0x1) != previousValue)
{
previousValue = codeword & 0x1;
i--;
if (i < 0)
{
break;
}
}
result[i]++;
codeword >>= 1;
}
return result;
}
/// <summary>
/// Gets the codeword bucket number.
/// </summary>
/// <returns>The codeword bucket number.</returns>
/// <param name="codeword">Codeword.</param>
private static int getCodewordBucketNumber(int codeword)
{
return getCodewordBucketNumber(getBitCountForCodeword(codeword));
}
/// <summary>
/// Gets the codeword bucket number.
/// </summary>
/// <returns>The codeword bucket number.</returns>
/// <param name="moduleBitCount">Module bit count.</param>
private static int getCodewordBucketNumber(int[] moduleBitCount)
{
return (moduleBitCount[0] - moduleBitCount[2] + moduleBitCount[4] - moduleBitCount[6] + 9)%9;
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the <see cref="ZXing.PDF417.Internal.BarcodeValue"/> jagged array.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the <see cref="ZXing.PDF417.Internal.BarcodeValue"/> jagged array.</returns>
/// <param name="barcodeMatrix">Barcode matrix as a jagged array.</param>
public static String ToString(BarcodeValue[][] barcodeMatrix)
{
StringBuilder formatter = new StringBuilder();
for (int row = 0; row < barcodeMatrix.Length; row++)
{
formatter.AppendFormat(CultureInfo.InvariantCulture, "Row {0,2}: ", row);
for (int column = 0; column < barcodeMatrix[row].Length; column++)
{
BarcodeValue barcodeValue = barcodeMatrix[row][column];
int[] values = barcodeValue.getValue();
if (values.Length == 0)
{
formatter.Append(" ");
}
else
{
formatter.AppendFormat(CultureInfo.InvariantCulture, "{0,4}({1,2})", values[0], barcodeValue.getConfidence(values[0]));
}
}
formatter.Append("\n");
}
return formatter.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.ObjectModel;
using Signum.Utilities;
using System.Reflection;
using Signum.Entities;
using Signum.Utilities.ExpressionTrees;
using Signum.Utilities.Reflection;
using Signum.Engine.Maps;
using Signum.Entities.Reflection;
namespace Signum.Engine.Linq
{
internal class EntityExpression : DbExpression
{
public static readonly FieldInfo IdField = ReflectionTools.GetFieldInfo((Entity ei) =>ei.id);
public static readonly FieldInfo ToStrField = ReflectionTools.GetFieldInfo((Entity ie) =>ie.toStr);
public static readonly MethodInfo ToStringMethod = ReflectionTools.GetMethodInfo((object o) => o.ToString());
public static readonly PropertyInfo IdOrNullProperty = ReflectionTools.GetPropertyInfo((Entity ei) => ei.IdOrNull);
public readonly Table Table;
public readonly PrimaryKeyExpression ExternalId;
public readonly IntervalExpression? ExternalPeriod;
//Optional
public readonly Alias? TableAlias;
public readonly ReadOnlyCollection<FieldBinding>? Bindings;
public readonly ReadOnlyCollection<MixinEntityExpression>? Mixins;
public readonly bool AvoidExpandOnRetrieving;
public readonly IntervalExpression? TablePeriod;
public EntityExpression(Type type, PrimaryKeyExpression externalId,
IntervalExpression? externalPeriod,
Alias? tableAlias,
IEnumerable<FieldBinding>? bindings,
IEnumerable<MixinEntityExpression>? mixins,
IntervalExpression? tablePeriod, bool avoidExpandOnRetrieving)
: base(DbExpressionType.Entity, type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (!type.IsEntity())
throw new ArgumentException("type");
this.Table = Schema.Current.Table(type);
this.ExternalId = externalId ?? throw new ArgumentNullException(nameof(externalId));
this.TableAlias = tableAlias;
this.Bindings = bindings.ToReadOnly();
this.Mixins = mixins.ToReadOnly();
this.ExternalPeriod = externalPeriod;
this.TablePeriod = tablePeriod;
this.AvoidExpandOnRetrieving = avoidExpandOnRetrieving;
}
public override string ToString()
{
var constructor = "new {0}{1}({2})".FormatWith(Type.TypeName(), AvoidExpandOnRetrieving ? "?": "",
ExternalId.ToString());
return constructor +
(Bindings == null ? null : ("\r\n{\r\n " + Bindings.ToString(",\r\n ").Indent(4) + "\r\n}")) +
(Mixins == null ? null : ("\r\n" + Mixins.ToString(m => ".Mixin({0})".FormatWith(m), "\r\n")));
}
public Expression GetBinding(FieldInfo fi)
{
if (Bindings == null)
throw new InvalidOperationException("EntityInitiExpression not completed");
FieldBinding binding = Bindings.Where(fb => ReflectionTools.FieldEquals(fi, fb.FieldInfo)).SingleEx(() => "field '{0}' in {1} (field Ignored?)".FormatWith(fi.Name, this.Type.TypeName()));
return binding.Binding;
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitEntity(this);
}
internal EntityExpression WithExpandEntity(ExpandEntity expandEntity)
{
switch (expandEntity)
{
case ExpandEntity.EagerEntity:
return new EntityExpression(this.Type, this.ExternalId, this.ExternalPeriod, this.TableAlias, this.Bindings, this.Mixins, this.TablePeriod, avoidExpandOnRetrieving: false);
case ExpandEntity.LazyEntity:
return new EntityExpression(this.Type, this.ExternalId, this.ExternalPeriod, this.TableAlias, this.Bindings, this.Mixins, this.TablePeriod, avoidExpandOnRetrieving: true);
default:
throw new NotImplementedException();
}
}
}
internal class EmbeddedEntityExpression : DbExpression
{
public readonly Expression HasValue;
public readonly ReadOnlyCollection<FieldBinding> Bindings;
public readonly FieldEmbedded? FieldEmbedded; //used for updates
public readonly Table? ViewTable; //used for updates
public EmbeddedEntityExpression(Type type, Expression hasValue, IEnumerable<FieldBinding> bindings, FieldEmbedded? fieldEmbedded, Table? viewTable)
: base(DbExpressionType.EmbeddedInit, type)
{
if (bindings == null)
throw new ArgumentNullException(nameof(bindings));
if (hasValue == null || hasValue.Type != typeof(bool))
throw new ArgumentException("hasValue should be a boolean expression");
HasValue = hasValue;
Bindings = bindings.ToReadOnly();
FieldEmbedded = fieldEmbedded;
ViewTable = viewTable;
}
public Expression GetBinding(FieldInfo fi)
{
return Bindings.SingleEx(fb => ReflectionTools.FieldEquals(fi, fb.FieldInfo)).Binding;
}
public override string ToString()
{
string constructor = "new {0}".FormatWith(Type.TypeName());
string bindings = Bindings?.Let(b => b.ToString(",\r\n ")) ?? "";
return bindings.HasText() ?
constructor + "\r\n{" + bindings.Indent(4) + "\r\n}" :
constructor;
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitEmbeddedEntity(this);
}
public Expression GetViewId()
{
var field = ViewTable!.GetViewPrimaryKey()!;
return this.Bindings.SingleEx(b => ReflectionTools.FieldEquals(b.FieldInfo, field.FieldInfo)).Binding;
}
}
internal class MixinEntityExpression : DbExpression
{
public readonly ReadOnlyCollection<FieldBinding> Bindings;
public readonly FieldMixin? FieldMixin; //used for updates
public readonly Alias? MainEntityAlias;
public MixinEntityExpression(Type type, IEnumerable<FieldBinding> bindings, Alias? mainEntityAlias, FieldMixin? fieldMixin)
: base(DbExpressionType.MixinInit, type)
{
if (bindings == null)
throw new ArgumentNullException(nameof(bindings));
Bindings = bindings.ToReadOnly();
FieldMixin = fieldMixin;
MainEntityAlias = mainEntityAlias;
}
public Expression GetBinding(FieldInfo fi)
{
return Bindings.SingleEx(fb => ReflectionTools.FieldEquals(fi, fb.FieldInfo)).Binding;
}
public override string ToString()
{
string constructor = "new {0}".FormatWith(Type.TypeName());
string bindings = Bindings?.Let(b => b.ToString(",\r\n ")) ?? "";
return bindings.HasText() ?
constructor + "\r\n{" + bindings.Indent(4) + "\r\n}" :
constructor;
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitMixinEntity(this);
}
}
internal class FieldBinding
{
public readonly FieldInfo FieldInfo;
public readonly Expression Binding;
public FieldBinding(FieldInfo fieldInfo, Expression binding, bool allowForcedNull = false)
{
var ft = fieldInfo.FieldType;
if(allowForcedNull)
ft = ft.Nullify();
if (!ft.IsAssignableFrom(binding.Type))
throw new ArgumentException("Type of expression is {0} but type of field is {1}".FormatWith(binding.Type.TypeName(), fieldInfo.FieldType.TypeName()));
this.FieldInfo = fieldInfo;
this.Binding = binding;
}
public override string ToString()
{
return "{0} = {1}".FormatWith(FieldInfo.Name, Binding.ToString());
}
}
internal class ImplementedByExpression : DbExpression//, IPropertyInitExpression
{
public readonly ReadOnlyDictionary<Type, EntityExpression> Implementations;
public readonly CombineStrategy Strategy;
public ImplementedByExpression(Type type, CombineStrategy strategy, IDictionary<Type, EntityExpression> implementations)
: base(DbExpressionType.ImplementedBy, type)
{
this.Implementations = implementations.ToReadOnly();
this.Strategy = strategy;
}
public override string ToString()
{
return "ImplementedBy({0}){{\r\n{1}\r\n}}".FormatWith(Strategy,
Implementations.ToString(kvp => "{0} -> {1}".FormatWith(kvp.Key.TypeName(), kvp.Value.ToString()), "\r\n").Indent(4)
);
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitImplementedBy(this);
}
}
internal class ImplementedByAllExpression : DbExpression
{
public readonly Expression Id;
public readonly TypeImplementedByAllExpression TypeId;
public readonly IntervalExpression? ExternalPeriod;
public ImplementedByAllExpression(Type type, Expression id, TypeImplementedByAllExpression typeId, IntervalExpression? externalPeriod)
: base(DbExpressionType.ImplementedByAll, type)
{
if (id == null)
throw new ArgumentNullException(nameof(id));
if (id.Type != typeof(string))
throw new ArgumentException("string");
this.Id = id;
this.TypeId = typeId ?? throw new ArgumentNullException(nameof(typeId));
this.ExternalPeriod = externalPeriod;
}
public override string ToString()
{
return "ImplementedByAll{{ ID = {0}, Type = {1} }}".FormatWith(Id, TypeId);
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitImplementedByAll(this);
}
}
internal class LiteReferenceExpression : DbExpression
{
public bool LazyToStr;
public bool EagerEntity;
public readonly Expression Reference; //Fie, ImplementedBy, ImplementedByAll or Constant to NullEntityExpression
public readonly Expression? CustomToStr; //Not readonly
public LiteReferenceExpression(Type type, Expression reference, Expression? customToStr, bool lazyToStr, bool eagerEntity) :
base(DbExpressionType.LiteReference, type)
{
Type? cleanType = Lite.Extract(type);
if (cleanType != reference.Type)
throw new ArgumentException("The type {0} is not the Lite version of {1}".FormatWith(type.TypeName(), reference.Type.TypeName()));
this.Reference = reference;
this.CustomToStr = customToStr;
this.LazyToStr = lazyToStr;
this.EagerEntity = eagerEntity;
}
public override string ToString()
{
return "({0}).ToLite({1})".FormatWith(Reference.ToString(), CustomToStr == null ? null : ("customToStr: " + CustomToStr.ToString()));
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitLiteReference(this);
}
internal LiteReferenceExpression WithExpandLite(ExpandLite expandLite)
{
switch (expandLite)
{
case ExpandLite.EntityEager:
return new LiteReferenceExpression(this.Type, this.Reference, this.CustomToStr, lazyToStr: false, eagerEntity: true);
case ExpandLite.ToStringEager:
return new LiteReferenceExpression(this.Type, this.Reference, this.CustomToStr, lazyToStr: false, eagerEntity: false);
case ExpandLite.ToStringLazy:
return new LiteReferenceExpression(this.Type, this.Reference, this.CustomToStr, lazyToStr: true, eagerEntity: false);
case ExpandLite.ToStringNull:
return new LiteReferenceExpression(this.Type, this.Reference, Expression.Constant(null, typeof(string)), lazyToStr: true, eagerEntity: false);
default:
throw new NotImplementedException();
}
}
}
internal class LiteValueExpression : DbExpression
{
public readonly Expression TypeId;
public readonly Expression Id;
public readonly Expression? ToStr;
public LiteValueExpression(Type type, Expression typeId, Expression id, Expression? toStr) :
base(DbExpressionType.LiteValue, type)
{
this.TypeId = typeId ?? throw new ArgumentNullException(nameof(typeId));
this.Id = id ?? throw new ArgumentNullException(nameof(id));
this.ToStr = toStr;
}
public override string ToString()
{
return $"new Lite<{Type.CleanType().TypeName()}>({TypeId},{Id},{ToStr})";
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitLiteValue(this);
}
}
internal class TypeEntityExpression : DbExpression
{
public readonly PrimaryKeyExpression ExternalId;
public readonly Type TypeValue;
public TypeEntityExpression(PrimaryKeyExpression externalId, Type typeValue)
: base(DbExpressionType.TypeEntity, typeof(Type))
{
this.TypeValue = typeValue ?? throw new ArgumentException("typeValue");
this.ExternalId = externalId ?? throw new ArgumentException("externalId");
}
public override string ToString()
{
return "TypeFie({0};{1})".FormatWith(TypeValue.TypeName(), ExternalId.ToString());
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitTypeEntity(this);
}
}
internal class TypeImplementedByExpression : DbExpression
{
public readonly ReadOnlyDictionary<Type, PrimaryKeyExpression> TypeImplementations;
public TypeImplementedByExpression(IDictionary<Type, PrimaryKeyExpression> typeImplementations)
: base(DbExpressionType.TypeImplementedBy, typeof(Type))
{
if (typeImplementations == null || typeImplementations.Any(a => a.Value.Type.UnNullify() != typeof(PrimaryKey)))
throw new ArgumentException("typeId");
this.TypeImplementations = typeImplementations.ToReadOnly();
}
public override string ToString()
{
return "TypeIb({0})".FormatWith(TypeImplementations.ToString(kvp => "{0}({1})".FormatWith(kvp.Key.TypeName(), kvp.Value.ToString()), " | "));
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitTypeImplementedBy(this);
}
}
internal class TypeImplementedByAllExpression : DbExpression
{
public readonly PrimaryKeyExpression TypeColumn;
public TypeImplementedByAllExpression(PrimaryKeyExpression typeColumn)
: base(DbExpressionType.TypeImplementedByAll, typeof(Type))
{
this.TypeColumn = typeColumn ?? throw new ArgumentException("typeId");
}
public override string ToString()
{
return "TypeIba({0})".FormatWith(TypeColumn.ToString());
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitTypeImplementedByAll(this);
}
}
internal class MListExpression : DbExpression
{
public readonly PrimaryKeyExpression BackID; // not readonly
public readonly TableMList TableMList;
public readonly IntervalExpression? ExternalPeriod;
public MListExpression(Type type, PrimaryKeyExpression backID, IntervalExpression? externalPeriod, TableMList tr)
: base(DbExpressionType.MList, type)
{
this.BackID = backID;
this.ExternalPeriod = externalPeriod;
this.TableMList = tr;
}
public override string ToString()
{
return "new MList({0},{1})".FormatWith(TableMList.Name, BackID);
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitMList(this);
}
}
internal class AdditionalFieldExpression : DbExpression
{
public readonly PrimaryKeyExpression BackID; // not readonly
public readonly IntervalExpression? ExternalPeriod;
public readonly PropertyRoute Route;
public AdditionalFieldExpression(Type type, PrimaryKeyExpression backID, IntervalExpression? externalPeriod, PropertyRoute route)
: base(DbExpressionType.AdditionalField, type)
{
this.BackID = backID;
this.Route = route;
this.ExternalPeriod = externalPeriod;
}
public override string ToString()
{
return "new AdditionalField({0})".FormatWith(this.Route);
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitAdditionalField(this);
}
}
internal class MListProjectionExpression : DbExpression
{
public readonly ProjectionExpression Projection;
public MListProjectionExpression(Type type, ProjectionExpression projection)
: base(DbExpressionType.MListProjection, type)
{
if (!projection.Type.ElementType()!.IsInstantiationOf(typeof(MList<>.RowIdElement)))
throw new ArgumentException("projector should be collation of RowIdValue");
this.Projection = projection;
}
public override string ToString()
{
return "new MList({0})".FormatWith(Projection.ToString());
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitMListProjection(this);
}
}
internal class MListElementExpression : DbExpression
{
public readonly PrimaryKeyExpression RowId;
public readonly EntityExpression Parent;
public readonly Expression? Order;
public readonly Expression Element;
public readonly TableMList Table;
public readonly Alias Alias;
public readonly IntervalExpression? TablePeriod;
public MListElementExpression(PrimaryKeyExpression rowId, EntityExpression parent, Expression? order, Expression element, IntervalExpression? systemPeriod, TableMList table, Alias alias)
: base(DbExpressionType.MListElement, typeof(MListElement<,>).MakeGenericType(parent.Type, element.Type))
{
this.RowId = rowId;
this.Parent = parent;
this.Order = order;
this.Element = element;
this.TablePeriod = systemPeriod;
this.Table = table;
this.Alias = alias;
}
public override string ToString()
{
return "MListElement({0})\r\n{{\r\nParent={1},\r\nOrder={2},\r\nElement={3}}})".FormatWith(
RowId.ToString(),
Parent.ToString(),
Order?.ToString(),
Element.ToString());
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitMListElement(this);
}
}
internal class PrimaryKeyExpression : DbExpression
{
public static Variable<bool> PreferVariableNameVariable = Statics.ThreadVariable<bool>("preferParameterName");
public static IDisposable PreferVariableName()
{
var oldValue = PreferVariableNameVariable.Value;
PreferVariableNameVariable.Value = true;
return new Disposable(() => PreferVariableNameVariable.Value = oldValue);
}
public readonly Expression Value;
public Type ValueType { get { return Value.Type; } }
public PrimaryKeyExpression(Expression value)
: base(DbExpressionType.PrimaryKey, typeof(PrimaryKey?))
{
if (value.Type.Nullify() != value.Type)
throw new InvalidOperationException("value should be nullable");
this.Value = value;
}
public override string ToString()
{
return "(PrimaryKey?)(" + Value.ToString() + ")";
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitPrimaryKey(this);
}
}
internal class PrimaryKeyStringExpression : DbExpression
{
public readonly Expression Id;
public readonly TypeImplementedByAllExpression TypeId;
public PrimaryKeyStringExpression(Expression id, TypeImplementedByAllExpression typeId)
: base(DbExpressionType.PrimaryKeyString, typeof(PrimaryKey?))
{
if (id == null)
throw new ArgumentNullException(nameof(id));
if(id.Type != typeof(string))
throw new ArgumentException("id should be a string");
this.Id = id;
this.TypeId = typeId ?? throw new ArgumentNullException(nameof(typeId));
}
public override string ToString()
{
return "(PrimaryKeyString?)(" + Id.ToString() + ", " + TypeId.ToString() + ")";
}
protected override Expression Accept(DbExpressionVisitor visitor)
{
return visitor.VisitPrimaryKeyString(this);
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.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.
*******************************************************************************/
//
// Novell.Directory.Ldap.LdapReferralException.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using Novell.Directory.LDAP.VQ.Utilclass;
namespace Novell.Directory.LDAP.VQ
{
/// <summary> Thrown when a server returns a referral and when a referral has not
/// been followed. It contains a list of URL strings corresponding
/// to the referrals or search continuation references received on an Ldap
/// operation.
/// </summary>
public class LdapReferralException : LdapException
{
/// <summary> Sets a referral that could not be processed
///
/// </summary>
/// <param name="url">The referral URL that could not be processed.
/// </param>
virtual public string FailedReferral
{
/* Gets the referral that could not be processed. If multiple referrals
* could not be processed, the method returns one of them.
*
* @return the referral that could not be followed.
*/
get
{
return failedReferral;
}
set
{
failedReferral = value;
}
}
private string failedReferral = null;
private string[] referrals = null;
/// <summary> Constructs a default exception with no specific error information.</summary>
public LdapReferralException() : base()
{
}
/// <summary> Constructs a default exception with a specified string as additional
/// information.
///
/// This form is used for lower-level errors.
///
/// </summary>
/// <param name="message">The additional error information.
/// </param>
public LdapReferralException(string message) : base(message, REFERRAL, (string)null)
{
}
/// <summary> Constructs a default exception with a specified string as additional
/// information.
///
/// This form is used for lower-level errors.
///
///
/// </summary>
/// <param name="arguments"> The modifying arguments to be included in the
/// message string.
///
/// </param>
/// <param name="message">The additional error information.
/// </param>
public LdapReferralException(string message, object[] arguments) : base(message, arguments, REFERRAL, (string)null)
{
}
/// <summary> Constructs a default exception with a specified string as additional
/// information and an exception that indicates a failure to follow a
/// referral. This excepiton applies only to synchronous operations and
/// is thrown only on receipt of a referral when the referral was not
/// followed.
///
/// </summary>
/// <param name="message">The additional error information.
///
///
/// </param>
/// <param name="rootException">An exception which caused referral following to fail.
/// </param>
public LdapReferralException(string message, Exception rootException) : base(message, REFERRAL, null, rootException)
{
}
/// <summary> Constructs a default exception with a specified string as additional
/// information and an exception that indicates a failure to follow a
/// referral. This excepiton applies only to synchronous operations and
/// is thrown only on receipt of a referral when the referral was not
/// followed.
///
/// </summary>
/// <param name="message">The additional error information.
///
///
/// </param>
/// <param name="arguments"> The modifying arguments to be included in the
/// message string.
///
/// </param>
/// <param name="rootException">An exception which caused referral following to fail.
/// </param>
public LdapReferralException(string message, object[] arguments, Exception rootException) : base(message, arguments, REFERRAL, null, rootException)
{
}
/// <summary> Constructs an exception with a specified error string, result code, and
/// an error message from the server.
///
/// </summary>
/// <param name="message"> The additional error information.
///
/// </param>
/// <param name="resultCode"> The result code returned.
///
/// </param>
/// <param name="serverMessage"> Error message specifying additional information
/// from the server.
/// </param>
public LdapReferralException(string message, int resultCode, string serverMessage) : base(message, resultCode, serverMessage)
{
}
/// <summary> Constructs an exception with a specified error string, result code, and
/// an error message from the server.
///
/// </summary>
/// <param name="message"> The additional error information.
///
/// </param>
/// <param name="arguments"> The modifying arguments to be included in the
/// message string.
///
/// </param>
/// <param name="resultCode"> The result code returned.
///
/// </param>
/// <param name="serverMessage"> Error message specifying additional information
/// from the server.
/// </param>
public LdapReferralException(string message, object[] arguments, int resultCode, string serverMessage) : base(message, arguments, resultCode, serverMessage)
{
}
/// <summary> Constructs an exception with a specified error string, result code,
/// an error message from the server, and an exception that indicates
/// a failure to follow a referral.
///
/// </summary>
/// <param name="message"> The additional error information.
///
/// </param>
/// <param name="resultCode"> The result code returned.
///
/// </param>
/// <param name="serverMessage"> Error message specifying additional information
/// from the server.
/// </param>
public LdapReferralException(string message, int resultCode, string serverMessage, Exception rootException) : base(message, resultCode, serverMessage, rootException)
{
}
/// <summary> Constructs an exception with a specified error string, result code,
/// an error message from the server, and an exception that indicates
/// a failure to follow a referral.
///
/// </summary>
/// <param name="message"> The additional error information.
///
/// </param>
/// <param name="arguments"> The modifying arguments to be included in the
/// message string.
///
/// </param>
/// <param name="resultCode"> The result code returned.
///
/// </param>
/// <param name="serverMessage"> Error message specifying additional information
/// from the server.
/// </param>
public LdapReferralException(string message, object[] arguments, int resultCode, string serverMessage, Exception rootException) : base(message, arguments, resultCode, serverMessage, rootException)
{
}
/// <summary> Gets the list of referral URLs (Ldap URLs to other servers) returned by
/// the Ldap server.
///
/// The referral list may include URLs of a type other than ones for an Ldap
/// server (for example, a referral URL other than ldap://something).
///
/// </summary>
/// <returns> The list of URLs that comprise this referral
/// </returns>
public virtual string[] getReferrals()
{
return referrals;
}
/// <summary> Sets the list of referrals
///
/// </summary>
/// <param name="urls">the list of referrals returned by the Ldap server in a
/// single response.
/// </param>
/* package */
internal virtual void setReferrals(string[] urls)
{
referrals = urls;
}
/// <summary> returns a string of information about the exception and the
/// the nested exceptions, if any.
/// </summary>
public override string ToString()
{
string msg, tmsg;
// Format the basic exception information
msg = getExceptionString("LdapReferralException");
// Add failed referral information
if ((object)failedReferral != null)
{
tmsg = ResourcesHandler.getMessage("FAILED_REFERRAL", new object[] { "LdapReferralException", failedReferral });
// If found no string from resource file, use a default string
if (tmsg.ToUpper().Equals("SERVER_MSG".ToUpper()))
{
tmsg = "LdapReferralException: Failed Referral: " + failedReferral;
}
msg = msg + '\n' + tmsg;
}
// Add referral information, display all the referrals in the list
if (referrals != null)
{
for (int i = 0; i < referrals.Length; i++)
{
tmsg = ResourcesHandler.getMessage("REFERRAL_ITEM", new object[] { "LdapReferralException", referrals[i] });
// If found no string from resource file, use a default string
if (tmsg.ToUpper().Equals("SERVER_MSG".ToUpper()))
{
tmsg = "LdapReferralException: Referral: " + referrals[i];
}
msg = msg + '\n' + tmsg;
}
}
return msg;
}
}
}
| |
namespace SqlDiffFramework.Forms
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.ToolStripStatusLabel spacer1;
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.msgDropDown = new System.Windows.Forms.ToolStripDropDownButton();
this.spacer2 = new System.Windows.Forms.ToolStripStatusLabel();
this.memoryStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.spacer3 = new System.Windows.Forms.ToolStripStatusLabel();
this.legendLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.LegendCurrentDiffLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.LegendNonCurrentDiffLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.LegendCurrentOmittedLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.LegendNonCurrentOmittedLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.mainSplitContainer = new System.Windows.Forms.SplitContainer();
this.leftSqlEditor = new CleanCode.SqlEditorControls.SqlEditor();
this.rightSqlEditor = new CleanCode.SqlEditorControls.SqlEditor();
this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newWorkspaceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.newQueryMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openQueryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator16 = new System.Windows.Forms.ToolStripSeparator();
this.saveLeftQueryMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveRightQueryMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator18 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator34 = new System.Windows.Forms.ToolStripSeparator();
this.tabLeavesControlMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tabInsertsSpacesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.findToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.replaceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.restoreSettingsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.nextDifferenceMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.previousDifferenceMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator14 = new System.Windows.Forms.ToolStripSeparator();
this.firstDifferenceMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.currentDifferenceMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastDifferenceMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.setCurrentDifferenceMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator25 = new System.Windows.Forms.ToolStripSeparator();
this.showProgressMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator19 = new System.Windows.Forms.ToolStripSeparator();
this.showLeftPaneMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.showRightPaneMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.showBothPanesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.queryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.executeQueryMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.executeBatchMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.metaQueriesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editConnectionsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mirrorQueryMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.userGuideMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
this.showMainKeyReferenceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.showGeneralKeyReferenceMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.showInputKeyReferenceMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.showOutputKeyReferenceMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.aboutMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.commandToolStrip = new System.Windows.Forms.ToolStrip();
this.nextDiffButton = new System.Windows.Forms.ToolStripButton();
this.previousDiffButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.firstDiffButton = new System.Windows.Forms.ToolStripButton();
this.currentDiffButton = new System.Windows.Forms.ToolStripButton();
this.lastDiffButton = new System.Windows.Forms.ToolStripButton();
this.setCurrentDiffButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.turboSortButton = new System.Windows.Forms.ToolStripButton();
this.tandemButton = new System.Windows.Forms.ToolStripButton();
this.autoDiffButton = new System.Windows.Forms.ToolStripButton();
this.autoDiffSplitButton = new System.Windows.Forms.ToolStripSplitButton();
this.taubererDiffMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.hertelDiffMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.potterDiffMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.showProgressButton = new System.Windows.Forms.ToolStripButton();
this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel();
this.filterValueTextBox = new System.Windows.Forms.ToolStripTextBox();
this.toolStripLabel7 = new System.Windows.Forms.ToolStripLabel();
this.filterFieldTextBox = new System.Windows.Forms.ToolStripTextBox();
this.reportToolStrip = new System.Windows.Forms.ToolStrip();
this.toolStripLabel17 = new System.Windows.Forms.ToolStripLabel();
this.currentDiffLabel = new System.Windows.Forms.ToolStripLabel();
this.toolStripLabel13 = new System.Windows.Forms.ToolStripLabel();
this.diffCountLabel = new System.Windows.Forms.ToolStripLabel();
this.toolStripSeparator32 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripLabel19 = new System.Windows.Forms.ToolStripLabel();
this.matchPercentageLabel = new System.Windows.Forms.ToolStripLabel();
this.toolStripSeparator33 = new System.Windows.Forms.ToolStripSeparator();
this.addedLinesButton = new System.Windows.Forms.ToolStripButton();
this.addedLinesLabel = new System.Windows.Forms.ToolStripLabel();
this.missingLinesButton = new System.Windows.Forms.ToolStripButton();
this.missingLinesLabel = new System.Windows.Forms.ToolStripLabel();
this.changedLinesButton = new System.Windows.Forms.ToolStripButton();
this.changedLinesLabel = new System.Windows.Forms.ToolStripLabel();
this.memoryUsageTimer = new System.Windows.Forms.Timer(this.components);
spacer1 = new System.Windows.Forms.ToolStripStatusLabel();
this.statusStrip.SuspendLayout();
this.mainSplitContainer.Panel1.SuspendLayout();
this.mainSplitContainer.Panel2.SuspendLayout();
this.mainSplitContainer.SuspendLayout();
this.toolStripContainer1.BottomToolStripPanel.SuspendLayout();
this.toolStripContainer1.ContentPanel.SuspendLayout();
this.toolStripContainer1.TopToolStripPanel.SuspendLayout();
this.toolStripContainer1.SuspendLayout();
this.menuStrip.SuspendLayout();
this.commandToolStrip.SuspendLayout();
this.reportToolStrip.SuspendLayout();
this.SuspendLayout();
//
// spacer1
//
spacer1.AutoSize = false;
spacer1.Name = "spacer1";
spacer1.Size = new System.Drawing.Size(732, 17);
spacer1.Spring = true;
//
// statusStrip
//
this.statusStrip.Dock = System.Windows.Forms.DockStyle.None;
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.msgDropDown,
spacer1,
this.spacer2,
this.memoryStatusLabel,
this.spacer3,
this.legendLabel,
this.LegendCurrentDiffLabel,
this.LegendNonCurrentDiffLabel,
this.LegendCurrentOmittedLabel,
this.LegendNonCurrentOmittedLabel});
this.statusStrip.Location = new System.Drawing.Point(0, 0);
this.statusStrip.Name = "statusStrip";
this.statusStrip.ShowItemToolTips = true;
this.statusStrip.Size = new System.Drawing.Size(1028, 22);
this.statusStrip.TabIndex = 0;
this.statusStrip.Text = "statusStrip";
//
// msgDropDown
//
this.msgDropDown.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.msgDropDown.Image = ((System.Drawing.Image)(resources.GetObject("msgDropDown.Image")));
this.msgDropDown.ImageTransparentColor = System.Drawing.Color.Magenta;
this.msgDropDown.Name = "msgDropDown";
this.msgDropDown.Size = new System.Drawing.Size(30, 20);
this.msgDropDown.Text = "--";
this.msgDropDown.ToolTipText = "Status message history";
//
// spacer2
//
this.spacer2.AutoSize = false;
this.spacer2.Name = "spacer2";
this.spacer2.Size = new System.Drawing.Size(25, 17);
//
// memoryStatusLabel
//
this.memoryStatusLabel.AutoSize = false;
this.memoryStatusLabel.BackColor = System.Drawing.SystemColors.ControlText;
this.memoryStatusLabel.ForeColor = System.Drawing.SystemColors.ControlLight;
this.memoryStatusLabel.Name = "memoryStatusLabel";
this.memoryStatusLabel.Size = new System.Drawing.Size(45, 17);
this.memoryStatusLabel.Text = "--";
this.memoryStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.memoryStatusLabel.Click += new System.EventHandler(this.memoryStatusLabel_Click);
//
// spacer3
//
this.spacer3.AutoSize = false;
this.spacer3.Name = "spacer3";
this.spacer3.Size = new System.Drawing.Size(25, 17);
//
// legendLabel
//
this.legendLabel.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold);
this.legendLabel.Name = "legendLabel";
this.legendLabel.Size = new System.Drawing.Size(48, 17);
this.legendLabel.Text = "Legend";
this.legendLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// LegendCurrentDiffLabel
//
this.LegendCurrentDiffLabel.AutoSize = false;
this.LegendCurrentDiffLabel.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Right)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom)));
this.LegendCurrentDiffLabel.BorderStyle = System.Windows.Forms.Border3DStyle.Bump;
this.LegendCurrentDiffLabel.Margin = new System.Windows.Forms.Padding(2, 2, 0, 2);
this.LegendCurrentDiffLabel.Name = "LegendCurrentDiffLabel";
this.LegendCurrentDiffLabel.Size = new System.Drawing.Size(25, 18);
this.LegendCurrentDiffLabel.ToolTipText = "Current Diff--extra or different element";
//
// LegendNonCurrentDiffLabel
//
this.LegendNonCurrentDiffLabel.AutoSize = false;
this.LegendNonCurrentDiffLabel.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Right)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom)));
this.LegendNonCurrentDiffLabel.BorderStyle = System.Windows.Forms.Border3DStyle.Bump;
this.LegendNonCurrentDiffLabel.Margin = new System.Windows.Forms.Padding(2, 2, 0, 2);
this.LegendNonCurrentDiffLabel.Name = "LegendNonCurrentDiffLabel";
this.LegendNonCurrentDiffLabel.Size = new System.Drawing.Size(25, 18);
this.LegendNonCurrentDiffLabel.ToolTipText = "All differences except the current diff";
//
// LegendCurrentOmittedLabel
//
this.LegendCurrentOmittedLabel.AutoSize = false;
this.LegendCurrentOmittedLabel.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Right)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom)));
this.LegendCurrentOmittedLabel.BorderStyle = System.Windows.Forms.Border3DStyle.Bump;
this.LegendCurrentOmittedLabel.Margin = new System.Windows.Forms.Padding(2, 2, 0, 2);
this.LegendCurrentOmittedLabel.Name = "LegendCurrentOmittedLabel";
this.LegendCurrentOmittedLabel.Size = new System.Drawing.Size(25, 18);
this.LegendCurrentOmittedLabel.ToolTipText = "Current Diff--omitted element";
//
// LegendNonCurrentOmittedLabel
//
this.LegendNonCurrentOmittedLabel.AutoSize = false;
this.LegendNonCurrentOmittedLabel.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Right)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom)));
this.LegendNonCurrentOmittedLabel.BorderStyle = System.Windows.Forms.Border3DStyle.Bump;
this.LegendNonCurrentOmittedLabel.Margin = new System.Windows.Forms.Padding(2, 2, 0, 2);
this.LegendNonCurrentOmittedLabel.Name = "LegendNonCurrentOmittedLabel";
this.LegendNonCurrentOmittedLabel.Size = new System.Drawing.Size(25, 18);
this.LegendNonCurrentOmittedLabel.ToolTipText = "All omitted elements except the current diff";
//
// mainSplitContainer
//
this.mainSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.mainSplitContainer.Location = new System.Drawing.Point(0, 0);
this.mainSplitContainer.Margin = new System.Windows.Forms.Padding(0);
this.mainSplitContainer.Name = "mainSplitContainer";
//
// mainSplitContainer.Panel1
//
this.mainSplitContainer.Panel1.Controls.Add(this.leftSqlEditor);
//
// mainSplitContainer.Panel2
//
this.mainSplitContainer.Panel2.Controls.Add(this.rightSqlEditor);
this.mainSplitContainer.Size = new System.Drawing.Size(1028, 545);
this.mainSplitContainer.SplitterDistance = 512;
this.mainSplitContainer.TabIndex = 9;
this.mainSplitContainer.TabStop = false;
//
// leftSqlEditor
//
this.leftSqlEditor.AutoExecuteMode = false;
this.leftSqlEditor.AutoHighlightMode = true;
this.leftSqlEditor.CommandTimeout = 60;
this.leftSqlEditor.ContainerTest = false;
this.leftSqlEditor.CsvPath = ".";
this.leftSqlEditor.DateCellStyleFormat = null;
this.leftSqlEditor.DbConnectionName = "--";
this.leftSqlEditor.Dock = System.Windows.Forms.DockStyle.Fill;
this.leftSqlEditor.LocalMode = false;
this.leftSqlEditor.Location = new System.Drawing.Point(0, 0);
this.leftSqlEditor.MaxColumnWidth = 200;
this.leftSqlEditor.Name = "leftSqlEditor";
this.leftSqlEditor.Partner = null;
this.leftSqlEditor.RowLimitForBinaryFieldPatching = 50000;
this.leftSqlEditor.ShowBooleansAsCheckBoxes = false;
this.leftSqlEditor.Size = new System.Drawing.Size(512, 545);
this.leftSqlEditor.SqlPath = ".";
this.leftSqlEditor.StaleQueryColor = System.Drawing.Color.LightSteelBlue;
this.leftSqlEditor.TabIndex = 0;
this.leftSqlEditor.TabLeavesControl = false;
this.leftSqlEditor.TandemMode = false;
this.leftSqlEditor.TurboSortMode = false;
this.leftSqlEditor.UniqueNameHint = null;
this.leftSqlEditor.UserCommandsTitle = "SqlEditor Quick Reference";
//
// rightSqlEditor
//
this.rightSqlEditor.AutoExecuteMode = false;
this.rightSqlEditor.AutoHighlightMode = true;
this.rightSqlEditor.CommandTimeout = 60;
this.rightSqlEditor.ContainerTest = false;
this.rightSqlEditor.CsvPath = ".";
this.rightSqlEditor.DateCellStyleFormat = null;
this.rightSqlEditor.DbConnectionName = "--";
this.rightSqlEditor.Dock = System.Windows.Forms.DockStyle.Fill;
this.rightSqlEditor.LocalMode = false;
this.rightSqlEditor.Location = new System.Drawing.Point(0, 0);
this.rightSqlEditor.MaxColumnWidth = 200;
this.rightSqlEditor.Name = "rightSqlEditor";
this.rightSqlEditor.Partner = null;
this.rightSqlEditor.RowLimitForBinaryFieldPatching = 50000;
this.rightSqlEditor.ShowBooleansAsCheckBoxes = false;
this.rightSqlEditor.Size = new System.Drawing.Size(512, 545);
this.rightSqlEditor.SqlPath = ".";
this.rightSqlEditor.StaleQueryColor = System.Drawing.Color.LightSteelBlue;
this.rightSqlEditor.TabIndex = 0;
this.rightSqlEditor.TabLeavesControl = false;
this.rightSqlEditor.TandemMode = false;
this.rightSqlEditor.TurboSortMode = false;
this.rightSqlEditor.UniqueNameHint = null;
this.rightSqlEditor.UserCommandsTitle = "SqlEditor Quick Reference";
//
// toolStripContainer1
//
//
// toolStripContainer1.BottomToolStripPanel
//
this.toolStripContainer1.BottomToolStripPanel.Controls.Add(this.statusStrip);
//
// toolStripContainer1.ContentPanel
//
this.toolStripContainer1.ContentPanel.AutoScroll = true;
this.toolStripContainer1.ContentPanel.Controls.Add(this.mainSplitContainer);
this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(1028, 545);
this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolStripContainer1.Location = new System.Drawing.Point(0, 0);
this.toolStripContainer1.Name = "toolStripContainer1";
this.toolStripContainer1.Size = new System.Drawing.Size(1028, 641);
this.toolStripContainer1.TabIndex = 0;
this.toolStripContainer1.Text = "toolStripContainer1";
//
// toolStripContainer1.TopToolStripPanel
//
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.menuStrip);
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.commandToolStrip);
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.reportToolStrip);
//
// menuStrip
//
this.menuStrip.Dock = System.Windows.Forms.DockStyle.None;
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.viewToolStripMenuItem,
this.queryToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1028, 24);
this.menuStrip.TabIndex = 0;
this.menuStrip.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newWorkspaceToolStripMenuItem,
this.toolStripSeparator1,
this.newQueryMenuItem,
this.openQueryToolStripMenuItem,
this.toolStripSeparator16,
this.saveLeftQueryMenuItem,
this.saveRightQueryMenuItem,
this.toolStripSeparator18,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// newWorkspaceToolStripMenuItem
//
this.newWorkspaceToolStripMenuItem.Name = "newWorkspaceToolStripMenuItem";
this.newWorkspaceToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.newWorkspaceToolStripMenuItem.Size = new System.Drawing.Size(210, 22);
this.newWorkspaceToolStripMenuItem.Text = "&New Workspace";
this.newWorkspaceToolStripMenuItem.ToolTipText = "Open another instance of SqlDiffFramework";
this.newWorkspaceToolStripMenuItem.Click += new System.EventHandler(this.newWorkspaceMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(207, 6);
//
// newQueryMenuItem
//
this.newQueryMenuItem.Name = "newQueryMenuItem";
this.newQueryMenuItem.ShortcutKeyDisplayString = "";
this.newQueryMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.W)));
this.newQueryMenuItem.Size = new System.Drawing.Size(210, 22);
this.newQueryMenuItem.Text = "Ne&w Query";
this.newQueryMenuItem.Click += new System.EventHandler(this.newQueryMenuItem_Click);
//
// openQueryToolStripMenuItem
//
this.openQueryToolStripMenuItem.Name = "openQueryToolStripMenuItem";
this.openQueryToolStripMenuItem.ShortcutKeyDisplayString = "";
this.openQueryToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.O)));
this.openQueryToolStripMenuItem.Size = new System.Drawing.Size(210, 22);
this.openQueryToolStripMenuItem.Text = "&Open Query";
this.openQueryToolStripMenuItem.Click += new System.EventHandler(this.openQueryToolStripMenuItem_Click);
//
// toolStripSeparator16
//
this.toolStripSeparator16.Name = "toolStripSeparator16";
this.toolStripSeparator16.Size = new System.Drawing.Size(207, 6);
//
// saveLeftQueryMenuItem
//
this.saveLeftQueryMenuItem.Name = "saveLeftQueryMenuItem";
this.saveLeftQueryMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F8)));
this.saveLeftQueryMenuItem.Size = new System.Drawing.Size(210, 22);
this.saveLeftQueryMenuItem.Text = "Save &Left Query";
this.saveLeftQueryMenuItem.Click += new System.EventHandler(this.saveLeftQueryMenuItem_Click);
//
// saveRightQueryMenuItem
//
this.saveRightQueryMenuItem.Name = "saveRightQueryMenuItem";
this.saveRightQueryMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F9)));
this.saveRightQueryMenuItem.Size = new System.Drawing.Size(210, 22);
this.saveRightQueryMenuItem.Text = "Save &Right Query";
this.saveRightQueryMenuItem.Click += new System.EventHandler(this.saveRightQueryMenuItem_Click);
//
// toolStripSeparator18
//
this.toolStripSeparator18.Name = "toolStripSeparator18";
this.toolStripSeparator18.Size = new System.Drawing.Size(207, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F4)));
this.exitToolStripMenuItem.Size = new System.Drawing.Size(210, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.toolStripSeparator34,
this.tabLeavesControlMenuItem,
this.tabInsertsSpacesMenuItem,
this.toolStripSeparator2,
this.findToolStripMenuItem,
this.replaceToolStripMenuItem,
this.toolStripSeparator3,
this.restoreSettingsMenuItem,
this.optionsToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20);
this.editToolStripMenuItem.Text = "&Edit";
//
// cutToolStripMenuItem
//
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.Size = new System.Drawing.Size(169, 22);
this.cutToolStripMenuItem.Text = "Cu&t";
this.cutToolStripMenuItem.Visible = false;
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.Size = new System.Drawing.Size(169, 22);
this.copyToolStripMenuItem.Text = "&Copy";
this.copyToolStripMenuItem.Visible = false;
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(169, 22);
this.pasteToolStripMenuItem.Text = "&Paste";
this.pasteToolStripMenuItem.Visible = false;
//
// toolStripSeparator34
//
this.toolStripSeparator34.Name = "toolStripSeparator34";
this.toolStripSeparator34.Size = new System.Drawing.Size(166, 6);
this.toolStripSeparator34.Visible = false;
//
// tabLeavesControlMenuItem
//
this.tabLeavesControlMenuItem.CheckOnClick = true;
this.tabLeavesControlMenuItem.Name = "tabLeavesControlMenuItem";
this.tabLeavesControlMenuItem.Size = new System.Drawing.Size(169, 22);
this.tabLeavesControlMenuItem.Text = "&Tab Leaves Pane";
this.tabLeavesControlMenuItem.ToolTipText = "Toggle behavior of tab/ctrl-tab moving within input/output panes";
this.tabLeavesControlMenuItem.Visible = false;
this.tabLeavesControlMenuItem.Click += new System.EventHandler(this.tabLeavesControlMenuItem_Click);
//
// tabInsertsSpacesMenuItem
//
this.tabInsertsSpacesMenuItem.CheckOnClick = true;
this.tabInsertsSpacesMenuItem.Name = "tabInsertsSpacesMenuItem";
this.tabInsertsSpacesMenuItem.Size = new System.Drawing.Size(169, 22);
this.tabInsertsSpacesMenuItem.Text = "Tab &Inserts Spaces";
this.tabInsertsSpacesMenuItem.ToolTipText = "If disabled, Tab inserts an actual Tab";
this.tabInsertsSpacesMenuItem.Visible = false;
this.tabInsertsSpacesMenuItem.Click += new System.EventHandler(this.tabInsertsSpacesMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(166, 6);
this.toolStripSeparator2.Visible = false;
//
// findToolStripMenuItem
//
this.findToolStripMenuItem.Name = "findToolStripMenuItem";
this.findToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F)));
this.findToolStripMenuItem.Size = new System.Drawing.Size(169, 22);
this.findToolStripMenuItem.Text = "&Find...";
this.findToolStripMenuItem.Click += new System.EventHandler(this.findToolStripMenuItem_Click);
//
// replaceToolStripMenuItem
//
this.replaceToolStripMenuItem.Name = "replaceToolStripMenuItem";
this.replaceToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.H)));
this.replaceToolStripMenuItem.Size = new System.Drawing.Size(169, 22);
this.replaceToolStripMenuItem.Text = "&Replace...";
this.replaceToolStripMenuItem.Click += new System.EventHandler(this.replaceToolStripMenuItem_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(166, 6);
//
// restoreSettingsMenuItem
//
this.restoreSettingsMenuItem.Name = "restoreSettingsMenuItem";
this.restoreSettingsMenuItem.Size = new System.Drawing.Size(169, 22);
this.restoreSettingsMenuItem.Text = "Restore &Settings...";
this.restoreSettingsMenuItem.ToolTipText = "Restore settings to last saved or to factory defaults";
this.restoreSettingsMenuItem.Click += new System.EventHandler(this.restoreSettingsMenuItem_Click);
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(169, 22);
this.optionsToolStripMenuItem.Text = "&Options...";
this.optionsToolStripMenuItem.Click += new System.EventHandler(this.optionsToolStripMenuItem_Click);
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.nextDifferenceMenuItem,
this.previousDifferenceMenuItem,
this.toolStripSeparator14,
this.firstDifferenceMenuItem,
this.currentDifferenceMenuItem,
this.lastDifferenceMenuItem,
this.setCurrentDifferenceMenuItem,
this.toolStripSeparator25,
this.showProgressMenuItem,
this.toolStripSeparator19,
this.showLeftPaneMenuItem,
this.showRightPaneMenuItem,
this.showBothPanesMenuItem});
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
this.viewToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.viewToolStripMenuItem.Text = "&View";
//
// nextDifferenceMenuItem
//
this.nextDifferenceMenuItem.Enabled = false;
this.nextDifferenceMenuItem.Name = "nextDifferenceMenuItem";
this.nextDifferenceMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.Down)));
this.nextDifferenceMenuItem.Size = new System.Drawing.Size(228, 22);
this.nextDifferenceMenuItem.Text = "&Next Difference";
this.nextDifferenceMenuItem.Click += new System.EventHandler(this.nextDifferenceMenuItem_Click);
//
// previousDifferenceMenuItem
//
this.previousDifferenceMenuItem.Enabled = false;
this.previousDifferenceMenuItem.Name = "previousDifferenceMenuItem";
this.previousDifferenceMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.Up)));
this.previousDifferenceMenuItem.Size = new System.Drawing.Size(228, 22);
this.previousDifferenceMenuItem.Text = "&Previous Difference";
this.previousDifferenceMenuItem.Click += new System.EventHandler(this.previousDifferenceMenuItem_Click);
//
// toolStripSeparator14
//
this.toolStripSeparator14.Name = "toolStripSeparator14";
this.toolStripSeparator14.Size = new System.Drawing.Size(225, 6);
//
// firstDifferenceMenuItem
//
this.firstDifferenceMenuItem.Enabled = false;
this.firstDifferenceMenuItem.Name = "firstDifferenceMenuItem";
this.firstDifferenceMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.Home)));
this.firstDifferenceMenuItem.Size = new System.Drawing.Size(228, 22);
this.firstDifferenceMenuItem.Text = "&First Difference";
this.firstDifferenceMenuItem.Click += new System.EventHandler(this.firstDifferenceMenuItem_Click);
//
// currentDifferenceMenuItem
//
this.currentDifferenceMenuItem.Enabled = false;
this.currentDifferenceMenuItem.Name = "currentDifferenceMenuItem";
this.currentDifferenceMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.Return)));
this.currentDifferenceMenuItem.Size = new System.Drawing.Size(228, 22);
this.currentDifferenceMenuItem.Text = "&Current Difference";
this.currentDifferenceMenuItem.Click += new System.EventHandler(this.currentDifferenceMenuItem_Click);
//
// lastDifferenceMenuItem
//
this.lastDifferenceMenuItem.Enabled = false;
this.lastDifferenceMenuItem.Name = "lastDifferenceMenuItem";
this.lastDifferenceMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.End)));
this.lastDifferenceMenuItem.Size = new System.Drawing.Size(228, 22);
this.lastDifferenceMenuItem.Text = "&Last Difference";
this.lastDifferenceMenuItem.Click += new System.EventHandler(this.lastDifferenceMenuItem_Click);
//
// setCurrentDifferenceMenuItem
//
this.setCurrentDifferenceMenuItem.Enabled = false;
this.setCurrentDifferenceMenuItem.Name = "setCurrentDifferenceMenuItem";
this.setCurrentDifferenceMenuItem.ShortcutKeyDisplayString = "Alt+.";
this.setCurrentDifferenceMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.OemPeriod)));
this.setCurrentDifferenceMenuItem.Size = new System.Drawing.Size(228, 22);
this.setCurrentDifferenceMenuItem.Text = "&Set Current Difference";
this.setCurrentDifferenceMenuItem.Click += new System.EventHandler(this.setCurrentDifferenceMenuItem_Click);
//
// toolStripSeparator25
//
this.toolStripSeparator25.Name = "toolStripSeparator25";
this.toolStripSeparator25.Size = new System.Drawing.Size(225, 6);
//
// showProgressMenuItem
//
this.showProgressMenuItem.CheckOnClick = true;
this.showProgressMenuItem.Name = "showProgressMenuItem";
this.showProgressMenuItem.Size = new System.Drawing.Size(228, 22);
this.showProgressMenuItem.Text = "Show Progress &Monitor ";
this.showProgressMenuItem.Click += new System.EventHandler(this.showProgressMenuItem_Click);
//
// toolStripSeparator19
//
this.toolStripSeparator19.Name = "toolStripSeparator19";
this.toolStripSeparator19.Size = new System.Drawing.Size(225, 6);
//
// showLeftPaneMenuItem
//
this.showLeftPaneMenuItem.Name = "showLeftPaneMenuItem";
this.showLeftPaneMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D1)));
this.showLeftPaneMenuItem.Size = new System.Drawing.Size(228, 22);
this.showLeftPaneMenuItem.Text = "&Expand Left Pane";
this.showLeftPaneMenuItem.Click += new System.EventHandler(this.showLeftPaneMenuItem_Click);
//
// showRightPaneMenuItem
//
this.showRightPaneMenuItem.Name = "showRightPaneMenuItem";
this.showRightPaneMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D2)));
this.showRightPaneMenuItem.Size = new System.Drawing.Size(228, 22);
this.showRightPaneMenuItem.Text = "Expand &Right Pane";
this.showRightPaneMenuItem.Click += new System.EventHandler(this.showRightPaneMenuItem_Click);
//
// showBothPanesMenuItem
//
this.showBothPanesMenuItem.Name = "showBothPanesMenuItem";
this.showBothPanesMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D3)));
this.showBothPanesMenuItem.Size = new System.Drawing.Size(228, 22);
this.showBothPanesMenuItem.Text = "Show &Both Panes";
this.showBothPanesMenuItem.Click += new System.EventHandler(this.showBothPanesMenuItem_Click);
//
// queryToolStripMenuItem
//
this.queryToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.executeQueryMenuItem,
this.executeBatchMenuItem,
this.toolStripSeparator7,
this.metaQueriesMenuItem,
this.editConnectionsMenuItem,
this.mirrorQueryMenuItem});
this.queryToolStripMenuItem.Name = "queryToolStripMenuItem";
this.queryToolStripMenuItem.Size = new System.Drawing.Size(51, 20);
this.queryToolStripMenuItem.Text = "&Query";
//
// executeQueryMenuItem
//
this.executeQueryMenuItem.Name = "executeQueryMenuItem";
this.executeQueryMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F5;
this.executeQueryMenuItem.Size = new System.Drawing.Size(219, 22);
this.executeQueryMenuItem.Text = "E&xecute Query";
this.executeQueryMenuItem.Click += new System.EventHandler(this.executeQueryMenuItem_Click);
//
// executeBatchMenuItem
//
this.executeBatchMenuItem.Name = "executeBatchMenuItem";
this.executeBatchMenuItem.Size = new System.Drawing.Size(219, 22);
this.executeBatchMenuItem.Text = "Execute &Batch...";
this.executeBatchMenuItem.Click += new System.EventHandler(this.executeBatchMenuItem_Click);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(216, 6);
//
// metaQueriesMenuItem
//
this.metaQueriesMenuItem.Name = "metaQueriesMenuItem";
this.metaQueriesMenuItem.ShortcutKeyDisplayString = "Ctrl+F2";
this.metaQueriesMenuItem.Size = new System.Drawing.Size(219, 22);
this.metaQueriesMenuItem.Text = "&Meta-Queries...";
this.metaQueriesMenuItem.ToolTipText = "Find database meta-information\n(Press Shift to reload query library)";
this.metaQueriesMenuItem.Click += new System.EventHandler(this.metaQueriesMenuItem_Click);
//
// editConnectionsMenuItem
//
this.editConnectionsMenuItem.Name = "editConnectionsMenuItem";
this.editConnectionsMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F3)));
this.editConnectionsMenuItem.Size = new System.Drawing.Size(219, 22);
this.editConnectionsMenuItem.Text = "Edit &Connections...";
this.editConnectionsMenuItem.ToolTipText = "Add or change connection details";
this.editConnectionsMenuItem.Click += new System.EventHandler(this.editConnectionsMenuItem_Click);
//
// mirrorQueryMenuItem
//
this.mirrorQueryMenuItem.Name = "mirrorQueryMenuItem";
this.mirrorQueryMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.M)));
this.mirrorQueryMenuItem.Size = new System.Drawing.Size(219, 22);
this.mirrorQueryMenuItem.Text = "Mirror &Query...";
this.mirrorQueryMenuItem.ToolTipText = "Copy settings and text from one pane to the other";
this.mirrorQueryMenuItem.Click += new System.EventHandler(this.mirrorQueryMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.userGuideMenuItem,
this.toolStripSeparator9,
this.showMainKeyReferenceToolStripMenuItem,
this.showGeneralKeyReferenceMenuItem,
this.showInputKeyReferenceMenuItem,
this.showOutputKeyReferenceMenuItem,
this.toolStripSeparator8,
this.aboutMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "&Help";
//
// userGuideMenuItem
//
this.userGuideMenuItem.Name = "userGuideMenuItem";
this.userGuideMenuItem.Size = new System.Drawing.Size(289, 22);
this.userGuideMenuItem.Text = "&User Guide";
this.userGuideMenuItem.Click += new System.EventHandler(this.userGuideMenuItem_Click);
//
// toolStripSeparator9
//
this.toolStripSeparator9.Name = "toolStripSeparator9";
this.toolStripSeparator9.Size = new System.Drawing.Size(286, 6);
//
// showMainKeyReferenceToolStripMenuItem
//
this.showMainKeyReferenceToolStripMenuItem.Name = "showMainKeyReferenceToolStripMenuItem";
this.showMainKeyReferenceToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Shift | System.Windows.Forms.Keys.F1)));
this.showMainKeyReferenceToolStripMenuItem.Size = new System.Drawing.Size(289, 22);
this.showMainKeyReferenceToolStripMenuItem.Text = "Show &Main Key Reference";
this.showMainKeyReferenceToolStripMenuItem.Click += new System.EventHandler(this.showMainKeyReferenceMenuItem_Click);
//
// showGeneralKeyReferenceMenuItem
//
this.showGeneralKeyReferenceMenuItem.Name = "showGeneralKeyReferenceMenuItem";
this.showGeneralKeyReferenceMenuItem.ShortcutKeyDisplayString = "Ctrl+F1";
this.showGeneralKeyReferenceMenuItem.Size = new System.Drawing.Size(289, 22);
this.showGeneralKeyReferenceMenuItem.Text = "Show &Editor Pane Key Reference";
this.showGeneralKeyReferenceMenuItem.Click += new System.EventHandler(this.showEditorPaneKeyReferenceMenuItem_Click);
//
// showInputKeyReferenceMenuItem
//
this.showInputKeyReferenceMenuItem.Name = "showInputKeyReferenceMenuItem";
this.showInputKeyReferenceMenuItem.ShortcutKeyDisplayString = "F1";
this.showInputKeyReferenceMenuItem.Size = new System.Drawing.Size(289, 22);
this.showInputKeyReferenceMenuItem.Text = "Show &Input Key Reference";
this.showInputKeyReferenceMenuItem.Click += new System.EventHandler(this.showInputKeyReferenceMenuItem_Click);
//
// showOutputKeyReferenceMenuItem
//
this.showOutputKeyReferenceMenuItem.Name = "showOutputKeyReferenceMenuItem";
this.showOutputKeyReferenceMenuItem.ShortcutKeyDisplayString = "F1";
this.showOutputKeyReferenceMenuItem.Size = new System.Drawing.Size(289, 22);
this.showOutputKeyReferenceMenuItem.Text = "Show &Output Key Reference";
this.showOutputKeyReferenceMenuItem.Click += new System.EventHandler(this.showOutputKeyReferenceMenuItem_Click);
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
this.toolStripSeparator8.Size = new System.Drawing.Size(286, 6);
//
// aboutMenuItem
//
this.aboutMenuItem.Name = "aboutMenuItem";
this.aboutMenuItem.Size = new System.Drawing.Size(289, 22);
this.aboutMenuItem.Text = "&About SqlDiffFramework";
this.aboutMenuItem.Click += new System.EventHandler(this.aboutMenuItem_Click);
//
// commandToolStrip
//
this.commandToolStrip.Dock = System.Windows.Forms.DockStyle.None;
this.commandToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.nextDiffButton,
this.previousDiffButton,
this.toolStripSeparator5,
this.firstDiffButton,
this.currentDiffButton,
this.lastDiffButton,
this.setCurrentDiffButton,
this.toolStripSeparator4,
this.turboSortButton,
this.tandemButton,
this.autoDiffButton,
this.autoDiffSplitButton,
this.toolStripSeparator6,
this.showProgressButton,
this.toolStripLabel2,
this.filterValueTextBox,
this.toolStripLabel7,
this.filterFieldTextBox});
this.commandToolStrip.Location = new System.Drawing.Point(3, 24);
this.commandToolStrip.Name = "commandToolStrip";
this.commandToolStrip.Size = new System.Drawing.Size(336, 25);
this.commandToolStrip.TabIndex = 1;
//
// nextDiffButton
//
this.nextDiffButton.AutoToolTip = false;
this.nextDiffButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.nextDiffButton.Enabled = false;
this.nextDiffButton.Image = ((System.Drawing.Image)(resources.GetObject("nextDiffButton.Image")));
this.nextDiffButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.nextDiffButton.Name = "nextDiffButton";
this.nextDiffButton.Size = new System.Drawing.Size(23, 22);
this.nextDiffButton.Text = "Next";
this.nextDiffButton.ToolTipText = "Next Difference (Alt+Down)";
this.nextDiffButton.Click += new System.EventHandler(this.nextDiffButton_Click);
//
// previousDiffButton
//
this.previousDiffButton.AutoToolTip = false;
this.previousDiffButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.previousDiffButton.Enabled = false;
this.previousDiffButton.Image = ((System.Drawing.Image)(resources.GetObject("previousDiffButton.Image")));
this.previousDiffButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.previousDiffButton.Name = "previousDiffButton";
this.previousDiffButton.Size = new System.Drawing.Size(23, 22);
this.previousDiffButton.Text = "Previous";
this.previousDiffButton.ToolTipText = "Previous Difference (Alt+Up)";
this.previousDiffButton.Click += new System.EventHandler(this.previousDiffButton_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(6, 25);
//
// firstDiffButton
//
this.firstDiffButton.AutoToolTip = false;
this.firstDiffButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.firstDiffButton.Enabled = false;
this.firstDiffButton.Image = ((System.Drawing.Image)(resources.GetObject("firstDiffButton.Image")));
this.firstDiffButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.firstDiffButton.Name = "firstDiffButton";
this.firstDiffButton.Size = new System.Drawing.Size(23, 22);
this.firstDiffButton.ToolTipText = "First Difference (Alt+Home)";
this.firstDiffButton.Click += new System.EventHandler(this.firstDiffButton_Click);
//
// currentDiffButton
//
this.currentDiffButton.AutoToolTip = false;
this.currentDiffButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.currentDiffButton.Enabled = false;
this.currentDiffButton.Image = ((System.Drawing.Image)(resources.GetObject("currentDiffButton.Image")));
this.currentDiffButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.currentDiffButton.Name = "currentDiffButton";
this.currentDiffButton.Size = new System.Drawing.Size(23, 22);
this.currentDiffButton.ToolTipText = "Current Difference (Alt+Enter)";
this.currentDiffButton.Click += new System.EventHandler(this.currentDiffButton_Click);
//
// lastDiffButton
//
this.lastDiffButton.AutoToolTip = false;
this.lastDiffButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.lastDiffButton.Enabled = false;
this.lastDiffButton.Image = ((System.Drawing.Image)(resources.GetObject("lastDiffButton.Image")));
this.lastDiffButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.lastDiffButton.Name = "lastDiffButton";
this.lastDiffButton.Size = new System.Drawing.Size(23, 22);
this.lastDiffButton.ToolTipText = "Last Difference (Alt+End)";
this.lastDiffButton.Click += new System.EventHandler(this.lastDiffButton_Click);
//
// setCurrentDiffButton
//
this.setCurrentDiffButton.AutoToolTip = false;
this.setCurrentDiffButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.setCurrentDiffButton.Enabled = false;
this.setCurrentDiffButton.Image = global::SqlDiffFramework.Properties.Resources.current_diff_set;
this.setCurrentDiffButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.setCurrentDiffButton.Name = "setCurrentDiffButton";
this.setCurrentDiffButton.Size = new System.Drawing.Size(23, 22);
this.setCurrentDiffButton.ToolTipText = "Set current difference to selection (Alt+.)";
this.setCurrentDiffButton.Click += new System.EventHandler(this.setCurrentDiffButton_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(6, 25);
//
// turboSortButton
//
this.turboSortButton.AutoSize = false;
this.turboSortButton.AutoToolTip = false;
this.turboSortButton.Checked = global::SqlDiffFramework.Properties.Settings.Default.TurboSortButton_Checked;
this.turboSortButton.CheckOnClick = true;
this.turboSortButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.turboSortButton.Image = global::SqlDiffFramework.Properties.Resources.turboSort;
this.turboSortButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.turboSortButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.turboSortButton.Name = "turboSortButton";
this.turboSortButton.Size = new System.Drawing.Size(55, 22);
this.turboSortButton.ToolTipText = "Re-sort internally to normalize possible sort differences (e.g. between Oracle an" +
"d SQL Server)";
this.turboSortButton.Click += new System.EventHandler(this.turboSortButton_Click);
//
// tandemButton
//
this.tandemButton.AutoSize = false;
this.tandemButton.AutoToolTip = false;
this.tandemButton.Checked = global::SqlDiffFramework.Properties.Settings.Default.TandemButton_Checked;
this.tandemButton.CheckOnClick = true;
this.tandemButton.CheckState = System.Windows.Forms.CheckState.Checked;
this.tandemButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tandemButton.Image = global::SqlDiffFramework.Properties.Resources.link;
this.tandemButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tandemButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tandemButton.Name = "tandemButton";
this.tandemButton.Size = new System.Drawing.Size(44, 22);
this.tandemButton.Text = "Tandem";
this.tandemButton.ToolTipText = "Load corresponding left or right file automatically when the other is loaded manu" +
"ally.";
this.tandemButton.Click += new System.EventHandler(this.tandemButton_Click);
//
// autoDiffButton
//
this.autoDiffButton.Checked = global::SqlDiffFramework.Properties.Settings.Default.AutoDiffButton_Checked;
this.autoDiffButton.CheckOnClick = true;
this.autoDiffButton.CheckState = System.Windows.Forms.CheckState.Checked;
this.autoDiffButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.autoDiffButton.Image = ((System.Drawing.Image)(resources.GetObject("autoDiffButton.Image")));
this.autoDiffButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.autoDiffButton.Name = "autoDiffButton";
this.autoDiffButton.Size = new System.Drawing.Size(30, 22);
this.autoDiffButton.Text = "Diff";
this.autoDiffButton.ToolTipText = "Enable auto-diff upon grid load";
this.autoDiffButton.Click += new System.EventHandler(this.autoDiffButton_Click);
//
// autoDiffSplitButton
//
this.autoDiffSplitButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.autoDiffSplitButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.taubererDiffMenuItem,
this.hertelDiffMenuItem,
this.potterDiffMenuItem});
this.autoDiffSplitButton.Image = ((System.Drawing.Image)(resources.GetObject("autoDiffSplitButton.Image")));
this.autoDiffSplitButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.autoDiffSplitButton.Name = "autoDiffSplitButton";
this.autoDiffSplitButton.Size = new System.Drawing.Size(16, 22);
//
// taubererDiffMenuItem
//
this.taubererDiffMenuItem.Name = "taubererDiffMenuItem";
this.taubererDiffMenuItem.Size = new System.Drawing.Size(120, 22);
this.taubererDiffMenuItem.Text = "Tauberer";
this.taubererDiffMenuItem.ToolTipText = "handles larger data set but not always accurate on larger data sets (count marked" +
" with *)";
//
// hertelDiffMenuItem
//
this.hertelDiffMenuItem.Name = "hertelDiffMenuItem";
this.hertelDiffMenuItem.Size = new System.Drawing.Size(120, 22);
this.hertelDiffMenuItem.Text = "Hertel";
this.hertelDiffMenuItem.ToolTipText = "memory hog but always accurate";
//
// potterDiffMenuItem
//
this.potterDiffMenuItem.Name = "potterDiffMenuItem";
this.potterDiffMenuItem.Size = new System.Drawing.Size(120, 22);
this.potterDiffMenuItem.Text = "Potter";
this.potterDiffMenuItem.ToolTipText = "slower on largest data sets but always accurate";
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(6, 25);
//
// showProgressButton
//
this.showProgressButton.CheckOnClick = true;
this.showProgressButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.showProgressButton.Image = ((System.Drawing.Image)(resources.GetObject("showProgressButton.Image")));
this.showProgressButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.showProgressButton.Name = "showProgressButton";
this.showProgressButton.Size = new System.Drawing.Size(23, 22);
this.showProgressButton.ToolTipText = "Show Progress Monitor";
this.showProgressButton.Click += new System.EventHandler(this.showProgressButton_Click);
//
// toolStripLabel2
//
this.toolStripLabel2.Name = "toolStripLabel2";
this.toolStripLabel2.Size = new System.Drawing.Size(33, 22);
this.toolStripLabel2.Text = "Filter";
this.toolStripLabel2.Visible = false;
//
// filterValueTextBox
//
this.filterValueTextBox.Name = "filterValueTextBox";
this.filterValueTextBox.Size = new System.Drawing.Size(50, 25);
this.filterValueTextBox.ToolTipText = "Show only rows with this value";
this.filterValueTextBox.Visible = false;
//
// toolStripLabel7
//
this.toolStripLabel7.Name = "toolStripLabel7";
this.toolStripLabel7.Size = new System.Drawing.Size(32, 22);
this.toolStripLabel7.Text = "Field";
this.toolStripLabel7.Visible = false;
//
// filterFieldTextBox
//
this.filterFieldTextBox.Name = "filterFieldTextBox";
this.filterFieldTextBox.Size = new System.Drawing.Size(50, 25);
this.filterFieldTextBox.ToolTipText = "Common field name to filter on";
this.filterFieldTextBox.Visible = false;
//
// reportToolStrip
//
this.reportToolStrip.Dock = System.Windows.Forms.DockStyle.None;
this.reportToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripLabel17,
this.currentDiffLabel,
this.toolStripLabel13,
this.diffCountLabel,
this.toolStripSeparator32,
this.toolStripLabel19,
this.matchPercentageLabel,
this.toolStripSeparator33,
this.addedLinesButton,
this.addedLinesLabel,
this.missingLinesButton,
this.missingLinesLabel,
this.changedLinesButton,
this.changedLinesLabel});
this.reportToolStrip.Location = new System.Drawing.Point(3, 49);
this.reportToolStrip.Name = "reportToolStrip";
this.reportToolStrip.Size = new System.Drawing.Size(417, 25);
this.reportToolStrip.TabIndex = 2;
//
// toolStripLabel17
//
this.toolStripLabel17.Name = "toolStripLabel17";
this.toolStripLabel17.Size = new System.Drawing.Size(72, 22);
this.toolStripLabel17.Text = "Current Diff:";
//
// currentDiffLabel
//
this.currentDiffLabel.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold);
this.currentDiffLabel.Name = "currentDiffLabel";
this.currentDiffLabel.Size = new System.Drawing.Size(17, 22);
this.currentDiffLabel.Text = "--";
this.currentDiffLabel.ToolTipText = "Index of Current Diff Chunk";
//
// toolStripLabel13
//
this.toolStripLabel13.Name = "toolStripLabel13";
this.toolStripLabel13.Size = new System.Drawing.Size(18, 22);
this.toolStripLabel13.Text = "of";
//
// diffCountLabel
//
this.diffCountLabel.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold);
this.diffCountLabel.Name = "diffCountLabel";
this.diffCountLabel.Size = new System.Drawing.Size(17, 22);
this.diffCountLabel.Text = "--";
this.diffCountLabel.ToolTipText = "Total Number of Diff Chunks";
//
// toolStripSeparator32
//
this.toolStripSeparator32.Name = "toolStripSeparator32";
this.toolStripSeparator32.Size = new System.Drawing.Size(6, 25);
//
// toolStripLabel19
//
this.toolStripLabel19.Name = "toolStripLabel19";
this.toolStripLabel19.Size = new System.Drawing.Size(44, 22);
this.toolStripLabel19.Text = "Match:";
//
// matchPercentageLabel
//
this.matchPercentageLabel.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold);
this.matchPercentageLabel.Name = "matchPercentageLabel";
this.matchPercentageLabel.Size = new System.Drawing.Size(17, 22);
this.matchPercentageLabel.Text = "--";
this.matchPercentageLabel.ToolTipText = "Percentage of lines matching vs. total lines";
//
// toolStripSeparator33
//
this.toolStripSeparator33.Name = "toolStripSeparator33";
this.toolStripSeparator33.Size = new System.Drawing.Size(6, 25);
//
// addedLinesButton
//
this.addedLinesButton.AutoToolTip = false;
this.addedLinesButton.CheckOnClick = true;
this.addedLinesButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.addedLinesButton.Image = ((System.Drawing.Image)(resources.GetObject("addedLinesButton.Image")));
this.addedLinesButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.addedLinesButton.Name = "addedLinesButton";
this.addedLinesButton.Size = new System.Drawing.Size(46, 22);
this.addedLinesButton.Text = "Added";
this.addedLinesButton.ToolTipText = "Include added rows in diff navigation";
//
// addedLinesLabel
//
this.addedLinesLabel.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold);
this.addedLinesLabel.Name = "addedLinesLabel";
this.addedLinesLabel.Size = new System.Drawing.Size(17, 22);
this.addedLinesLabel.Text = "--";
this.addedLinesLabel.ToolTipText = "Lines added to left table";
//
// missingLinesButton
//
this.missingLinesButton.AutoToolTip = false;
this.missingLinesButton.CheckOnClick = true;
this.missingLinesButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.missingLinesButton.Image = ((System.Drawing.Image)(resources.GetObject("missingLinesButton.Image")));
this.missingLinesButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.missingLinesButton.Name = "missingLinesButton";
this.missingLinesButton.Size = new System.Drawing.Size(52, 22);
this.missingLinesButton.Text = "Missing";
this.missingLinesButton.ToolTipText = "Include missing rows in diff navigation";
//
// missingLinesLabel
//
this.missingLinesLabel.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold);
this.missingLinesLabel.Name = "missingLinesLabel";
this.missingLinesLabel.Size = new System.Drawing.Size(17, 22);
this.missingLinesLabel.Text = "--";
this.missingLinesLabel.ToolTipText = "Lines missing from left table";
//
// changedLinesButton
//
this.changedLinesButton.AutoToolTip = false;
this.changedLinesButton.CheckOnClick = true;
this.changedLinesButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.changedLinesButton.Image = ((System.Drawing.Image)(resources.GetObject("changedLinesButton.Image")));
this.changedLinesButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.changedLinesButton.Name = "changedLinesButton";
this.changedLinesButton.Size = new System.Drawing.Size(59, 22);
this.changedLinesButton.Text = "Changed";
this.changedLinesButton.ToolTipText = "Include changed rows in diff navigation";
//
// changedLinesLabel
//
this.changedLinesLabel.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold);
this.changedLinesLabel.Name = "changedLinesLabel";
this.changedLinesLabel.Size = new System.Drawing.Size(17, 22);
this.changedLinesLabel.Text = "--";
this.changedLinesLabel.ToolTipText = "Lines changed between left and right tables";
//
// memoryUsageTimer
//
this.memoryUsageTimer.Interval = 1000;
this.memoryUsageTimer.Tick += new System.EventHandler(this.memoryUsageTimer_Tick);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1028, 641);
this.Controls.Add(this.toolStripContainer1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip;
this.Name = "MainForm";
this.Text = "SqlDiffFramework";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
this.Load += new System.EventHandler(this.MainForm_Load);
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.mainSplitContainer.Panel1.ResumeLayout(false);
this.mainSplitContainer.Panel2.ResumeLayout(false);
this.mainSplitContainer.ResumeLayout(false);
this.toolStripContainer1.BottomToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.BottomToolStripPanel.PerformLayout();
this.toolStripContainer1.ContentPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.PerformLayout();
this.toolStripContainer1.ResumeLayout(false);
this.toolStripContainer1.PerformLayout();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.commandToolStrip.ResumeLayout(false);
this.commandToolStrip.PerformLayout();
this.reportToolStrip.ResumeLayout(false);
this.reportToolStrip.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.ToolStripDropDownButton msgDropDown;
private System.Windows.Forms.SplitContainer mainSplitContainer;
private System.Windows.Forms.ToolStripContainer toolStripContainer1;
private System.Windows.Forms.ToolStrip commandToolStrip;
private System.Windows.Forms.ToolStripButton nextDiffButton;
private System.Windows.Forms.ToolStripButton previousDiffButton;
private System.Windows.Forms.ToolStripButton currentDiffButton;
private System.Windows.Forms.ToolStripButton firstDiffButton;
private System.Windows.Forms.ToolStripButton lastDiffButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
//private System.Windows.Forms.ToolStripButton useLocalDataButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripStatusLabel LegendCurrentOmittedLabel;
private System.Windows.Forms.ToolStripStatusLabel LegendCurrentDiffLabel;
private System.Windows.Forms.ToolStripStatusLabel legendLabel;
private System.Windows.Forms.ToolStripStatusLabel LegendNonCurrentDiffLabel;
private System.Windows.Forms.MenuStrip menuStrip;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem nextDifferenceMenuItem;
private System.Windows.Forms.ToolStripMenuItem previousDifferenceMenuItem;
private System.Windows.Forms.ToolStripMenuItem firstDifferenceMenuItem;
private System.Windows.Forms.ToolStripMenuItem currentDifferenceMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastDifferenceMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator14;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newWorkspaceToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator16;
private System.Windows.Forms.ToolStripButton turboSortButton;
//private System.Windows.Forms.ToolStripButton autoHighlightButton;
private System.Windows.Forms.ToolStripMenuItem openQueryToolStripMenuItem;
private System.Windows.Forms.ToolStripButton tandemButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator18;
private System.Windows.Forms.ToolStripStatusLabel spacer2;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator25;
private System.Windows.Forms.ToolStrip reportToolStrip;
private System.Windows.Forms.ToolStripLabel toolStripLabel13;
private System.Windows.Forms.ToolStripLabel diffCountLabel;
private System.Windows.Forms.ToolStripLabel toolStripLabel17;
private System.Windows.Forms.ToolStripLabel currentDiffLabel;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator32;
private System.Windows.Forms.ToolStripLabel toolStripLabel19;
private System.Windows.Forms.ToolStripLabel matchPercentageLabel;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator33;
private System.Windows.Forms.ToolStripLabel addedLinesLabel;
private System.Windows.Forms.ToolStripLabel missingLinesLabel;
private System.Windows.Forms.ToolStripLabel changedLinesLabel;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator19;
private System.Windows.Forms.ToolStripMenuItem showLeftPaneMenuItem;
private System.Windows.Forms.ToolStripMenuItem showRightPaneMenuItem;
private System.Windows.Forms.ToolStripMenuItem showBothPanesMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
//private System.Windows.Forms.ToolStripButton autoExecuteButton;
private System.Windows.Forms.ToolStripMenuItem newQueryMenuItem;
private System.Windows.Forms.ToolStripStatusLabel memoryStatusLabel;
private System.Windows.Forms.ToolStripStatusLabel spacer3;
private System.Windows.Forms.ToolStripLabel toolStripLabel2;
private System.Windows.Forms.ToolStripTextBox filterValueTextBox;
private System.Windows.Forms.ToolStripLabel toolStripLabel7;
private System.Windows.Forms.ToolStripTextBox filterFieldTextBox;
private System.Windows.Forms.ToolStripStatusLabel LegendNonCurrentOmittedLabel;
private System.Windows.Forms.ToolStripMenuItem showProgressMenuItem;
private System.Windows.Forms.ToolStripButton autoDiffButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator34;
private System.Windows.Forms.ToolStripMenuItem restoreSettingsMenuItem;
private System.Windows.Forms.Timer memoryUsageTimer;
private System.Windows.Forms.ToolStripMenuItem saveLeftQueryMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveRightQueryMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem queryToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem executeQueryMenuItem;
private System.Windows.Forms.ToolStripMenuItem metaQueriesMenuItem;
private System.Windows.Forms.ToolStripMenuItem editConnectionsMenuItem;
private System.Windows.Forms.ToolStripButton setCurrentDiffButton;
private System.Windows.Forms.ToolStripMenuItem setCurrentDifferenceMenuItem;
private System.Windows.Forms.ToolStripButton showProgressButton;
private System.Windows.Forms.ToolStripMenuItem tabLeavesControlMenuItem;
private System.Windows.Forms.ToolStripMenuItem tabInsertsSpacesMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem showInputKeyReferenceMenuItem;
private System.Windows.Forms.ToolStripMenuItem showOutputKeyReferenceMenuItem;
private CleanCode.SqlEditorControls.SqlEditor leftSqlEditor;
private CleanCode.SqlEditorControls.SqlEditor rightSqlEditor;
private System.Windows.Forms.ToolStripMenuItem showGeneralKeyReferenceMenuItem;
private System.Windows.Forms.ToolStripMenuItem showMainKeyReferenceToolStripMenuItem;
private System.Windows.Forms.ToolStripSplitButton autoDiffSplitButton;
private System.Windows.Forms.ToolStripMenuItem taubererDiffMenuItem;
private System.Windows.Forms.ToolStripMenuItem hertelDiffMenuItem;
private System.Windows.Forms.ToolStripMenuItem potterDiffMenuItem;
private System.Windows.Forms.ToolStripMenuItem mirrorQueryMenuItem;
private System.Windows.Forms.ToolStripMenuItem findToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem replaceToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem executeBatchMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripButton addedLinesButton;
private System.Windows.Forms.ToolStripButton missingLinesButton;
private System.Windows.Forms.ToolStripButton changedLinesButton;
private System.Windows.Forms.ToolStripMenuItem userGuideMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator9;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
}
}
| |
// 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.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel
{
internal partial class CSharpCodeModelService
{
protected override AbstractNodeLocator CreateNodeLocator()
{
return new NodeLocator(this);
}
private class NodeLocator : AbstractNodeLocator
{
public NodeLocator(CSharpCodeModelService codeModelService)
: base(codeModelService)
{
}
protected override EnvDTE.vsCMPart DefaultPart
{
get { return EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; }
}
protected override VirtualTreePoint? GetStartPoint(SourceText text, SyntaxNode node, EnvDTE.vsCMPart part)
{
switch (node.Kind())
{
case SyntaxKind.Attribute:
return GetStartPoint(text, (AttributeSyntax)node, part);
case SyntaxKind.AttributeArgument:
return GetStartPoint(text, (AttributeArgumentSyntax)node, part);
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
return GetStartPoint(text, (BaseTypeDeclarationSyntax)node, part);
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
return GetStartPoint(text, (BaseMethodDeclarationSyntax)node, part);
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.EventDeclaration:
return GetStartPoint(text, (BasePropertyDeclarationSyntax)node, part);
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return GetStartPoint(text, (AccessorDeclarationSyntax)node, part);
case SyntaxKind.DelegateDeclaration:
return GetStartPoint(text, (DelegateDeclarationSyntax)node, part);
case SyntaxKind.NamespaceDeclaration:
return GetStartPoint(text, (NamespaceDeclarationSyntax)node, part);
case SyntaxKind.UsingDirective:
return GetStartPoint(text, (UsingDirectiveSyntax)node, part);
case SyntaxKind.EnumMemberDeclaration:
return GetStartPoint(text, (EnumMemberDeclarationSyntax)node, part);
case SyntaxKind.VariableDeclarator:
return GetStartPoint(text, (VariableDeclaratorSyntax)node, part);
case SyntaxKind.Parameter:
return GetStartPoint(text, (ParameterSyntax)node, part);
default:
Debug.Fail("Unsupported node kind: " + node.Kind());
throw new NotSupportedException();
}
}
protected override VirtualTreePoint? GetEndPoint(SourceText text, SyntaxNode node, EnvDTE.vsCMPart part)
{
switch (node.Kind())
{
case SyntaxKind.Attribute:
return GetEndPoint(text, (AttributeSyntax)node, part);
case SyntaxKind.AttributeArgument:
return GetEndPoint(text, (AttributeArgumentSyntax)node, part);
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
return GetEndPoint(text, (BaseTypeDeclarationSyntax)node, part);
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
return GetEndPoint(text, (BaseMethodDeclarationSyntax)node, part);
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.EventDeclaration:
return GetEndPoint(text, (BasePropertyDeclarationSyntax)node, part);
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return GetEndPoint(text, (AccessorDeclarationSyntax)node, part);
case SyntaxKind.DelegateDeclaration:
return GetEndPoint(text, (DelegateDeclarationSyntax)node, part);
case SyntaxKind.NamespaceDeclaration:
return GetEndPoint(text, (NamespaceDeclarationSyntax)node, part);
case SyntaxKind.UsingDirective:
return GetEndPoint(text, (UsingDirectiveSyntax)node, part);
case SyntaxKind.EnumMemberDeclaration:
return GetEndPoint(text, (EnumMemberDeclarationSyntax)node, part);
case SyntaxKind.VariableDeclarator:
return GetEndPoint(text, (VariableDeclaratorSyntax)node, part);
case SyntaxKind.Parameter:
return GetEndPoint(text, (ParameterSyntax)node, part);
default:
Debug.Fail("Unsupported node kind: " + node.Kind());
throw new NotSupportedException();
}
}
private SyntaxToken GetFirstTokenAfterAttributes(BaseTypeDeclarationSyntax node)
{
return node.AttributeLists.Count != 0
? node.AttributeLists.Last().GetLastToken().GetNextToken()
: node.GetFirstToken();
}
private SyntaxToken GetFirstTokenAfterAttributes(BaseMethodDeclarationSyntax node)
{
return node.AttributeLists.Count != 0
? node.AttributeLists.Last().GetLastToken().GetNextToken()
: node.GetFirstToken();
}
private VirtualTreePoint GetBodyStartPoint(SourceText text, SyntaxToken openBrace)
{
Debug.Assert(!openBrace.IsMissing);
var openBraceLine = text.Lines.GetLineFromPosition(openBrace.Span.End);
var textAfterBrace = text.ToString(TextSpan.FromBounds(openBrace.Span.End, openBraceLine.End));
return string.IsNullOrWhiteSpace(textAfterBrace)
? new VirtualTreePoint(openBrace.SyntaxTree, text, text.Lines[openBraceLine.LineNumber + 1].Start)
: new VirtualTreePoint(openBrace.SyntaxTree, text, openBrace.Span.End);
}
private VirtualTreePoint GetBodyStartPoint(SourceText text, SyntaxToken openBrace, SyntaxToken closeBrace, int memberStartColumn)
{
Debug.Assert(!openBrace.IsMissing);
Debug.Assert(!closeBrace.IsMissing);
Debug.Assert(memberStartColumn >= 0);
var openBraceLine = text.Lines.GetLineFromPosition(openBrace.SpanStart);
var closeBraceLine = text.Lines.GetLineFromPosition(closeBrace.SpanStart);
var tokenAfterOpenBrace = openBrace.GetNextToken();
var nextPosition = tokenAfterOpenBrace.SpanStart;
// We need to check if there is any significant trivia trailing this token or leading
// to the next token. This accounts for the fact that comments were included in the token
// stream in Dev10.
var significantTrivia = openBrace.GetAllTrailingTrivia()
.Where(t => !t.MatchesKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia))
.FirstOrDefault();
if (significantTrivia.Kind() != SyntaxKind.None)
{
nextPosition = significantTrivia.SpanStart;
}
// If the opening and closing curlies are at least two lines apart then place the cursor
// on the next line provided that there isn't any token on the line with the open curly.
if (openBraceLine.LineNumber + 1 < closeBraceLine.LineNumber &&
openBraceLine.LineNumber < text.Lines.IndexOf(tokenAfterOpenBrace.SpanStart))
{
var lineAfterOpenBrace = text.Lines[openBraceLine.LineNumber + 1];
var firstNonWhitespaceOffset = lineAfterOpenBrace.GetFirstNonWhitespaceOffset() ?? -1;
// If the line contains any text, we return the start of the first non-whitespace character.
if (firstNonWhitespaceOffset >= 0)
{
return new VirtualTreePoint(openBrace.SyntaxTree, text, lineAfterOpenBrace.Start + firstNonWhitespaceOffset);
}
// If the line is all whitespace then place the caret at the first indent after the start
// of the member.
var indentSize = GetTabSize(text);
var lineText = lineAfterOpenBrace.ToString();
var lineEndColumn = lineText.GetColumnFromLineOffset(lineText.Length, indentSize);
int indentColumn = memberStartColumn + indentSize;
var virtualSpaces = indentColumn - lineEndColumn;
return new VirtualTreePoint(openBrace.SyntaxTree, text, lineAfterOpenBrace.End, virtualSpaces);
}
else
{
// If the body is empty then place it after the open brace; otherwise, place
// at the start of the first token after the open curly.
if (closeBrace.SpanStart == nextPosition)
{
return new VirtualTreePoint(openBrace.SyntaxTree, text, openBrace.Span.End);
}
else
{
return new VirtualTreePoint(openBrace.SyntaxTree, text, nextPosition);
}
}
}
private VirtualTreePoint GetBodyEndPoint(SourceText text, SyntaxToken closeBrace)
{
var closeBraceLine = text.Lines.GetLineFromPosition(closeBrace.SpanStart);
var textBeforeBrace = text.ToString(TextSpan.FromBounds(closeBraceLine.Start, closeBrace.SpanStart));
return string.IsNullOrWhiteSpace(textBeforeBrace)
? new VirtualTreePoint(closeBrace.SyntaxTree, text, closeBraceLine.Start)
: new VirtualTreePoint(closeBrace.SyntaxTree, text, closeBrace.SpanStart);
}
private VirtualTreePoint GetStartPoint(SourceText text, AttributeSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.GetFirstToken().SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Name.SpanStart;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartBody:
case EnvDTE.vsCMPart.vsCMPartNavigate:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.SpanStart;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartHeader:
startPosition = GetFirstTokenAfterAttributes(node).SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.GetFirstToken().SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Identifier.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing)
{
throw Exceptions.ThrowEFail();
}
return GetBodyStartPoint(text, node.OpenBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, BaseMethodDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartHeader:
startPosition = GetFirstTokenAfterAttributes(node).SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.GetFirstToken().SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
if (node.Body != null && !node.Body.OpenBraceToken.IsMissing)
{
var line = text.Lines.GetLineFromPosition(node.SpanStart);
var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text));
return GetBodyStartPoint(text, node.Body.OpenBraceToken, node.Body.CloseBraceToken, indentation);
}
else
{
switch (node.Kind())
{
case SyntaxKind.MethodDeclaration:
startPosition = ((MethodDeclarationSyntax)node).Identifier.SpanStart;
break;
case SyntaxKind.ConstructorDeclaration:
startPosition = ((ConstructorDeclarationSyntax)node).Identifier.SpanStart;
break;
case SyntaxKind.DestructorDeclaration:
startPosition = ((DestructorDeclarationSyntax)node).Identifier.SpanStart;
break;
case SyntaxKind.ConversionOperatorDeclaration:
startPosition = ((ConversionOperatorDeclarationSyntax)node).ImplicitOrExplicitKeyword.SpanStart;
break;
case SyntaxKind.OperatorDeclaration:
startPosition = ((OperatorDeclarationSyntax)node).OperatorToken.SpanStart;
break;
default:
startPosition = GetFirstTokenAfterAttributes(node).SpanStart;
break;
}
}
break;
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing)
{
throw Exceptions.ThrowEFail();
}
return GetBodyStartPoint(text, node.Body.OpenBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private AccessorDeclarationSyntax FindFirstAccessorNode(BasePropertyDeclarationSyntax node)
{
if (node.AccessorList == null)
{
return null;
}
return node.AccessorList.Accessors.FirstOrDefault();
}
private VirtualTreePoint GetStartPoint(SourceText text, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
var firstAccessorNode = FindFirstAccessorNode(node);
if (firstAccessorNode != null)
{
var line = text.Lines.GetLineFromPosition(firstAccessorNode.SpanStart);
var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text));
if (firstAccessorNode.Body != null)
{
return GetBodyStartPoint(text, firstAccessorNode.Body.OpenBraceToken, firstAccessorNode.Body.CloseBraceToken, indentation);
}
else if (!firstAccessorNode.SemicolonToken.IsMissing)
{
// This is total weirdness from the old C# code model with auto props.
// If there isn't a body, the semi-colon is used
return GetBodyStartPoint(text, firstAccessorNode.SemicolonToken, firstAccessorNode.SemicolonToken, indentation);
}
}
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.AccessorList != null && !node.AccessorList.OpenBraceToken.IsMissing)
{
var line = text.Lines.GetLineFromPosition(node.SpanStart);
var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text));
return GetBodyStartPoint(text, node.AccessorList.OpenBraceToken, node.AccessorList.CloseBraceToken, indentation);
}
throw Exceptions.ThrowEFail();
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, AccessorDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
if (node.Body != null && !node.Body.OpenBraceToken.IsMissing)
{
var line = text.Lines.GetLineFromPosition(node.SpanStart);
var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text));
return GetBodyStartPoint(text, node.Body.OpenBraceToken, node.Body.CloseBraceToken, indentation);
}
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.Body == null ||
node.Body.OpenBraceToken.IsMissing ||
node.Body.CloseBraceToken.IsMissing)
{
throw Exceptions.ThrowEFail();
}
return GetBodyStartPoint(text, node.Body.OpenBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, NamespaceDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.GetFirstToken().SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Name.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing)
{
throw Exceptions.ThrowEFail();
}
return GetBodyStartPoint(text, node.OpenBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, DelegateDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.GetFirstToken().SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Identifier.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, UsingDirectiveSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Name.SpanStart;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, VariableDeclaratorSyntax node, EnvDTE.vsCMPart part)
{
var field = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>();
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (field.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = field.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Identifier.SpanStart;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, EnumMemberDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Identifier.SpanStart;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, ParameterSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Identifier.SpanStart;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, AttributeSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Name.Span.End;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartBody:
case EnvDTE.vsCMPart.vsCMPartNavigate:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
endPosition = node.AttributeLists.Last().GetLastToken().Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Identifier.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
return GetBodyEndPoint(text, node.CloseBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, BaseMethodDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
endPosition = node.AttributeLists.Last().GetLastToken().Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
if (node.Body != null && !node.Body.CloseBraceToken.IsMissing)
{
return GetBodyEndPoint(text, node.Body.CloseBraceToken);
}
else
{
switch (node.Kind())
{
case SyntaxKind.MethodDeclaration:
endPosition = ((MethodDeclarationSyntax)node).Identifier.Span.End;
break;
case SyntaxKind.ConstructorDeclaration:
endPosition = ((ConstructorDeclarationSyntax)node).Identifier.Span.End;
break;
case SyntaxKind.DestructorDeclaration:
endPosition = ((DestructorDeclarationSyntax)node).Identifier.Span.End;
break;
case SyntaxKind.ConversionOperatorDeclaration:
endPosition = ((ConversionOperatorDeclarationSyntax)node).ImplicitOrExplicitKeyword.Span.End;
break;
case SyntaxKind.OperatorDeclaration:
endPosition = ((OperatorDeclarationSyntax)node).OperatorToken.Span.End;
break;
default:
endPosition = GetFirstTokenAfterAttributes(node).Span.End;
break;
}
}
break;
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing)
{
throw Exceptions.ThrowEFail();
}
return GetBodyEndPoint(text, node.Body.CloseBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
endPosition = node.AttributeLists.Last().Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
var firstAccessorNode = FindFirstAccessorNode(node);
if (firstAccessorNode != null)
{
if (firstAccessorNode.Body != null)
{
return GetBodyEndPoint(text, firstAccessorNode.Body.CloseBraceToken);
}
else
{
// This is total weirdness from the old C# code model with auto props.
// If there isn't a body, the semi-colon is used
return GetBodyEndPoint(text, firstAccessorNode.SemicolonToken);
}
}
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.AccessorList != null && !node.AccessorList.CloseBraceToken.IsMissing)
{
return GetBodyEndPoint(text, node.AccessorList.CloseBraceToken);
}
throw Exceptions.ThrowEFail();
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, AccessorDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
case EnvDTE.vsCMPart.vsCMPartNavigate:
if (node.Body == null ||
node.Body.OpenBraceToken.IsMissing ||
node.Body.CloseBraceToken.IsMissing)
{
throw Exceptions.ThrowEFail();
}
return GetBodyEndPoint(text, node.Body.CloseBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, DelegateDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
endPosition = node.AttributeLists.Last().Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Identifier.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, NamespaceDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Name.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing)
{
throw Exceptions.ThrowEFail();
}
return GetBodyEndPoint(text, node.CloseBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, UsingDirectiveSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Name.Span.End;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, EnumMemberDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
endPosition = node.AttributeLists.Last().GetLastToken().Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Identifier.Span.End;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, VariableDeclaratorSyntax node, EnvDTE.vsCMPart part)
{
var field = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>();
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (field.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
endPosition = field.AttributeLists.Last().GetLastToken().Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = field.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Identifier.Span.End;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, ParameterSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
endPosition = node.AttributeLists.Last().GetLastToken().Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Identifier.Span.End;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Rest.Generator.NodeJS.Templates
{
#line 1 "MethodJsonPipelineTemplate.cshtml"
using System.Linq;
#line default
#line hidden
#line 2 "MethodJsonPipelineTemplate.cshtml"
using Microsoft.Rest.Generator.ClientModel
#line default
#line hidden
;
#line 3 "MethodJsonPipelineTemplate.cshtml"
using Microsoft.Rest.Generator.NodeJS
#line default
#line hidden
;
#line 4 "MethodJsonPipelineTemplate.cshtml"
using Microsoft.Rest.Generator.NodeJS.TemplateModels
#line default
#line hidden
;
using System.Threading.Tasks;
public class MethodJsonPipelineTemplate : Microsoft.Rest.Generator.Template<Microsoft.Rest.Generator.NodeJS.MethodTemplateModel>
{
#line hidden
public MethodJsonPipelineTemplate()
{
}
#pragma warning disable 1998
public override async Task ExecuteAsync()
{
WriteLiteral("// Send Request\r\nreturn client.pipeline(httpRequest, function (err, response, res" +
"ponseBody) {\r\n if (err) {\r\n return callback(err);\r\n }\r\n var statusCode = r" +
"esponse.statusCode;\r\n if (");
#line 12 "MethodJsonPipelineTemplate.cshtml"
Write(Model.FailureStatusCodePredicate);
#line default
#line hidden
WriteLiteral(@") {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = httpRequest;
error.response = response;
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
error.body = parsedErrorResponse;
");
#line 22 "MethodJsonPipelineTemplate.cshtml"
#line default
#line hidden
#line 22 "MethodJsonPipelineTemplate.cshtml"
if (Model.DefaultResponse != null)
{
var deserializeErrorBody = Model.GetDeserializationString(Model.DefaultResponse, "error.body");
if (!string.IsNullOrWhiteSpace(deserializeErrorBody))
{
#line default
#line hidden
WriteLiteral(" if (error.body !== null && error.body !== undefined) {\r\n ");
#line 28 "MethodJsonPipelineTemplate.cshtml"
Write(deserializeErrorBody);
#line default
#line hidden
WriteLiteral("\r\n }\r\n");
#line 30 "MethodJsonPipelineTemplate.cshtml"
}
}
#line default
#line hidden
WriteLiteral(@" } catch (defaultError) {
error.message = util.format('Error ""%s"" occurred in deserializing the responseBody - ""%s"" for the default response.', defaultError, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = new msRest.HttpOperationResponse();
result.request = httpRequest;
result.response = response;
if (responseBody === '') responseBody = null;
");
#line 44 "MethodJsonPipelineTemplate.cshtml"
Write(Model.InitializeResponseBody);
#line default
#line hidden
WriteLiteral("\r\n\r\n");
#line 46 "MethodJsonPipelineTemplate.cshtml"
#line default
#line hidden
#line 46 "MethodJsonPipelineTemplate.cshtml"
foreach (var responsePair in Model.Responses.Where(r => r.Value != null))
{
#line default
#line hidden
WriteLiteral(" \r\n // Deserialize Response\r\n if (statusCode === ");
#line 50 "MethodJsonPipelineTemplate.cshtml"
Write(MethodTemplateModel.GetStatusCodeReference(responsePair.Key));
#line default
#line hidden
WriteLiteral(") {\r\n var parsedResponse;\r\n try {\r\n parsedResponse = JSON.parse(respon" +
"seBody);\r\n result.body = parsedResponse;\r\n");
#line 55 "MethodJsonPipelineTemplate.cshtml"
#line default
#line hidden
#line 55 "MethodJsonPipelineTemplate.cshtml"
var deserializeBody = Model.GetDeserializationString(Model.ReturnType);
if (!string.IsNullOrWhiteSpace(deserializeBody))
{
#line default
#line hidden
WriteLiteral(" if (result.body !== null && result.body !== undefined) {\r\n ");
#line 60 "MethodJsonPipelineTemplate.cshtml"
Write(deserializeBody);
#line default
#line hidden
WriteLiteral("\r\n }\r\n");
#line 62 "MethodJsonPipelineTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral("\r\n } catch (error) {\r\n ");
#line 65 "MethodJsonPipelineTemplate.cshtml"
Write(Model.DeserializationError);
#line default
#line hidden
WriteLiteral("\r\n }\r\n }\r\n \r\n");
#line 69 "MethodJsonPipelineTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" ");
#line 70 "MethodJsonPipelineTemplate.cshtml"
if (Model.ReturnType != null && Model.DefaultResponse != null && !Model.Responses.Any())
{
#line default
#line hidden
WriteLiteral(" var parsedResponse;\r\n try {\r\n parsedResponse = JSON.parse(responseBody);\r\n " +
" result.body = parsedResponse;\r\n");
#line 76 "MethodJsonPipelineTemplate.cshtml"
var deserializeBody = Model.GetDeserializationString(Model.DefaultResponse);
if (!string.IsNullOrWhiteSpace(deserializeBody))
{
#line default
#line hidden
WriteLiteral(" if (result.body !== null && result.body !== undefined) {\r\n ");
#line 80 "MethodJsonPipelineTemplate.cshtml"
Write(deserializeBody);
#line default
#line hidden
WriteLiteral("\r\n }\r\n");
#line 82 "MethodJsonPipelineTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" } catch (error) {\r\n");
#line 84 "MethodJsonPipelineTemplate.cshtml"
Write(Model.DeserializationError);
#line default
#line hidden
WriteLiteral("\r\n}\r\n");
#line 86 "MethodJsonPipelineTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" ");
#line 87 "MethodJsonPipelineTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
WriteLiteral("\r\n\r\n return callback(null, result);\r\n});");
}
#pragma warning restore 1998
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Tests;
using Xunit;
namespace System.Tests
{
public static class TestExtensionMethod
{
public static DelegateTests.TestStruct TestFunc(this DelegateTests.TestClass testparam)
{
return testparam.structField;
}
public static void IncrementX(this DelegateTests.TestSerializableClass t)
{
t.x++;
}
}
public static unsafe class DelegateTests
{
public struct TestStruct
{
public object o1;
public object o2;
}
public class TestClass
{
public TestStruct structField;
}
[Serializable]
public class TestSerializableClass
{
public int x = 1;
}
private static void EmptyFunc() { }
public delegate TestStruct StructReturningDelegate();
[Fact]
public static void ClosedStaticDelegate()
{
TestClass foo = new TestClass();
foo.structField.o1 = new object();
foo.structField.o2 = new object();
StructReturningDelegate testDelegate = foo.TestFunc;
TestStruct returnedStruct = testDelegate();
Assert.Same(foo.structField.o1, returnedStruct.o1);
Assert.Same(foo.structField.o2, returnedStruct.o2);
}
public class A { }
public class B : A { }
public delegate A DynamicInvokeDelegate(A nonRefParam1, B nonRefParam2, ref A refParam, out B outParam);
public static A DynamicInvokeTestFunction(A nonRefParam1, B nonRefParam2, ref A refParam, out B outParam)
{
outParam = (B)refParam;
refParam = nonRefParam2;
return nonRefParam1;
}
[Fact]
public static void DynamicInvoke()
{
A a1 = new A();
A a2 = new A();
B b1 = new B();
B b2 = new B();
DynamicInvokeDelegate testDelegate = DynamicInvokeTestFunction;
// Check that the delegate behaves as expected
A refParam = b2;
B outParam = null;
A returnValue = testDelegate(a1, b1, ref refParam, out outParam);
Assert.Same(returnValue, a1);
Assert.Same(refParam, b1);
Assert.Same(outParam, b2);
// Check dynamic invoke behavior
object[] parameters = new object[] { a1, b1, b2, null };
object retVal = testDelegate.DynamicInvoke(parameters);
Assert.Same(retVal, a1);
Assert.Same(parameters[2], b1);
Assert.Same(parameters[3], b2);
// Check invoke on a delegate that takes no parameters.
Action emptyDelegate = EmptyFunc;
emptyDelegate.DynamicInvoke(new object[] { });
emptyDelegate.DynamicInvoke(null);
}
[Fact]
public static void DynamicInvoke_MissingTypeForDefaultParameter_Succeeds()
{
// Passing Type.Missing with default.
Delegate d = new IntIntDelegateWithDefault(IntIntMethod);
d.DynamicInvoke(7, Type.Missing);
}
[Fact]
public static void DynamicInvoke_MissingTypeForNonDefaultParameter_ThrowsArgumentException()
{
Delegate d = new IntIntDelegate(IntIntMethod);
AssertExtensions.Throws<ArgumentException>("parameters", () => d.DynamicInvoke(7, Type.Missing));
}
[Theory]
[InlineData(new object[] { 7 }, new object[] { 8 })]
[InlineData(new object[] { null }, new object[] { 1 })]
public static void DynamicInvoke_RefValueTypeParameter(object[] args, object[] expected)
{
Delegate d = new RefIntDelegate(RefIntMethod);
d.DynamicInvoke(args);
Assert.Equal(expected, args);
}
[Fact]
public static void DynamicInvoke_NullRefValueTypeParameter_ReturnsValueTypeDefault()
{
Delegate d = new RefValueTypeDelegate(RefValueTypeMethod);
object[] args = new object[] { null };
d.DynamicInvoke(args);
MyStruct s = (MyStruct)(args[0]);
Assert.Equal(7, s.X);
Assert.Equal(8, s.Y);
}
[Fact]
public static void DynamicInvoke_TypeDoesntExactlyMatchRefValueType_ThrowsArgumentException()
{
Delegate d = new RefIntDelegate(RefIntMethod);
AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke((uint)7));
AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke(IntEnum.One));
}
[Theory]
[InlineData(7, (short)7)] // uint -> int
[InlineData(7, IntEnum.Seven)] // Enum (int) -> int
[InlineData(7, ShortEnum.Seven)] // Enum (short) -> int
public static void DynamicInvoke_ValuePreservingPrimitiveWidening_Succeeds(object o1, object o2)
{
Delegate d = new IntIntDelegate(IntIntMethod);
d.DynamicInvoke(o1, o2);
}
[Theory]
[InlineData(IntEnum.Seven, 7)]
[InlineData(IntEnum.Seven, (short)7)]
public static void DynamicInvoke_ValuePreservingWideningToEnum_Succeeds(object o1, object o2)
{
Delegate d = new EnumEnumDelegate(EnumEnumMethod);
d.DynamicInvoke(o1, o2);
}
[Fact]
public static void DynamicInvoke_SizePreservingNonVauePreservingConversion_ThrowsArgumentException()
{
Delegate d = new IntIntDelegate(IntIntMethod);
AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke(7, (uint)7));
AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke(7, U4.Seven));
}
[Fact]
public static void DynamicInvoke_NullValueType_Succeeds()
{
Delegate d = new ValueTypeDelegate(ValueTypeMethod);
d.DynamicInvoke(new object[] { null });
}
[Fact]
public static void DynamicInvoke_ConvertMatchingTToNullable_Succeeds()
{
Delegate d = new NullableDelegate(NullableMethod);
d.DynamicInvoke(7);
}
[Fact]
public static void DynamicInvoke_ConvertNonMatchingTToNullable_ThrowsArgumentException()
{
Delegate d = new NullableDelegate(NullableMethod);
AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke((short)7));
AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke(IntEnum.Seven));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_AllPrimitiveParametersWithMissingValues()
{
object[] parameters = new object[13];
for (int i = 0; i < parameters.Length; i++) { parameters[i] = Type.Missing; }
Assert.Equal(
"True, test, c, 2, -1, -3, 4, -5, 6, -7, 8, 9.1, 11.12",
(string)(new AllPrimitivesWithDefaultValues(AllPrimitivesMethod)).DynamicInvoke(parameters));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_AllPrimitiveParametersWithAllExplicitValues()
{
Assert.Equal(
"False, value, d, 102, -101, -103, 104, -105, 106, -107, 108, 109.1, 111.12",
(string)(new AllPrimitivesWithDefaultValues(AllPrimitivesMethod)).DynamicInvoke(
new object[13]
{
false,
"value",
'd',
(byte)102,
(sbyte)-101,
(short)-103,
(ushort)104,
(int)-105,
(uint)106,
(long)-107,
(ulong)108,
(float)109.1,
(double)111.12
}
));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_AllPrimitiveParametersWithSomeExplicitValues()
{
Assert.Equal(
"False, test, d, 2, -101, -3, 104, -5, 106, -7, 108, 9.1, 111.12",
(string)(new AllPrimitivesWithDefaultValues(AllPrimitivesMethod)).DynamicInvoke(
new object[13]
{
false,
Type.Missing,
'd',
Type.Missing,
(sbyte)-101,
Type.Missing,
(ushort)104,
Type.Missing,
(uint)106,
Type.Missing,
(ulong)108,
Type.Missing,
(double)111.12
}
));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_StringParameterWithMissingValue()
{
Assert.Equal
("test",
(string)(new StringWithDefaultValue(StringMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_StringParameterWithExplicitValue()
{
Assert.Equal(
"value",
(string)(new StringWithDefaultValue(StringMethod)).DynamicInvoke(new object[] { "value" }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_ReferenceTypeParameterWithMissingValue()
{
Assert.Null((new ReferenceWithDefaultValue(ReferenceMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_ReferenceTypeParameterWithExplicitValue()
{
CustomReferenceType referenceInstance = new CustomReferenceType();
Assert.Same(
referenceInstance,
(new ReferenceWithDefaultValue(ReferenceMethod)).DynamicInvoke(new object[] { referenceInstance }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_ValueTypeParameterWithMissingValue()
{
Assert.Equal(
0,
((CustomValueType)(new ValueTypeWithDefaultValue(ValueTypeMethod)).DynamicInvoke(new object[] { Type.Missing })).Id);
}
[Fact]
public static void DynamicInvoke_DefaultParameter_ValueTypeParameterWithExplicitValue()
{
Assert.Equal(
1,
((CustomValueType)(new ValueTypeWithDefaultValue(ValueTypeMethod)).DynamicInvoke(new object[] { new CustomValueType { Id = 1 } })).Id);
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DateTimeParameterWithMissingValue()
{
Assert.Equal(
new DateTime(42),
(DateTime)(new DateTimeWithDefaultValueAttribute(DateTimeMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DateTimeParameterWithExplicitValue()
{
Assert.Equal(
new DateTime(43),
(DateTime)(new DateTimeWithDefaultValueAttribute(DateTimeMethod)).DynamicInvoke(new object[] { new DateTime(43) }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DecimalParameterWithAttributeAndMissingValue()
{
Assert.Equal(
new decimal(4, 3, 2, true, 1),
(decimal)(new DecimalWithDefaultValueAttribute(DecimalMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DecimalParameterWithAttributeAndExplicitValue()
{
Assert.Equal(
new decimal(12, 13, 14, true, 1),
(decimal)(new DecimalWithDefaultValueAttribute(DecimalMethod)).DynamicInvoke(new object[] { new decimal(12, 13, 14, true, 1) }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DecimalParameterWithMissingValue()
{
Assert.Equal(
3.14m,
(decimal)(new DecimalWithDefaultValue(DecimalMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DecimalParameterWithExplicitValue()
{
Assert.Equal(
103.14m,
(decimal)(new DecimalWithDefaultValue(DecimalMethod)).DynamicInvoke(new object[] { 103.14m }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_NullableIntWithMissingValue()
{
Assert.Null((int?)(new NullableIntWithDefaultValue(NullableIntMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_NullableIntWithExplicitValue()
{
Assert.Equal(
(int?)42,
(int?)(new NullableIntWithDefaultValue(NullableIntMethod)).DynamicInvoke(new object[] { (int?)42 }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_EnumParameterWithMissingValue()
{
Assert.Equal(
IntEnum.Seven,
(IntEnum)(new EnumWithDefaultValue(EnumMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_OptionalParameter_WithExplicitValue()
{
Assert.Equal(
"value",
(new OptionalObjectParameter(ObjectMethod)).DynamicInvoke(new object[] { "value" }));
}
[Fact]
public static void DynamicInvoke_OptionalParameter_WithMissingValue()
{
Assert.Equal(
Type.Missing,
(new OptionalObjectParameter(ObjectMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_OptionalParameterUnassingableFromMissing_WithMissingValue()
{
AssertExtensions.Throws<ArgumentException>(null, () => (new OptionalStringParameter(StringMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_ParameterSpecification_ArrayOfStrings()
{
Assert.Equal(
"value",
(new StringParameter(StringMethod)).DynamicInvoke(new string[] { "value" }));
}
[Fact]
public static void DynamicInvoke_ParameterSpecification_ArrayOfMissing()
{
Assert.Same(
Missing.Value,
(new OptionalObjectParameter(ObjectMethod)).DynamicInvoke(new Missing[] { Missing.Value }));
}
private static void IntIntMethod(int expected, int actual)
{
Assert.Equal(expected, actual);
}
private delegate void IntIntDelegate(int expected, int actual);
private delegate void IntIntDelegateWithDefault(int expected, int actual = 7);
private static void RefIntMethod(ref int i) => i++;
private delegate void RefIntDelegate(ref int i);
private struct MyStruct
{
public int X;
public int Y;
}
private static void RefValueTypeMethod(ref MyStruct s)
{
s.X += 7;
s.Y += 8;
}
private delegate void RefValueTypeDelegate(ref MyStruct s);
private static void EnumEnumMethod(IntEnum expected, IntEnum actual)
{
Assert.Equal(expected, actual);
}
private delegate void EnumEnumDelegate(IntEnum expected, IntEnum actual);
private static void ValueTypeMethod(MyStruct s)
{
Assert.Equal(0, s.X);
Assert.Equal(0, s.Y);
}
private delegate void ValueTypeDelegate(MyStruct s);
private static void NullableMethod(int? n)
{
Assert.True(n.HasValue);
Assert.Equal(7, n.Value);
}
private delegate void NullableDelegate(int? s);
public enum ShortEnum : short
{
One = 1,
Seven = 7,
}
public enum IntEnum : int
{
One = 1,
Seven = 7,
}
public enum U4 : uint
{
One = 1,
Seven = 7,
}
private delegate string AllPrimitivesWithDefaultValues(
bool boolean = true,
string str = "test",
char character = 'c',
byte unsignedbyte = 2,
sbyte signedbyte = -1,
short int16 = -3,
ushort uint16 = 4,
int int32 = -5,
uint uint32 = 6,
long int64 = -7,
ulong uint64 = 8,
float single = (float)9.1,
double dbl = 11.12);
private static string AllPrimitivesMethod(
bool boolean,
string str,
char character,
byte unsignedbyte,
sbyte signedbyte,
short int16,
ushort uint16,
int int32,
uint uint32,
long int64,
ulong uint64,
float single,
double dbl)
{
return FormattableString.Invariant($"{boolean}, {str}, {character}, {unsignedbyte}, {signedbyte}, {int16}, {uint16}, {int32}, {uint32}, {int64}, {uint64}, {single}, {dbl}");
}
private delegate string StringParameter(string parameter);
private delegate string StringWithDefaultValue(string parameter = "test");
private static string StringMethod(string parameter)
{
return parameter;
}
private class CustomReferenceType { };
private delegate CustomReferenceType ReferenceWithDefaultValue(CustomReferenceType parameter = null);
private static CustomReferenceType ReferenceMethod(CustomReferenceType parameter)
{
return parameter;
}
private struct CustomValueType { public int Id; };
private delegate CustomValueType ValueTypeWithDefaultValue(CustomValueType parameter = default(CustomValueType));
private static CustomValueType ValueTypeMethod(CustomValueType parameter)
{
return parameter;
}
private delegate DateTime DateTimeWithDefaultValueAttribute([DateTimeConstant(42)] DateTime parameter);
private static DateTime DateTimeMethod(DateTime parameter)
{
return parameter;
}
private delegate decimal DecimalWithDefaultValueAttribute([DecimalConstant(1, 1, 2, 3, 4)] decimal parameter);
private delegate decimal DecimalWithDefaultValue(decimal parameter = 3.14m);
private static decimal DecimalMethod(decimal parameter)
{
return parameter;
}
private delegate int? NullableIntWithDefaultValue(int? parameter = null);
private static int? NullableIntMethod(int? parameter)
{
return parameter;
}
private delegate IntEnum EnumWithDefaultValue(IntEnum parameter = IntEnum.Seven);
private static IntEnum EnumMethod(IntEnum parameter = IntEnum.Seven)
{
return parameter;
}
private delegate object OptionalObjectParameter([Optional] object parameter);
private static object ObjectMethod(object parameter)
{
return parameter;
}
private delegate string OptionalStringParameter([Optional] string parameter);
}
public static class CreateDelegateTests
{
#region Tests
[Fact]
public static void CreateDelegate1_Method_Static()
{
C c = new C();
MethodInfo mi = typeof(C).GetMethod("S");
Delegate dg = Delegate.CreateDelegate(typeof(D), mi);
Assert.Equal(mi, dg.Method);
Assert.Null(dg.Target);
D d = (D)dg;
d(c);
}
[Fact]
public static void CreateDelegate1_Method_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(D), (MethodInfo)null));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate1_Type_Null()
{
MethodInfo mi = typeof(C).GetMethod("S");
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, mi));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2()
{
E e;
e = (E)Delegate.CreateDelegate(typeof(E), new B(), "Execute");
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
e = (E)Delegate.CreateDelegate(typeof(E), new C(), "Execute");
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
e = (E)Delegate.CreateDelegate(typeof(E), new C(), "DoExecute");
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
}
[Fact]
public static void CreateDelegate2_Method_ArgumentsMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "StartExecute"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2_Method_CaseMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "ExecutE"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2_Method_DoesNotExist()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoesNotExist"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2_Method_Null()
{
C c = new C();
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(D), c, (string)null));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2_Method_ReturnTypeMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoExecute"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2_Method_Static()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "Run"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2_Target_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("target", () => Delegate.CreateDelegate(typeof(D), null, "N"));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2_Target_GenericTypeParameter()
{
Type theT = typeof(DummyGenericClassForDelegateTests<>).GetTypeInfo().GenericTypeParameters[0];
Type delegateType = typeof(Func<object, object, bool>);
AssertExtensions.Throws<ArgumentException>("target", () => Delegate.CreateDelegate(delegateType, theT, "ReferenceEquals"));
}
[Fact]
public static void CreateDelegate2_Type_Null()
{
C c = new C();
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, c, "N"));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3()
{
E e;
// matching static method
e = (E)Delegate.CreateDelegate(typeof(E), typeof(B), "Run");
Assert.NotNull(e);
Assert.Equal(5, e(new C()));
// matching static method
e = (E)Delegate.CreateDelegate(typeof(E), typeof(C), "Run");
Assert.NotNull(e);
Assert.Equal(5, e(new C()));
// matching static method
e = (E)Delegate.CreateDelegate(typeof(E), typeof(C), "DoRun");
Assert.NotNull(e);
Assert.Equal(107, e(new C()));
}
[Fact]
public static void CreateDelegate3_Method_ArgumentsMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "StartRun"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3_Method_CaseMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "RuN"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3_Method_DoesNotExist()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "DoesNotExist"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3_Method_Instance()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "Execute"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3_Method_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(D), typeof(C), (string)null));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3_Method_ReturnTypeMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "DoRun"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3_Target_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("target", () => Delegate.CreateDelegate(typeof(D), (Type)null, "S"));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3_Type_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, typeof(C), "S"));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4()
{
E e;
B b = new B();
// instance method, exact case, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), b, "Execute", true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// instance method, exact case, do not ignore case
e = (E)Delegate.CreateDelegate(typeof(E), b, "Execute", false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// instance method, case mismatch, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), b, "ExecutE", true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
C c = new C();
// instance method, exact case, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), c, "Execute", true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// instance method, exact case, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), c, "DoExecute", true);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
// instance method, exact case, do not ignore case
e = (E)Delegate.CreateDelegate(typeof(E), c, "Execute", false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// instance method, case mismatch, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), c, "ExecutE", true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
}
[Fact]
public static void CreateDelegate4_Method_ArgumentsMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "StartExecute", false));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4_Method_CaseMismatch()
{
// instance method, case mismatch, do not igore case
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "ExecutE", false));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4_Method_DoesNotExist()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoesNotExist", false));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4_Method_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(D), new C(), (string)null, true));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4_Method_ReturnTypeMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoExecute", false));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4_Method_Static()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "Run", true));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4_Target_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("target", () => Delegate.CreateDelegate(typeof(D), null, "N", true));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4_Type_Null()
{
C c = new C();
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, c, "N", true));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate9()
{
E e;
// do not ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Execute", false, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// do not ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Execute", false, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Execute", true, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Execute", true, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// do not ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"Execute", false, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// do not ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"Execute", false, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"Execute", true, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"Execute", true, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// do not ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"DoExecute", false, false);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
// do not ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"DoExecute", false, true);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
// ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"DoExecute", true, false);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
// ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"DoExecute", true, true);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
}
[Fact]
public static void CreateDelegate9_Method_ArgumentsMismatch()
{
// throw bind failure
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "StartExecute", false, true));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
// do not throw on bind failure
E e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"StartExecute", false, false);
Assert.Null(e);
}
[Fact]
public static void CreateDelegate9_Method_CaseMismatch()
{
E e;
// do not ignore case, throw bind failure
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "ExecutE", false, true));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
// do not ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"ExecutE", false, false);
Assert.Null(e);
// ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"ExecutE", true, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"ExecutE", true, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
}
[Fact]
public static void CreateDelegate9_Method_DoesNotExist()
{
// throw bind failure
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoesNotExist", false, true));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
// do not throw on bind failure
E e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"DoesNotExist", false, false);
Assert.Null(e);
}
[Fact]
public static void CreateDelegate9_Method_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(E), new B(), (string)null, false, false));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate9_Method_ReturnTypeMismatch()
{
// throw bind failure
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoExecute", false, true));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
// do not throw on bind failure
E e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"DoExecute", false, false);
Assert.Null(e);
}
[Fact]
public static void CreateDelegate9_Method_Static()
{
// throw bind failure
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "Run", true, true));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
// do not throw on bind failure
E e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Run", true, false);
Assert.Null(e);
}
[Fact]
public static void CreateDelegate9_Target_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("target", () => Delegate.CreateDelegate(typeof(E), (object)null, "Execute", true, false));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate9_Type_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, new B(), "Execute", true, false));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
#endregion Tests
#region Test Setup
public class B
{
public virtual string retarg3(string s)
{
return s;
}
static int Run(C x)
{
return 5;
}
public static void DoRun(C x)
{
}
public static int StartRun(C x, B b)
{
return 6;
}
int Execute(C c)
{
return 4;
}
public static void DoExecute(C c)
{
}
public int StartExecute(C c, B b)
{
return 3;
}
}
public class C : B, Iface
{
public string retarg(string s)
{
return s;
}
public string retarg2(Iface iface, string s)
{
return s + "2";
}
public override string retarg3(string s)
{
return s + "2";
}
static void Run(C x)
{
}
public static new int DoRun(C x)
{
return 107;
}
void Execute(C c)
{
}
public new int DoExecute(C c)
{
return 102;
}
public static void M()
{
}
public static void N(C c)
{
}
public static void S(C c)
{
}
private void PrivateInstance()
{
}
}
public interface Iface
{
string retarg(string s);
}
public delegate void D(C c);
public delegate int E(C c);
#endregion Test Setup
}
}
internal class DummyGenericClassForDelegateTests<T> { }
| |
//
// https://github.com/mythz/ServiceStack.Redis
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2010 Liquidbit Ltd.
//
// Licensed under the same terms of Redis and ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Linq;
using ServiceStack.Common.Utils;
using ServiceStack.DesignPatterns.Model;
using ServiceStack.Redis.Support;
using ServiceStack.Text;
using ServiceStack.Common.Extensions;
namespace ServiceStack.Redis.Generic
{
internal partial class RedisTypedClient<T>
{
public IHasNamed<IRedisSortedSet<T>> SortedSets { get; set; }
internal class RedisClientSortedSets
: IHasNamed<IRedisSortedSet<T>>
{
private readonly RedisTypedClient<T> client;
public RedisClientSortedSets(RedisTypedClient<T> client)
{
this.client = client;
}
public IRedisSortedSet<T> this[string setId]
{
get
{
return new RedisClientSortedSet<T>(client, setId);
}
set
{
var col = this[setId];
col.Clear();
col.CopyTo(value.ToArray(), 0);
}
}
}
public static T DeserializeFromString(string serializedObj)
{
return JsonSerializer.DeserializeFromString<T>(serializedObj);
}
private static IDictionary<T, double> CreateGenericMap(IDictionary<string, double> map)
{
var genericMap = new OrderedDictionary<T, double>();
foreach (var entry in map)
{
genericMap[DeserializeFromString(entry.Key)] = entry.Value;
}
return genericMap;
}
public void AddItemToSortedSet(IRedisSortedSet<T> toSet, T value)
{
client.AddItemToSortedSet(toSet.Id, value.SerializeToString());
}
public void AddItemToSortedSet(IRedisSortedSet<T> toSet, T value, double score)
{
client.AddItemToSortedSet(toSet.Id, value.SerializeToString(), score);
}
public bool RemoveItemFromSortedSet(IRedisSortedSet<T> fromSet, T value)
{
return client.RemoveItemFromSortedSet(fromSet.Id, value.SerializeToString());
}
public T PopItemWithLowestScoreFromSortedSet(IRedisSortedSet<T> fromSet)
{
return DeserializeFromString(
client.PopItemWithLowestScoreFromSortedSet(fromSet.Id));
}
public T PopItemWithHighestScoreFromSortedSet(IRedisSortedSet<T> fromSet)
{
return DeserializeFromString(
client.PopItemWithHighestScoreFromSortedSet(fromSet.Id));
}
public bool SortedSetContainsItem(IRedisSortedSet<T> set, T value)
{
return client.SortedSetContainsItem(set.Id, value.SerializeToString());
}
public double IncrementItemInSortedSet(IRedisSortedSet<T> set, T value, double incrementBy)
{
return client.IncrementItemInSortedSet(set.Id, value.SerializeToString(), incrementBy);
}
public int GetItemIndexInSortedSet(IRedisSortedSet<T> set, T value)
{
return client.GetItemIndexInSortedSet(set.Id, value.SerializeToString());
}
public int GetItemIndexInSortedSetDesc(IRedisSortedSet<T> set, T value)
{
return client.GetItemIndexInSortedSetDesc(set.Id, value.SerializeToString());
}
public List<T> GetAllItemsFromSortedSet(IRedisSortedSet<T> set)
{
var list = client.GetAllItemsFromSortedSet(set.Id);
return list.ConvertEachTo<T>();
}
public List<T> GetAllItemsFromSortedSetDesc(IRedisSortedSet<T> set)
{
var list = client.GetAllItemsFromSortedSetDesc(set.Id);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSet(IRedisSortedSet<T> set, int fromRank, int toRank)
{
var list = client.GetRangeFromSortedSet(set.Id, fromRank, toRank);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSetDesc(IRedisSortedSet<T> set, int fromRank, int toRank)
{
var list = client.GetRangeFromSortedSetDesc(set.Id, fromRank, toRank);
return list.ConvertEachTo<T>();
}
public IDictionary<T, double> GetAllWithScoresFromSortedSet(IRedisSortedSet<T> set)
{
var map = client.GetRangeWithScoresFromSortedSet(set.Id, FirstElement, LastElement);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSet(IRedisSortedSet<T> set, int fromRank, int toRank)
{
var map = client.GetRangeWithScoresFromSortedSet(set.Id, fromRank, toRank);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetDesc(IRedisSortedSet<T> set, int fromRank, int toRank)
{
var map = client.GetRangeWithScoresFromSortedSetDesc(set.Id, fromRank, toRank);
return CreateGenericMap(map);
}
public List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore)
{
var list = client.GetRangeFromSortedSetByLowestScore(set.Id, fromStringScore, toStringScore);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take)
{
var list = client.GetRangeFromSortedSetByLowestScore(set.Id, fromStringScore, toStringScore, skip, take);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore)
{
var list = client.GetRangeFromSortedSetByLowestScore(set.Id, fromScore, toScore);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take)
{
var list = client.GetRangeFromSortedSetByLowestScore(set.Id, fromScore, toScore, skip, take);
return list.ConvertEachTo<T>();
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore)
{
var map = client.GetRangeWithScoresFromSortedSetByLowestScore(set.Id, fromStringScore, toStringScore);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take)
{
var map = client.GetRangeWithScoresFromSortedSetByLowestScore(set.Id, fromStringScore, toStringScore, skip, take);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore)
{
var map = client.GetRangeWithScoresFromSortedSetByLowestScore(set.Id, fromScore, toScore);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take)
{
var map = client.GetRangeWithScoresFromSortedSetByLowestScore(set.Id, fromScore, toScore, skip, take);
return CreateGenericMap(map);
}
public List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore)
{
var list = client.GetRangeFromSortedSetByHighestScore(set.Id, fromStringScore, toStringScore);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take)
{
var list = client.GetRangeFromSortedSetByHighestScore(set.Id, fromStringScore, toStringScore, skip, take);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore)
{
var list = client.GetRangeFromSortedSetByHighestScore(set.Id, fromScore, toScore);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take)
{
var list = client.GetRangeFromSortedSetByHighestScore(set.Id, fromScore, toScore, take, skip);
return list.ConvertEachTo<T>();
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore)
{
var map = client.GetRangeWithScoresFromSortedSetByHighestScore(set.Id, fromStringScore, toStringScore);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take)
{
var map = client.GetRangeWithScoresFromSortedSetByHighestScore(set.Id, fromStringScore, toStringScore, skip, take);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore)
{
var map = client.GetRangeWithScoresFromSortedSetByHighestScore(set.Id, fromScore, toScore);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take)
{
var map = client.GetRangeWithScoresFromSortedSetByHighestScore(set.Id, fromScore, toScore, skip, take);
return CreateGenericMap(map);
}
public int RemoveRangeFromSortedSet(IRedisSortedSet<T> set, int minRank, int maxRank)
{
return client.RemoveRangeFromSortedSet(set.Id, maxRank, maxRank);
}
public int RemoveRangeFromSortedSetByScore(IRedisSortedSet<T> set, double fromScore, double toScore)
{
return client.RemoveRangeFromSortedSetByScore(set.Id, fromScore, toScore);
}
public int GetSortedSetCount(IRedisSortedSet<T> set)
{
return client.GetSortedSetCount(set.Id);
}
public double GetItemScoreInSortedSet(IRedisSortedSet<T> set, T value)
{
return client.GetItemScoreInSortedSet(set.Id, value.SerializeToString());
}
public int StoreIntersectFromSortedSets(IRedisSortedSet<T> intoSetId, params IRedisSortedSet<T>[] setIds)
{
return client.StoreIntersectFromSortedSets(intoSetId.Id, setIds.ConvertAll(x => x.Id).ToArray());
}
public int StoreUnionFromSortedSets(IRedisSortedSet<T> intoSetId, params IRedisSortedSet<T>[] setIds)
{
return client.StoreUnionFromSortedSets(intoSetId.Id, setIds.ConvertAll(x => x.Id).ToArray());
}
}
}
| |
// Generated by ProtoGen, Version=2.3.0.277, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT!
using scg = global::System.Collections.Generic;
namespace PhoneNumbers {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public static partial class Phonenumber {
#region Static variables
#endregion
#region Extensions
internal static readonly object Descriptor;
static Phonenumber() {
Descriptor = null;
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public partial class PhoneNumber {
private static readonly PhoneNumber defaultInstance = new Builder().BuildPartial();
public static PhoneNumber DefaultInstance {
get { return defaultInstance; }
}
public PhoneNumber DefaultInstanceForType {
get { return defaultInstance; }
}
protected PhoneNumber ThisMessage {
get { return this; }
}
#region Nested types
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public static class Types {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public enum CountryCodeSource {
FROM_NUMBER_WITH_PLUS_SIGN = 1,
FROM_NUMBER_WITH_IDD = 5,
FROM_NUMBER_WITHOUT_PLUS_SIGN = 10,
FROM_DEFAULT_COUNTRY = 20,
}
}
#endregion
public const int CountryCodeFieldNumber = 1;
private bool hasCountryCode;
private int countryCode_ = 0;
public bool HasCountryCode {
get { return hasCountryCode; }
}
public int CountryCode {
get { return countryCode_; }
}
public const int NationalNumberFieldNumber = 2;
private bool hasNationalNumber;
private ulong nationalNumber_ = 0UL;
public bool HasNationalNumber {
get { return hasNationalNumber; }
}
public ulong NationalNumber {
get { return nationalNumber_; }
}
public const int ExtensionFieldNumber = 3;
private bool hasExtension;
private string extension_ = "";
public bool HasExtension {
get { return hasExtension; }
}
public string Extension {
get { return extension_; }
}
public const int ItalianLeadingZeroFieldNumber = 4;
private bool hasItalianLeadingZero;
private bool italianLeadingZero_ = false;
public bool HasItalianLeadingZero {
get { return hasItalianLeadingZero; }
}
public bool ItalianLeadingZero {
get { return italianLeadingZero_; }
}
public const int RawInputFieldNumber = 5;
private bool hasRawInput;
private string rawInput_ = "";
public bool HasRawInput {
get { return hasRawInput; }
}
public string RawInput {
get { return rawInput_; }
}
public const int CountryCodeSourceFieldNumber = 6;
private bool hasCountryCodeSource;
private global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource countryCodeSource_ = global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN;
public bool HasCountryCodeSource {
get { return hasCountryCodeSource; }
}
public global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource CountryCodeSource {
get { return countryCodeSource_; }
}
public const int PreferredDomesticCarrierCodeFieldNumber = 7;
private bool hasPreferredDomesticCarrierCode;
private string preferredDomesticCarrierCode_ = "";
public bool HasPreferredDomesticCarrierCode {
get { return hasPreferredDomesticCarrierCode; }
}
public string PreferredDomesticCarrierCode {
get { return preferredDomesticCarrierCode_; }
}
public bool IsInitialized {
get {
if (!hasCountryCode) return false;
if (!hasNationalNumber) return false;
return true;
}
}
#region Lite runtime methods
public override int GetHashCode() {
int hash = GetType().GetHashCode();
if (hasCountryCode) hash ^= countryCode_.GetHashCode();
if (hasNationalNumber) hash ^= nationalNumber_.GetHashCode();
if (hasExtension) hash ^= extension_.GetHashCode();
// Manual fix to behave like the Java version which ignores the hasItalianLeadingZero fields
hash ^= italianLeadingZero_.GetHashCode();
if (hasRawInput) hash ^= rawInput_.GetHashCode();
if (hasCountryCodeSource) hash ^= countryCodeSource_.GetHashCode();
if (hasPreferredDomesticCarrierCode) hash ^= preferredDomesticCarrierCode_.GetHashCode();
return hash;
}
public override bool Equals(object obj) {
PhoneNumber other = obj as PhoneNumber;
if (other == null) return false;
if (hasCountryCode != other.hasCountryCode || (hasCountryCode && !countryCode_.Equals(other.countryCode_))) return false;
if (hasNationalNumber != other.hasNationalNumber || (hasNationalNumber && !nationalNumber_.Equals(other.nationalNumber_))) return false;
if (hasExtension != other.hasExtension || (hasExtension && !extension_.Equals(other.extension_))) return false;
// Manual fix to behave like the Java version which ignores the hasItalianLeadingZero fields
if (!italianLeadingZero_.Equals(other.italianLeadingZero_)) return false;
if (hasRawInput != other.hasRawInput || (hasRawInput && !rawInput_.Equals(other.rawInput_))) return false;
if (hasCountryCodeSource != other.hasCountryCodeSource || (hasCountryCodeSource && !countryCodeSource_.Equals(other.countryCodeSource_))) return false;
if (hasPreferredDomesticCarrierCode != other.hasPreferredDomesticCarrierCode || (hasPreferredDomesticCarrierCode && !preferredDomesticCarrierCode_.Equals(other.preferredDomesticCarrierCode_))) return false;
return true;
}
#endregion
public static Builder CreateBuilder() { return new Builder(); }
public Builder ToBuilder() { return CreateBuilder(this); }
public Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(PhoneNumber prototype) {
return (Builder) new Builder().MergeFrom(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public partial class Builder {
protected Builder ThisBuilder {
get { return this; }
}
public Builder() {}
PhoneNumber result = new PhoneNumber();
protected PhoneNumber MessageBeingBuilt {
get { return result; }
}
public Builder Clear() {
result = new PhoneNumber();
return this;
}
public Builder Clone() {
return new Builder().MergeFrom(result);
}
public PhoneNumber DefaultInstanceForType {
get { return global::PhoneNumbers.PhoneNumber.DefaultInstance; }
}
public PhoneNumber Build() { return BuildPartial(); }
public PhoneNumber BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
}
PhoneNumber returnMe = result;
result = null;
return returnMe;
}
public Builder MergeFrom(PhoneNumber other) {
if (other == global::PhoneNumbers.PhoneNumber.DefaultInstance) return this;
if (other.HasCountryCode) {
CountryCode = other.CountryCode;
}
if (other.HasNationalNumber) {
NationalNumber = other.NationalNumber;
}
if (other.HasExtension) {
Extension = other.Extension;
}
if (other.HasItalianLeadingZero) {
ItalianLeadingZero = other.ItalianLeadingZero;
}
if (other.HasRawInput) {
RawInput = other.RawInput;
}
if (other.HasCountryCodeSource) {
CountryCodeSource = other.CountryCodeSource;
}
if (other.HasPreferredDomesticCarrierCode) {
PreferredDomesticCarrierCode = other.PreferredDomesticCarrierCode;
}
return this;
}
public bool HasCountryCode {
get { return result.HasCountryCode; }
}
public int CountryCode {
get { return result.CountryCode; }
set { SetCountryCode(value); }
}
public Builder SetCountryCode(int value) {
result.hasCountryCode = true;
result.countryCode_ = value;
return this;
}
public Builder ClearCountryCode() {
result.hasCountryCode = false;
result.countryCode_ = 0;
return this;
}
public bool HasNationalNumber {
get { return result.HasNationalNumber; }
}
public ulong NationalNumber {
get { return result.NationalNumber; }
set { SetNationalNumber(value); }
}
public Builder SetNationalNumber(ulong value) {
result.hasNationalNumber = true;
result.nationalNumber_ = value;
return this;
}
public Builder ClearNationalNumber() {
result.hasNationalNumber = false;
result.nationalNumber_ = 0UL;
return this;
}
public bool HasExtension {
get { return result.HasExtension; }
}
public string Extension {
get { return result.Extension; }
set { SetExtension(value); }
}
public Builder SetExtension(string value) {
if(value == null) throw new global::System.ArgumentNullException("value");
result.hasExtension = true;
result.extension_ = value;
return this;
}
public Builder ClearExtension() {
result.hasExtension = false;
result.extension_ = "";
return this;
}
public bool HasItalianLeadingZero {
get { return result.HasItalianLeadingZero; }
}
public bool ItalianLeadingZero {
get { return result.ItalianLeadingZero; }
set { SetItalianLeadingZero(value); }
}
public Builder SetItalianLeadingZero(bool value) {
result.hasItalianLeadingZero = true;
result.italianLeadingZero_ = value;
return this;
}
public Builder ClearItalianLeadingZero() {
result.hasItalianLeadingZero = false;
result.italianLeadingZero_ = false;
return this;
}
public bool HasRawInput {
get { return result.HasRawInput; }
}
public string RawInput {
get { return result.RawInput; }
set { SetRawInput(value); }
}
public Builder SetRawInput(string value) {
if(value == null) throw new global::System.ArgumentNullException("value");
result.hasRawInput = true;
result.rawInput_ = value;
return this;
}
public Builder ClearRawInput() {
result.hasRawInput = false;
result.rawInput_ = "";
return this;
}
public bool HasCountryCodeSource {
get { return result.HasCountryCodeSource; }
}
public global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource CountryCodeSource {
get { return result.CountryCodeSource; }
set { SetCountryCodeSource(value); }
}
public Builder SetCountryCodeSource(global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource value) {
result.hasCountryCodeSource = true;
result.countryCodeSource_ = value;
return this;
}
public Builder ClearCountryCodeSource() {
result.hasCountryCodeSource = false;
result.countryCodeSource_ = global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN;
return this;
}
public bool HasPreferredDomesticCarrierCode {
get { return result.HasPreferredDomesticCarrierCode; }
}
public string PreferredDomesticCarrierCode {
get { return result.PreferredDomesticCarrierCode; }
set { SetPreferredDomesticCarrierCode(value); }
}
public Builder SetPreferredDomesticCarrierCode(string value) {
if(value == null) throw new global::System.ArgumentNullException("value");
result.hasPreferredDomesticCarrierCode = true;
result.preferredDomesticCarrierCode_ = value;
return this;
}
public Builder ClearPreferredDomesticCarrierCode() {
result.hasPreferredDomesticCarrierCode = false;
result.preferredDomesticCarrierCode_ = "";
return this;
}
}
static PhoneNumber() {
object.ReferenceEquals(global::PhoneNumbers.Phonenumber.Descriptor, null);
}
}
#endregion
}
| |
namespace Azure.IoT.DeviceUpdate
{
public partial class DeploymentsClient
{
protected DeploymentsClient() { }
public DeploymentsClient(string accountEndpoint, string instanceId, Azure.Core.TokenCredential credential) { }
public DeploymentsClient(string accountEndpoint, string instanceId, Azure.Core.TokenCredential credential, Azure.IoT.DeviceUpdate.DeviceUpdateClientOptions options) { }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment> CancelDeployment(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment>> CancelDeploymentAsync(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment> CreateOrUpdateDeployment(string deploymentId, Azure.IoT.DeviceUpdate.Models.Deployment deployment, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment>> CreateOrUpdateDeploymentAsync(string deploymentId, Azure.IoT.DeviceUpdate.Models.Deployment deployment, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response DeleteDeployment(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteDeploymentAsync(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.Deployment> GetAllDeployments(string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.Deployment> GetAllDeploymentsAsync(string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment> GetDeployment(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment>> GetDeploymentAsync(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.DeploymentDeviceState> GetDeploymentDevices(string deploymentId, string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.DeploymentDeviceState> GetDeploymentDevicesAsync(string deploymentId, string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.DeploymentStatus> GetDeploymentStatus(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.DeploymentStatus>> GetDeploymentStatusAsync(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment> RetryDeployment(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment>> RetryDeploymentAsync(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class DevicesClient
{
protected DevicesClient() { }
public DevicesClient(string accountEndpoint, string instanceId, Azure.Core.TokenCredential credential) { }
public DevicesClient(string accountEndpoint, string instanceId, Azure.Core.TokenCredential credential, Azure.IoT.DeviceUpdate.DeviceUpdateClientOptions options) { }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Group> CreateOrUpdateGroup(string groupId, Azure.IoT.DeviceUpdate.Models.Group group, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Group>> CreateOrUpdateGroupAsync(string groupId, Azure.IoT.DeviceUpdate.Models.Group group, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response DeleteGroup(string groupId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteGroupAsync(string groupId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.DeviceClass> GetAllDeviceClasses(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.DeviceClass> GetAllDeviceClassesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.Device> GetAllDevices(string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.Device> GetAllDevicesAsync(string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.DeviceTag> GetAllDeviceTags(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.DeviceTag> GetAllDeviceTagsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.Group> GetAllGroups(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.Group> GetAllGroupsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Device> GetDevice(string deviceId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Device>> GetDeviceAsync(string deviceId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.DeviceClass> GetDeviceClass(string deviceClassId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.DeviceClass>> GetDeviceClassAsync(string deviceClassId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<string> GetDeviceClassDeviceIds(string deviceClassId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<string> GetDeviceClassDeviceIdsAsync(string deviceClassId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.UpdateId> GetDeviceClassInstallableUpdates(string deviceClassId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.UpdateId> GetDeviceClassInstallableUpdatesAsync(string deviceClassId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.DeviceTag> GetDeviceTag(string tagName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.DeviceTag>> GetDeviceTagAsync(string tagName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Group> GetGroup(string groupId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Group>> GetGroupAsync(string groupId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.UpdatableDevices> GetGroupBestUpdates(string groupId, string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.UpdatableDevices> GetGroupBestUpdatesAsync(string groupId, string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.UpdateCompliance> GetGroupUpdateCompliance(string groupId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.UpdateCompliance>> GetGroupUpdateComplianceAsync(string groupId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.UpdateCompliance> GetUpdateCompliance(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.UpdateCompliance>> GetUpdateComplianceAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class DeviceUpdateClientOptions : Azure.Core.ClientOptions
{
public DeviceUpdateClientOptions(Azure.IoT.DeviceUpdate.DeviceUpdateClientOptions.ServiceVersion version = Azure.IoT.DeviceUpdate.DeviceUpdateClientOptions.ServiceVersion.V2020_09_01) { }
public enum ServiceVersion
{
V2020_09_01 = 1,
}
}
public partial class UpdatesClient
{
protected UpdatesClient() { }
public UpdatesClient(string accountEndpoint, string instanceId, Azure.Core.TokenCredential credential) { }
public UpdatesClient(string accountEndpoint, string instanceId, Azure.Core.TokenCredential credential, Azure.IoT.DeviceUpdate.DeviceUpdateClientOptions options) { }
public virtual Azure.Response<string> DeleteUpdate(string provider, string name, string version, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<string>> DeleteUpdateAsync(string provider, string name, string version, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.File> GetFile(string provider, string name, string version, string fileId, Azure.IoT.DeviceUpdate.Models.AccessCondition accessCondition = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.File>> GetFileAsync(string provider, string name, string version, string fileId, Azure.IoT.DeviceUpdate.Models.AccessCondition accessCondition = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<string> GetFiles(string provider, string name, string version, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<string> GetFilesAsync(string provider, string name, string version, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<string> GetNames(string provider, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<string> GetNamesAsync(string provider, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Operation> GetOperation(string operationId, Azure.IoT.DeviceUpdate.Models.AccessCondition accessCondition = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Operation>> GetOperationAsync(string operationId, Azure.IoT.DeviceUpdate.Models.AccessCondition accessCondition = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.Operation> GetOperations(string filter = null, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.Operation> GetOperationsAsync(string filter = null, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<string> GetProviders(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<string> GetProvidersAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Update> GetUpdate(string provider, string name, string version, Azure.IoT.DeviceUpdate.Models.AccessCondition accessCondition = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Update>> GetUpdateAsync(string provider, string name, string version, Azure.IoT.DeviceUpdate.Models.AccessCondition accessCondition = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<string> GetVersions(string provider, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<string> GetVersionsAsync(string provider, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<string> ImportUpdate(Azure.IoT.DeviceUpdate.Models.ImportUpdateInput updateToImport, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<string>> ImportUpdateAsync(Azure.IoT.DeviceUpdate.Models.ImportUpdateInput updateToImport, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
}
namespace Azure.IoT.DeviceUpdate.Models
{
public partial class AccessCondition
{
public AccessCondition() { }
public string IfNoneMatch { get { throw null; } set { } }
}
public partial class Compatibility
{
internal Compatibility() { }
public string DeviceManufacturer { get { throw null; } }
public string DeviceModel { get { throw null; } }
}
public partial class Deployment
{
public Deployment(string deploymentId, Azure.IoT.DeviceUpdate.Models.DeploymentType deploymentType, System.DateTimeOffset startDateTime, Azure.IoT.DeviceUpdate.Models.DeviceGroupType deviceGroupType, System.Collections.Generic.IEnumerable<string> deviceGroupDefinition, Azure.IoT.DeviceUpdate.Models.UpdateId updateId) { }
public string DeploymentId { get { throw null; } set { } }
public Azure.IoT.DeviceUpdate.Models.DeploymentType DeploymentType { get { throw null; } set { } }
public string DeviceClassId { get { throw null; } set { } }
public System.Collections.Generic.IList<string> DeviceGroupDefinition { get { throw null; } }
public Azure.IoT.DeviceUpdate.Models.DeviceGroupType DeviceGroupType { get { throw null; } set { } }
public bool? IsCanceled { get { throw null; } set { } }
public bool? IsCompleted { get { throw null; } set { } }
public bool? IsRetried { get { throw null; } set { } }
public System.DateTimeOffset StartDateTime { get { throw null; } set { } }
public Azure.IoT.DeviceUpdate.Models.UpdateId UpdateId { get { throw null; } set { } }
}
public partial class DeploymentDeviceState
{
internal DeploymentDeviceState() { }
public string DeviceId { get { throw null; } }
public Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState DeviceState { get { throw null; } }
public bool MovedOnToNewDeployment { get { throw null; } }
public int RetryCount { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct DeploymentState : System.IEquatable<Azure.IoT.DeviceUpdate.Models.DeploymentState>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public DeploymentState(string value) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.DeploymentState Active { get { throw null; } }
public static Azure.IoT.DeviceUpdate.Models.DeploymentState Canceled { get { throw null; } }
public static Azure.IoT.DeviceUpdate.Models.DeploymentState Superseded { get { throw null; } }
public bool Equals(Azure.IoT.DeviceUpdate.Models.DeploymentState other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.IoT.DeviceUpdate.Models.DeploymentState left, Azure.IoT.DeviceUpdate.Models.DeploymentState right) { throw null; }
public static implicit operator Azure.IoT.DeviceUpdate.Models.DeploymentState (string value) { throw null; }
public static bool operator !=(Azure.IoT.DeviceUpdate.Models.DeploymentState left, Azure.IoT.DeviceUpdate.Models.DeploymentState right) { throw null; }
public override string ToString() { throw null; }
}
public partial class DeploymentStatus
{
internal DeploymentStatus() { }
public Azure.IoT.DeviceUpdate.Models.DeploymentState DeploymentState { get { throw null; } }
public int? DevicesCanceledCount { get { throw null; } }
public int? DevicesCompletedFailedCount { get { throw null; } }
public int? DevicesCompletedSucceededCount { get { throw null; } }
public int? DevicesIncompatibleCount { get { throw null; } }
public int? DevicesInProgressCount { get { throw null; } }
public int? TotalDevices { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct DeploymentType : System.IEquatable<Azure.IoT.DeviceUpdate.Models.DeploymentType>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public DeploymentType(string value) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.DeploymentType Complete { get { throw null; } }
public static Azure.IoT.DeviceUpdate.Models.DeploymentType Download { get { throw null; } }
public static Azure.IoT.DeviceUpdate.Models.DeploymentType Install { get { throw null; } }
public bool Equals(Azure.IoT.DeviceUpdate.Models.DeploymentType other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.IoT.DeviceUpdate.Models.DeploymentType left, Azure.IoT.DeviceUpdate.Models.DeploymentType right) { throw null; }
public static implicit operator Azure.IoT.DeviceUpdate.Models.DeploymentType (string value) { throw null; }
public static bool operator !=(Azure.IoT.DeviceUpdate.Models.DeploymentType left, Azure.IoT.DeviceUpdate.Models.DeploymentType right) { throw null; }
public override string ToString() { throw null; }
}
public partial class Device
{
internal Device() { }
public Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState? DeploymentStatus { get { throw null; } }
public string DeviceClassId { get { throw null; } }
public string DeviceId { get { throw null; } }
public string GroupId { get { throw null; } }
public Azure.IoT.DeviceUpdate.Models.UpdateId InstalledUpdateId { get { throw null; } }
public Azure.IoT.DeviceUpdate.Models.UpdateId LastAttemptedUpdateId { get { throw null; } }
public string LastDeploymentId { get { throw null; } }
public string Manufacturer { get { throw null; } }
public string Model { get { throw null; } }
public bool OnLatestUpdate { get { throw null; } }
}
public partial class DeviceClass
{
internal DeviceClass() { }
public Azure.IoT.DeviceUpdate.Models.UpdateId BestCompatibleUpdateId { get { throw null; } }
public string DeviceClassId { get { throw null; } }
public string Manufacturer { get { throw null; } }
public string Model { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct DeviceDeploymentState : System.IEquatable<Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public DeviceDeploymentState(string value) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState Canceled { get { throw null; } }
public static Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState Failed { get { throw null; } }
public static Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState Incompatible { get { throw null; } }
public static Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState InProgress { get { throw null; } }
public static Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState Succeeded { get { throw null; } }
public bool Equals(Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState left, Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState right) { throw null; }
public static implicit operator Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState (string value) { throw null; }
public static bool operator !=(Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState left, Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState right) { throw null; }
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct DeviceGroupType : System.IEquatable<Azure.IoT.DeviceUpdate.Models.DeviceGroupType>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public DeviceGroupType(string value) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.DeviceGroupType All { get { throw null; } }
public static Azure.IoT.DeviceUpdate.Models.DeviceGroupType DeviceGroupDefinitions { get { throw null; } }
public static Azure.IoT.DeviceUpdate.Models.DeviceGroupType Devices { get { throw null; } }
public bool Equals(Azure.IoT.DeviceUpdate.Models.DeviceGroupType other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.IoT.DeviceUpdate.Models.DeviceGroupType left, Azure.IoT.DeviceUpdate.Models.DeviceGroupType right) { throw null; }
public static implicit operator Azure.IoT.DeviceUpdate.Models.DeviceGroupType (string value) { throw null; }
public static bool operator !=(Azure.IoT.DeviceUpdate.Models.DeviceGroupType left, Azure.IoT.DeviceUpdate.Models.DeviceGroupType right) { throw null; }
public override string ToString() { throw null; }
}
public partial class DeviceTag
{
internal DeviceTag() { }
public int DeviceCount { get { throw null; } }
public string TagName { get { throw null; } }
}
public static partial class DeviceUpdateModelFactory
{
public static Azure.IoT.DeviceUpdate.Models.Compatibility Compatibility(string deviceManufacturer = null, string deviceModel = null) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.DeploymentDeviceState DeploymentDeviceState(string deviceId = null, int retryCount = 0, bool movedOnToNewDeployment = false, Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState deviceState = default(Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState)) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.DeploymentStatus DeploymentStatus(Azure.IoT.DeviceUpdate.Models.DeploymentState deploymentState = default(Azure.IoT.DeviceUpdate.Models.DeploymentState), int? totalDevices = default(int?), int? devicesIncompatibleCount = default(int?), int? devicesInProgressCount = default(int?), int? devicesCompletedFailedCount = default(int?), int? devicesCompletedSucceededCount = default(int?), int? devicesCanceledCount = default(int?)) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.Device Device(string deviceId = null, string deviceClassId = null, string manufacturer = null, string model = null, string groupId = null, Azure.IoT.DeviceUpdate.Models.UpdateId lastAttemptedUpdateId = null, Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState? deploymentStatus = default(Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState?), Azure.IoT.DeviceUpdate.Models.UpdateId installedUpdateId = null, bool onLatestUpdate = false, string lastDeploymentId = null) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.DeviceClass DeviceClass(string deviceClassId = null, string manufacturer = null, string model = null, Azure.IoT.DeviceUpdate.Models.UpdateId bestCompatibleUpdateId = null) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.DeviceTag DeviceTag(string tagName = null, int deviceCount = 0) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.Error Error(string code = null, string message = null, string target = null, System.Collections.Generic.IEnumerable<Azure.IoT.DeviceUpdate.Models.Error> details = null, Azure.IoT.DeviceUpdate.Models.InnerError innererror = null, System.DateTimeOffset? occurredDateTime = default(System.DateTimeOffset?)) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.File File(string fileId = null, string fileName = null, long sizeInBytes = (long)0, System.Collections.Generic.IReadOnlyDictionary<string, string> hashes = null, string mimeType = null, string etag = null) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.InnerError InnerError(string code = null, string message = null, string errorDetail = null, Azure.IoT.DeviceUpdate.Models.InnerError innerErrorValue = null) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.Operation Operation(string operationId = null, Azure.IoT.DeviceUpdate.Models.OperationStatus status = default(Azure.IoT.DeviceUpdate.Models.OperationStatus), Azure.IoT.DeviceUpdate.Models.UpdateId updateId = null, string resourceLocation = null, Azure.IoT.DeviceUpdate.Models.Error error = null, string traceId = null, System.DateTimeOffset lastActionDateTime = default(System.DateTimeOffset), System.DateTimeOffset createdDateTime = default(System.DateTimeOffset), string etag = null) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.UpdatableDevices UpdatableDevices(Azure.IoT.DeviceUpdate.Models.UpdateId updateId = null, int deviceCount = 0) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.Update Update(Azure.IoT.DeviceUpdate.Models.UpdateId updateId = null, string updateType = null, string installedCriteria = null, System.Collections.Generic.IEnumerable<Azure.IoT.DeviceUpdate.Models.Compatibility> compatibility = null, string manifestVersion = null, System.DateTimeOffset importedDateTime = default(System.DateTimeOffset), System.DateTimeOffset createdDateTime = default(System.DateTimeOffset), string etag = null) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.UpdateCompliance UpdateCompliance(int totalDeviceCount = 0, int onLatestUpdateDeviceCount = 0, int newUpdatesAvailableDeviceCount = 0, int updatesInProgressDeviceCount = 0) { throw null; }
}
public partial class Error
{
internal Error() { }
public string Code { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.IoT.DeviceUpdate.Models.Error> Details { get { throw null; } }
public Azure.IoT.DeviceUpdate.Models.InnerError Innererror { get { throw null; } }
public string Message { get { throw null; } }
public System.DateTimeOffset? OccurredDateTime { get { throw null; } }
public string Target { get { throw null; } }
}
public partial class File
{
internal File() { }
public string Etag { get { throw null; } }
public string FileId { get { throw null; } }
public string FileName { get { throw null; } }
public System.Collections.Generic.IReadOnlyDictionary<string, string> Hashes { get { throw null; } }
public string MimeType { get { throw null; } }
public long SizeInBytes { get { throw null; } }
}
public partial class FileImportMetadata
{
public FileImportMetadata(string filename, string url) { }
public string Filename { get { throw null; } }
public string Url { get { throw null; } }
}
public partial class Group
{
public Group(string groupId, Azure.IoT.DeviceUpdate.Models.GroupType groupType, System.Collections.Generic.IEnumerable<string> tags, string createdDateTime) { }
public string CreatedDateTime { get { throw null; } set { } }
public int? DeviceCount { get { throw null; } set { } }
public string GroupId { get { throw null; } set { } }
public Azure.IoT.DeviceUpdate.Models.GroupType GroupType { get { throw null; } set { } }
public System.Collections.Generic.IList<string> Tags { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct GroupType : System.IEquatable<Azure.IoT.DeviceUpdate.Models.GroupType>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public GroupType(string value) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.GroupType IoTHubTag { get { throw null; } }
public bool Equals(Azure.IoT.DeviceUpdate.Models.GroupType other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.IoT.DeviceUpdate.Models.GroupType left, Azure.IoT.DeviceUpdate.Models.GroupType right) { throw null; }
public static implicit operator Azure.IoT.DeviceUpdate.Models.GroupType (string value) { throw null; }
public static bool operator !=(Azure.IoT.DeviceUpdate.Models.GroupType left, Azure.IoT.DeviceUpdate.Models.GroupType right) { throw null; }
public override string ToString() { throw null; }
}
public enum HashType
{
Sha256 = 1,
}
public sealed partial class ImportManifest
{
public ImportManifest(Azure.IoT.DeviceUpdate.Models.UpdateId updateId, string updateType, string installedCriteria, System.Collections.Generic.List<Azure.IoT.DeviceUpdate.Models.ImportManifestCompatibilityInfo> compatibility, System.DateTime createdDateTime, System.Version manifestVersion, System.Collections.Generic.List<Azure.IoT.DeviceUpdate.Models.ImportManifestFile> files) { }
public System.Collections.Generic.List<Azure.IoT.DeviceUpdate.Models.ImportManifestCompatibilityInfo> Compatibility { get { throw null; } }
public System.DateTime CreatedDateTime { get { throw null; } }
public System.Collections.Generic.List<Azure.IoT.DeviceUpdate.Models.ImportManifestFile> Files { get { throw null; } }
public string InstalledCriteria { get { throw null; } }
public System.Version ManifestVersion { get { throw null; } }
public Azure.IoT.DeviceUpdate.Models.UpdateId UpdateId { get { throw null; } }
public string UpdateType { get { throw null; } }
}
public partial class ImportManifestCompatibilityInfo
{
public ImportManifestCompatibilityInfo(string deviceManufacturer, string deviceModel) { }
public string DeviceManufacturer { get { throw null; } }
public string DeviceModel { get { throw null; } }
}
public partial class ImportManifestFile
{
public ImportManifestFile(string fileName, long sizeInBytes, System.Collections.Generic.Dictionary<Azure.IoT.DeviceUpdate.Models.HashType, string> hashes) { }
public string FileName { get { throw null; } set { } }
public System.Collections.Generic.Dictionary<Azure.IoT.DeviceUpdate.Models.HashType, string> Hashes { get { throw null; } }
public long SizeInBytes { get { throw null; } set { } }
}
public partial class ImportManifestMetadata
{
public ImportManifestMetadata(string url, long sizeInBytes, System.Collections.Generic.IDictionary<string, string> hashes) { }
public System.Collections.Generic.IDictionary<string, string> Hashes { get { throw null; } }
public long SizeInBytes { get { throw null; } }
public string Url { get { throw null; } }
}
public partial class ImportUpdateInput
{
public ImportUpdateInput(Azure.IoT.DeviceUpdate.Models.ImportManifestMetadata importManifest, System.Collections.Generic.IEnumerable<Azure.IoT.DeviceUpdate.Models.FileImportMetadata> files) { }
public System.Collections.Generic.IList<Azure.IoT.DeviceUpdate.Models.FileImportMetadata> Files { get { throw null; } }
public Azure.IoT.DeviceUpdate.Models.ImportManifestMetadata ImportManifest { get { throw null; } }
}
public partial class InnerError
{
internal InnerError() { }
public string Code { get { throw null; } }
public string ErrorDetail { get { throw null; } }
public Azure.IoT.DeviceUpdate.Models.InnerError InnerErrorValue { get { throw null; } }
public string Message { get { throw null; } }
}
public partial class Operation
{
internal Operation() { }
public System.DateTimeOffset CreatedDateTime { get { throw null; } }
public Azure.IoT.DeviceUpdate.Models.Error Error { get { throw null; } }
public string Etag { get { throw null; } }
public System.DateTimeOffset LastActionDateTime { get { throw null; } }
public string OperationId { get { throw null; } }
public string ResourceLocation { get { throw null; } }
public Azure.IoT.DeviceUpdate.Models.OperationStatus Status { get { throw null; } }
public string TraceId { get { throw null; } }
public Azure.IoT.DeviceUpdate.Models.UpdateId UpdateId { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct OperationStatus : System.IEquatable<Azure.IoT.DeviceUpdate.Models.OperationStatus>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public OperationStatus(string value) { throw null; }
public static Azure.IoT.DeviceUpdate.Models.OperationStatus Failed { get { throw null; } }
public static Azure.IoT.DeviceUpdate.Models.OperationStatus NotStarted { get { throw null; } }
public static Azure.IoT.DeviceUpdate.Models.OperationStatus Running { get { throw null; } }
public static Azure.IoT.DeviceUpdate.Models.OperationStatus Succeeded { get { throw null; } }
public static Azure.IoT.DeviceUpdate.Models.OperationStatus Undefined { get { throw null; } }
public bool Equals(Azure.IoT.DeviceUpdate.Models.OperationStatus other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.IoT.DeviceUpdate.Models.OperationStatus left, Azure.IoT.DeviceUpdate.Models.OperationStatus right) { throw null; }
public static implicit operator Azure.IoT.DeviceUpdate.Models.OperationStatus (string value) { throw null; }
public static bool operator !=(Azure.IoT.DeviceUpdate.Models.OperationStatus left, Azure.IoT.DeviceUpdate.Models.OperationStatus right) { throw null; }
public override string ToString() { throw null; }
}
public partial class UpdatableDevices
{
internal UpdatableDevices() { }
public int DeviceCount { get { throw null; } }
public Azure.IoT.DeviceUpdate.Models.UpdateId UpdateId { get { throw null; } }
}
public partial class Update
{
internal Update() { }
public System.Collections.Generic.IReadOnlyList<Azure.IoT.DeviceUpdate.Models.Compatibility> Compatibility { get { throw null; } }
public System.DateTimeOffset CreatedDateTime { get { throw null; } }
public string Etag { get { throw null; } }
public System.DateTimeOffset ImportedDateTime { get { throw null; } }
public string InstalledCriteria { get { throw null; } }
public string ManifestVersion { get { throw null; } }
public Azure.IoT.DeviceUpdate.Models.UpdateId UpdateId { get { throw null; } }
public string UpdateType { get { throw null; } }
}
public partial class UpdateCompliance
{
internal UpdateCompliance() { }
public int NewUpdatesAvailableDeviceCount { get { throw null; } }
public int OnLatestUpdateDeviceCount { get { throw null; } }
public int TotalDeviceCount { get { throw null; } }
public int UpdatesInProgressDeviceCount { get { throw null; } }
}
public partial class UpdateId
{
public UpdateId(string provider, string name, string version) { }
public string Name { get { throw null; } set { } }
public string Provider { get { throw null; } set { } }
public string Version { get { throw null; } set { } }
}
}
| |
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Drawing.NativeMethods..ctor()")]
namespace System.Drawing {
using System.Runtime.InteropServices;
using System;
using System.Security.Permissions;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using Microsoft.Win32;
internal class NativeMethods {
internal static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
public enum RegionFlags {
ERROR = 0,
NULLREGION = 1,
SIMPLEREGION = 2,
COMPLEXREGION = 3,
}
public const byte PC_NOCOLLAPSE = 0x04;
public const int MAX_PATH = 260;
internal const int SM_REMOTESESSION = 0x1000;
internal const int OBJ_DC = 3,
OBJ_METADC = 4,
OBJ_MEMDC = 10,
OBJ_ENHMETADC = 12,
DIB_RGB_COLORS = 0,
BI_BITFIELDS = 3,
BI_RGB = 0,
BITMAPINFO_MAX_COLORSIZE = 256,
SPI_GETICONTITLELOGFONT = 0x001F,
SPI_GETNONCLIENTMETRICS = 41,
DEFAULT_GUI_FONT = 17;
[StructLayout(LayoutKind.Sequential)]
internal struct BITMAPINFO_FLAT {
public int bmiHeader_biSize;// = Marshal.SizeOf(typeof(BITMAPINFOHEADER));
public int bmiHeader_biWidth;
public int bmiHeader_biHeight;
public short bmiHeader_biPlanes;
public short bmiHeader_biBitCount;
public int bmiHeader_biCompression;
public int bmiHeader_biSizeImage;
public int bmiHeader_biXPelsPerMeter;
public int bmiHeader_biYPelsPerMeter;
public int bmiHeader_biClrUsed;
public int bmiHeader_biClrImportant;
[MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst=BITMAPINFO_MAX_COLORSIZE*4)]
public byte[] bmiColors; // RGBQUAD structs... Blue-Green-Red-Reserved, repeat...
}
[StructLayout(LayoutKind.Sequential)]
internal class BITMAPINFOHEADER {
public int biSize = 40; // ndirect.DllLib.sizeOf( this );
public int biWidth;
public int biHeight;
public short biPlanes;
public short biBitCount;
public int biCompression;
public int biSizeImage;
public int biXPelsPerMeter;
public int biYPelsPerMeter;
public int biClrUsed;
public int biClrImportant;
}
[StructLayout(LayoutKind.Sequential)]
internal struct PALETTEENTRY {
public byte peRed;
public byte peGreen;
public byte peBlue;
public byte peFlags;
}
internal struct RGBQUAD {
public byte rgbBlue;
public byte rgbGreen;
public byte rgbRed;
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
public byte rgbReserved;
#pragma warning restore 0414
}
[StructLayout(LayoutKind.Sequential)]
internal class NONCLIENTMETRICS {
public int cbSize = Marshal.SizeOf(typeof(NONCLIENTMETRICS));
public int iBorderWidth;
public int iScrollWidth;
public int iScrollHeight;
public int iCaptionWidth;
public int iCaptionHeight;
[MarshalAs(UnmanagedType.Struct)]
public SafeNativeMethods.LOGFONT lfCaptionFont;
public int iSmCaptionWidth;
public int iSmCaptionHeight;
[MarshalAs(UnmanagedType.Struct)]
public SafeNativeMethods.LOGFONT lfSmCaptionFont;
public int iMenuWidth;
public int iMenuHeight;
[MarshalAs(UnmanagedType.Struct)]
public SafeNativeMethods.LOGFONT lfMenuFont;
[MarshalAs(UnmanagedType.Struct)]
public SafeNativeMethods.LOGFONT lfStatusFont;
[MarshalAs(UnmanagedType.Struct)]
public SafeNativeMethods.LOGFONT lfMessageFont;
}
/* FxCop rule 'AvoidBuildingNonCallableCode' - Left here in case it is needed in the future.
public static byte[] Win9xHalfTonePalette {
get {
return new byte[] {
// The first 10 system colors
0x00, 0x00, 0x00, 0x00, // 0 Sys Black, gray 0
0x80, 0x00, 0x00, 0x00, // 1 Sys Dk Red
0x00, 0x80, 0x00, 0x00, // 2 Sys Dk Green
0x80, 0x80, 0x00, 0x00, // 3 Sys Dk Yellow
0x00, 0x00, 0x80, 0x00, // 4 Sys Dk Blue
0x80, 0x00, 0x80, 0x00, // 5 Sys Dk Violet
0x00, 0x80, 0x80, 0x00, // 6 Sys Dk Cyan
0xC0, 0xC0, 0xC0, 0x00, // 7 Sys Lt Gray, gray 192
// The following two system entries are modified for the desktop.
0xC0, 0xDC, 0xC0, 0x00, // 8 Sys 8 - VARIABLE
0xA6, 0xCA, 0xF0, 0x00, // 9 Sys 9 - VARIABLE
// Gray scale entries (dark)
0x04, 0x04, 0x04, PC_NOCOLLAPSE, // 10 Gray 4
0x08, 0x08, 0x08, PC_NOCOLLAPSE, // 11 Gray 8
0x0C, 0x0C, 0x0C, PC_NOCOLLAPSE, // 12 Gray 12
0x11, 0x11, 0x11, PC_NOCOLLAPSE, // 13 Gray 17
0x16, 0x16, 0x16, PC_NOCOLLAPSE, // 14 Gray 22
0x1C, 0x1C, 0x1C, PC_NOCOLLAPSE, // 15 Gray 28
0x22, 0x22, 0x22, PC_NOCOLLAPSE, // 16 Gray 34
0x29, 0x29, 0x29, PC_NOCOLLAPSE, // 17 Gray 41
0x55, 0x55, 0x55, PC_NOCOLLAPSE, // 18 Gray 85
0x4D, 0x4D, 0x4D, PC_NOCOLLAPSE, // 19 Gray 77
0x42, 0x42, 0x42, PC_NOCOLLAPSE, // 20 Gray 66
0x39, 0x39, 0x39, PC_NOCOLLAPSE, // 21 Gray 57
// Custom app/OS entries
0xFF, 0x7C, 0x80, PC_NOCOLLAPSE, // 22 Salmon
0xFF, 0x50, 0x50, PC_NOCOLLAPSE, // 23 Red
0xD6, 0x00, 0x93, PC_NOCOLLAPSE, // 24 Purple
0xCC, 0xEC, 0xFF, PC_NOCOLLAPSE, // 25 Lt Blue
0xEF, 0xD6, 0xC6, PC_NOCOLLAPSE, // 26 Win95 Tan
0xE7, 0xE7, 0xD6, PC_NOCOLLAPSE, // 27 Win95 Tan
0xAD, 0xA9, 0x90, PC_NOCOLLAPSE, // 28 Win95 Grayish
// Halftone palette entries
0x33, 0x00, 0x00, PC_NOCOLLAPSE, // 29
0x66, 0x00, 0x00, PC_NOCOLLAPSE, // 30
0x99, 0x00, 0x00, PC_NOCOLLAPSE, // 31
0xCC, 0x00, 0x00, PC_NOCOLLAPSE, // 32
0x00, 0x33, 0x00, PC_NOCOLLAPSE, // 33
0x33, 0x33, 0x00, PC_NOCOLLAPSE, // 34
0x66, 0x33, 0x00, PC_NOCOLLAPSE, // 35
0x99, 0x33, 0x00, PC_NOCOLLAPSE, // 36
0xCC, 0x33, 0x00, PC_NOCOLLAPSE, // 37
0xFF, 0x33, 0x00, PC_NOCOLLAPSE, // 38
0x00, 0x66, 0x00, PC_NOCOLLAPSE, // 39
0x33, 0x66, 0x00, PC_NOCOLLAPSE, // 40
0x66, 0x66, 0x00, PC_NOCOLLAPSE, // 41
0x99, 0x66, 0x00, PC_NOCOLLAPSE, // 42
0xCC, 0x66, 0x00, PC_NOCOLLAPSE, // 43
0xFF, 0x66, 0x00, PC_NOCOLLAPSE, // 44
0x00, 0x99, 0x00, PC_NOCOLLAPSE, // 45
0x33, 0x99, 0x00, PC_NOCOLLAPSE, // 46
0x66, 0x99, 0x00, PC_NOCOLLAPSE, // 47
0x99, 0x99, 0x00, PC_NOCOLLAPSE, // 48
0xCC, 0x99, 0x00, PC_NOCOLLAPSE, // 49
0xFF, 0x99, 0x00, PC_NOCOLLAPSE, // 50
0x00, 0xCC, 0x00, PC_NOCOLLAPSE, // 51
0x33, 0xCC, 0x00, PC_NOCOLLAPSE, // 52
0x66, 0xCC, 0x00, PC_NOCOLLAPSE, // 53
0x99, 0xCC, 0x00, PC_NOCOLLAPSE, // 54
0xCC, 0xCC, 0x00, PC_NOCOLLAPSE, // 55
0xFF, 0xCC, 0x00, PC_NOCOLLAPSE, // 56
0x66, 0xFF, 0x00, PC_NOCOLLAPSE, // 57
0x99, 0xFF, 0x00, PC_NOCOLLAPSE, // 58
0xCC, 0xFF, 0x00, PC_NOCOLLAPSE, // 59
0x00, 0x00, 0x33, PC_NOCOLLAPSE, // 60
0x33, 0x00, 0x33, PC_NOCOLLAPSE, // 61
0x66, 0x00, 0x33, PC_NOCOLLAPSE, // 62
0x99, 0x00, 0x33, PC_NOCOLLAPSE, // 63
0xCC, 0x00, 0x33, PC_NOCOLLAPSE, // 64
0xFF, 0x00, 0x33, PC_NOCOLLAPSE, // 65
0x00, 0x33, 0x33, PC_NOCOLLAPSE, // 66
0x33, 0x33, 0x33, PC_NOCOLLAPSE, // 67 Gray 51
0x66, 0x33, 0x33, PC_NOCOLLAPSE, // 68
0x99, 0x33, 0x33, PC_NOCOLLAPSE, // 69
0xCC, 0x33, 0x33, PC_NOCOLLAPSE, // 70
0xFF, 0x33, 0x33, PC_NOCOLLAPSE, // 71
0x00, 0x66, 0x33, PC_NOCOLLAPSE, // 72
0x33, 0x66, 0x33, PC_NOCOLLAPSE, // 73
0x66, 0x66, 0x33, PC_NOCOLLAPSE, // 74
0x99, 0x66, 0x33, PC_NOCOLLAPSE, // 75
0xCC, 0x66, 0x33, PC_NOCOLLAPSE, // 76
0xFF, 0x66, 0x33, PC_NOCOLLAPSE, // 77
0x00, 0x99, 0x33, PC_NOCOLLAPSE, // 78
0x33, 0x99, 0x33, PC_NOCOLLAPSE, // 79
0x66, 0x99, 0x33, PC_NOCOLLAPSE, // 80
0x99, 0x99, 0x33, PC_NOCOLLAPSE, // 81
0xCC, 0x99, 0x33, PC_NOCOLLAPSE, // 82
0xFF, 0x99, 0x33, PC_NOCOLLAPSE, // 83
0x00, 0xCC, 0x33, PC_NOCOLLAPSE, // 84
0x33, 0xCC, 0x33, PC_NOCOLLAPSE, // 85
0x66, 0xCC, 0x33, PC_NOCOLLAPSE, // 86
0x99, 0xCC, 0x33, PC_NOCOLLAPSE, // 87
0xCC, 0xCC, 0x33, PC_NOCOLLAPSE, // 88
0xFF, 0xCC, 0x33, PC_NOCOLLAPSE, // 89
0x33, 0xFF, 0x33, PC_NOCOLLAPSE, // 90
0x66, 0xFF, 0x33, PC_NOCOLLAPSE, // 91
0x99, 0xFF, 0x33, PC_NOCOLLAPSE, // 92
0xCC, 0xFF, 0x33, PC_NOCOLLAPSE, // 93
0xFF, 0xFF, 0x33, PC_NOCOLLAPSE, // 94
0x00, 0x00, 0x66, PC_NOCOLLAPSE, // 95
0x33, 0x00, 0x66, PC_NOCOLLAPSE, // 96
0x66, 0x00, 0x66, PC_NOCOLLAPSE, // 97
0x99, 0x00, 0x66, PC_NOCOLLAPSE, // 98
0xCC, 0x00, 0x66, PC_NOCOLLAPSE, // 99
0xFF, 0x00, 0x66, PC_NOCOLLAPSE, // 100
0x00, 0x33, 0x66, PC_NOCOLLAPSE, // 101
0x33, 0x33, 0x66, PC_NOCOLLAPSE, // 102
0x66, 0x33, 0x66, PC_NOCOLLAPSE, // 103
0x99, 0x33, 0x66, PC_NOCOLLAPSE, // 104
0xCC, 0x33, 0x66, PC_NOCOLLAPSE, // 105
0xFF, 0x33, 0x66, PC_NOCOLLAPSE, // 106
0x00, 0x66, 0x66, PC_NOCOLLAPSE, // 107
0x33, 0x66, 0x66, PC_NOCOLLAPSE, // 108
0x66, 0x66, 0x66, PC_NOCOLLAPSE, // 109 Gray 102
0x99, 0x66, 0x66, PC_NOCOLLAPSE, // 110
0xCC, 0x66, 0x66, PC_NOCOLLAPSE, // 111
0x00, 0x99, 0x66, PC_NOCOLLAPSE, // 112
0x33, 0x99, 0x66, PC_NOCOLLAPSE, // 113
0x66, 0x99, 0x66, PC_NOCOLLAPSE, // 114
0x99, 0x99, 0x66, PC_NOCOLLAPSE, // 115
0xCC, 0x99, 0x66, PC_NOCOLLAPSE, // 116
0xFF, 0x99, 0x66, PC_NOCOLLAPSE, // 117
0x00, 0xCC, 0x66, PC_NOCOLLAPSE, // 118
0x33, 0xCC, 0x66, PC_NOCOLLAPSE, // 119
0x99, 0xCC, 0x66, PC_NOCOLLAPSE, // 120
0xCC, 0xCC, 0x66, PC_NOCOLLAPSE, // 121
0xFF, 0xCC, 0x66, PC_NOCOLLAPSE, // 122
0x00, 0xFF, 0x66, PC_NOCOLLAPSE, // 123
0x33, 0xFF, 0x66, PC_NOCOLLAPSE, // 124
0x99, 0xFF, 0x66, PC_NOCOLLAPSE, // 125
0xCC, 0xFF, 0x66, PC_NOCOLLAPSE, // 126
0xFF, 0x00, 0xCC, PC_NOCOLLAPSE, // 127
0xCC, 0x00, 0xFF, PC_NOCOLLAPSE, // 128
0x00, 0x99, 0x99, PC_NOCOLLAPSE, // 129
0x99, 0x33, 0x99, PC_NOCOLLAPSE, // 130
0x99, 0x00, 0x99, PC_NOCOLLAPSE, // 131
0xCC, 0x00, 0x99, PC_NOCOLLAPSE, // 132
0x00, 0x00, 0x99, PC_NOCOLLAPSE, // 133
0x33, 0x33, 0x99, PC_NOCOLLAPSE, // 134
0x66, 0x00, 0x99, PC_NOCOLLAPSE, // 135
0xCC, 0x33, 0x99, PC_NOCOLLAPSE, // 136
0xFF, 0x00, 0x99, PC_NOCOLLAPSE, // 137
0x00, 0x66, 0x99, PC_NOCOLLAPSE, // 138
0x33, 0x66, 0x99, PC_NOCOLLAPSE, // 139
0x66, 0x33, 0x99, PC_NOCOLLAPSE, // 140
0x99, 0x66, 0x99, PC_NOCOLLAPSE, // 141
0xCC, 0x66, 0x99, PC_NOCOLLAPSE, // 142
0xFF, 0x33, 0x99, PC_NOCOLLAPSE, // 143
0x33, 0x99, 0x99, PC_NOCOLLAPSE, // 144
0x66, 0x99, 0x99, PC_NOCOLLAPSE, // 145
0x99, 0x99, 0x99, PC_NOCOLLAPSE, // 146 Gray 153
0xCC, 0x99, 0x99, PC_NOCOLLAPSE, // 147
0xFF, 0x99, 0x99, PC_NOCOLLAPSE, // 148
0x00, 0xCC, 0x99, PC_NOCOLLAPSE, // 149
0x33, 0xCC, 0x99, PC_NOCOLLAPSE, // 150
0x66, 0xCC, 0x66, PC_NOCOLLAPSE, // 151
0x99, 0xCC, 0x99, PC_NOCOLLAPSE, // 152
0xCC, 0xCC, 0x99, PC_NOCOLLAPSE, // 153
0xFF, 0xCC, 0x99, PC_NOCOLLAPSE, // 154
0x00, 0xFF, 0x99, PC_NOCOLLAPSE, // 155
0x33, 0xFF, 0x99, PC_NOCOLLAPSE, // 156
0x66, 0xCC, 0x99, PC_NOCOLLAPSE, // 157
0x99, 0xFF, 0x99, PC_NOCOLLAPSE, // 158
0xCC, 0xFF, 0x99, PC_NOCOLLAPSE, // 159
0xFF, 0xFF, 0x99, PC_NOCOLLAPSE, // 160
0x00, 0x00, 0xCC, PC_NOCOLLAPSE, // 161
0x33, 0x00, 0x99, PC_NOCOLLAPSE, // 162
0x66, 0x00, 0xCC, PC_NOCOLLAPSE, // 163
0x99, 0x00, 0xCC, PC_NOCOLLAPSE, // 164
0xCC, 0x00, 0xCC, PC_NOCOLLAPSE, // 165
0x00, 0x33, 0x99, PC_NOCOLLAPSE, // 166
0x33, 0x33, 0xCC, PC_NOCOLLAPSE, // 167
0x66, 0x33, 0xCC, PC_NOCOLLAPSE, // 168
0x99, 0x33, 0xCC, PC_NOCOLLAPSE, // 169
0xCC, 0x33, 0xCC, PC_NOCOLLAPSE, // 170
0xFF, 0x33, 0xCC, PC_NOCOLLAPSE, // 171
0x00, 0x66, 0xCC, PC_NOCOLLAPSE, // 172
0x33, 0x66, 0xCC, PC_NOCOLLAPSE, // 173
0x66, 0x66, 0x99, PC_NOCOLLAPSE, // 174
0x99, 0x66, 0xCC, PC_NOCOLLAPSE, // 175
0xCC, 0x66, 0xCC, PC_NOCOLLAPSE, // 176
0xFF, 0x66, 0x99, PC_NOCOLLAPSE, // 177
0x00, 0x99, 0xCC, PC_NOCOLLAPSE, // 178
0x33, 0x99, 0xCC, PC_NOCOLLAPSE, // 179
0x66, 0x99, 0xCC, PC_NOCOLLAPSE, // 180
0x99, 0x99, 0xCC, PC_NOCOLLAPSE, // 181
0xCC, 0x99, 0xCC, PC_NOCOLLAPSE, // 182
0xFF, 0x99, 0xCC, PC_NOCOLLAPSE, // 183
0x00, 0xCC, 0xCC, PC_NOCOLLAPSE, // 184
0x33, 0xCC, 0xCC, PC_NOCOLLAPSE, // 185
0x66, 0xCC, 0xCC, PC_NOCOLLAPSE, // 186
0x99, 0xCC, 0xCC, PC_NOCOLLAPSE, // 187
0xCC, 0xCC, 0xCC, PC_NOCOLLAPSE, // 188 Gray 204
0xFF, 0xCC, 0xCC, PC_NOCOLLAPSE, // 189
0x00, 0xFF, 0xCC, PC_NOCOLLAPSE, // 190
0x33, 0xFF, 0xCC, PC_NOCOLLAPSE, // 191
0x66, 0xFF, 0x99, PC_NOCOLLAPSE, // 192
0x99, 0xFF, 0xCC, PC_NOCOLLAPSE, // 193
0xCC, 0xFF, 0xCC, PC_NOCOLLAPSE, // 194
0xFF, 0xFF, 0xCC, PC_NOCOLLAPSE, // 195
0x33, 0x00, 0xCC, PC_NOCOLLAPSE, // 196
0x66, 0x00, 0xFF, PC_NOCOLLAPSE, // 197
0x99, 0x00, 0xFF, PC_NOCOLLAPSE, // 198
0x00, 0x33, 0xCC, PC_NOCOLLAPSE, // 199
0x33, 0x33, 0xFF, PC_NOCOLLAPSE, // 200
0x66, 0x33, 0xFF, PC_NOCOLLAPSE, // 201
0x99, 0x33, 0xFF, PC_NOCOLLAPSE, // 202
0xCC, 0x33, 0xFF, PC_NOCOLLAPSE, // 203
0xFF, 0x33, 0xFF, PC_NOCOLLAPSE, // 204
0x00, 0x66, 0xFF, PC_NOCOLLAPSE, // 205
0x33, 0x66, 0xFF, PC_NOCOLLAPSE, // 206
0x66, 0x66, 0xCC, PC_NOCOLLAPSE, // 207
0x99, 0x66, 0xFF, PC_NOCOLLAPSE, // 208
0xCC, 0x66, 0xFF, PC_NOCOLLAPSE, // 209
0xFF, 0x66, 0xCC, PC_NOCOLLAPSE, // 210
0x00, 0x99, 0xFF, PC_NOCOLLAPSE, // 211
0x33, 0x99, 0xFF, PC_NOCOLLAPSE, // 212
0x66, 0x99, 0xFF, PC_NOCOLLAPSE, // 213
0x99, 0x99, 0xFF, PC_NOCOLLAPSE, // 214
0xCC, 0x99, 0xFF, PC_NOCOLLAPSE, // 215
0xFF, 0x99, 0xFF, PC_NOCOLLAPSE, // 216
0x00, 0xCC, 0xFF, PC_NOCOLLAPSE, // 217
0x33, 0xCC, 0xFF, PC_NOCOLLAPSE, // 218
0x66, 0xCC, 0xFF, PC_NOCOLLAPSE, // 219
0x99, 0xCC, 0xFF, PC_NOCOLLAPSE, // 220
0xCC, 0xCC, 0xFF, PC_NOCOLLAPSE, // 221
0xFF, 0xCC, 0xFF, PC_NOCOLLAPSE, // 222
0x33, 0xFF, 0xFF, PC_NOCOLLAPSE, // 223
0x66, 0xFF, 0xCC, PC_NOCOLLAPSE, // 224
0x99, 0xFF, 0xFF, PC_NOCOLLAPSE, // 225
0xCC, 0xFF, 0xFF, PC_NOCOLLAPSE, // 226
0xFF, 0x66, 0x66, PC_NOCOLLAPSE, // 227
0x66, 0xFF, 0x66, PC_NOCOLLAPSE, // 228
0xFF, 0xFF, 0x66, PC_NOCOLLAPSE, // 229
0x66, 0x66, 0xFF, PC_NOCOLLAPSE, // 230
0xFF, 0x66, 0xFF, PC_NOCOLLAPSE, // 231
0x66, 0xFF, 0xFF, PC_NOCOLLAPSE, // 232
// App custom colors
0xA5, 0x00, 0x21, PC_NOCOLLAPSE, // 233 Brick red
// Gray palette
0x5F, 0x5F, 0x5F, PC_NOCOLLAPSE, // 234 Gray 95
0x77, 0x77, 0x77, PC_NOCOLLAPSE, // 235 Gray 119
0x86, 0x86, 0x86, PC_NOCOLLAPSE, // 236 Gray 134
0x96, 0x96, 0x96, PC_NOCOLLAPSE, // 237 Gray 150
0xCB, 0xCB, 0xCB, PC_NOCOLLAPSE, // 238 Gray 203
0xB2, 0xB2, 0xB2, PC_NOCOLLAPSE, // 239 Gray 178
0xD7, 0xD7, 0xD7, PC_NOCOLLAPSE, // 240 Gray 215
0xDD, 0xDD, 0xDD, PC_NOCOLLAPSE, // 241 Gray 221
0xE3, 0xE3, 0xE3, PC_NOCOLLAPSE, // 242 Gray 227
0xEA, 0xEA, 0xEA, PC_NOCOLLAPSE, // 243 Gray 234
0xF1, 0xF1, 0xF1, PC_NOCOLLAPSE, // 244 Gray 241
0xF8, 0xF8, 0xF8, PC_NOCOLLAPSE, // 245 Gray 248
// The last 10 system colors
// The following two system entries are modified for the desktop.
0xFF, 0xFB, 0xF0, 0x00, // 246 Sys 246 - VARIABLE
0xA0, 0xA0, 0xA4, 0x00, // 247 Sys 247 - VARIABLE
0x80, 0x80, 0x80, 0x00, // 248 Sys Lt Gray, gray 128
0xFF, 0x00, 0x00, 0x00, // 249 Sys Red
0x00, 0xFF, 0x00, 0x00, // 250 Sys Green
0xFF, 0xFF, 0x00, 0x00, // 251 Sys Yellow
0x00, 0x00, 0xFF, 0x00, // 252 Sys Blue
0xFF, 0x00, 0xFF, 0x00, // 253 Sys Violet
0x00, 0xFF, 0xFF, 0x00, // 254 Sys Cyan
0xFF, 0xFF, 0xFF, 0x00, // 255 Sys White, gray 255
};
}
}*/
}
}
| |
using System;
using Lucene.Net.Documents;
namespace Lucene.Net.Search
{
using Lucene.Net.Index;
using NUnit.Framework;
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using Bits = Lucene.Net.Util.Bits;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Documents.Document;
using Field = Field;
using FixedBitSet = Lucene.Net.Util.FixedBitSet;
using IndexReader = Lucene.Net.Index.IndexReader;
using IOUtils = Lucene.Net.Util.IOUtils;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using SerialMergeScheduler = Lucene.Net.Index.SerialMergeScheduler;
using SlowCompositeReaderWrapper = Lucene.Net.Index.SlowCompositeReaderWrapper;
using StringField = StringField;
using Term = Lucene.Net.Index.Term;
[TestFixture]
public class TestCachingWrapperFilter : LuceneTestCase
{
internal Directory Dir;
internal DirectoryReader Ir;
internal IndexSearcher @is;
internal RandomIndexWriter Iw;
[SetUp]
public override void SetUp()
{
base.SetUp();
Dir = NewDirectory();
Iw = new RandomIndexWriter(Random(), Dir);
Document doc = new Document();
Field idField = new StringField("id", "", Field.Store.NO);
doc.Add(idField);
// add 500 docs with id 0..499
for (int i = 0; i < 500; i++)
{
idField.StringValue = Convert.ToString(i);
Iw.AddDocument(doc);
}
// delete 20 of them
for (int i = 0; i < 20; i++)
{
Iw.DeleteDocuments(new Term("id", Convert.ToString(Random().Next(Iw.MaxDoc()))));
}
Ir = Iw.Reader;
@is = NewSearcher(Ir);
}
[TearDown]
public override void TearDown()
{
IOUtils.Close(Iw, Ir, Dir);
base.TearDown();
}
private void AssertFilterEquals(Filter f1, Filter f2)
{
Query query = new MatchAllDocsQuery();
TopDocs hits1 = @is.Search(query, f1, Ir.MaxDoc);
TopDocs hits2 = @is.Search(query, f2, Ir.MaxDoc);
Assert.AreEqual(hits1.TotalHits, hits2.TotalHits);
CheckHits.CheckEqual(query, hits1.ScoreDocs, hits2.ScoreDocs);
// now do it again to confirm caching works
TopDocs hits3 = @is.Search(query, f1, Ir.MaxDoc);
TopDocs hits4 = @is.Search(query, f2, Ir.MaxDoc);
Assert.AreEqual(hits3.TotalHits, hits4.TotalHits);
CheckHits.CheckEqual(query, hits3.ScoreDocs, hits4.ScoreDocs);
}
/// <summary>
/// test null iterator </summary>
[Test]
public virtual void TestEmpty()
{
Query query = new BooleanQuery();
Filter expected = new QueryWrapperFilter(query);
Filter actual = new CachingWrapperFilter(expected);
AssertFilterEquals(expected, actual);
}
/// <summary>
/// test iterator returns NO_MORE_DOCS </summary>
[Test]
public virtual void TestEmpty2()
{
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term("id", "0")), BooleanClause.Occur.MUST);
query.Add(new TermQuery(new Term("id", "0")), BooleanClause.Occur.MUST_NOT);
Filter expected = new QueryWrapperFilter(query);
Filter actual = new CachingWrapperFilter(expected);
AssertFilterEquals(expected, actual);
}
/// <summary>
/// test null docidset </summary>
[Test]
public virtual void TestEmpty3()
{
Filter expected = new PrefixFilter(new Term("bogusField", "bogusVal"));
Filter actual = new CachingWrapperFilter(expected);
AssertFilterEquals(expected, actual);
}
/// <summary>
/// test iterator returns single document </summary>
[Test]
public virtual void TestSingle()
{
for (int i = 0; i < 10; i++)
{
int id = Random().Next(Ir.MaxDoc);
Query query = new TermQuery(new Term("id", Convert.ToString(id)));
Filter expected = new QueryWrapperFilter(query);
Filter actual = new CachingWrapperFilter(expected);
AssertFilterEquals(expected, actual);
}
}
/// <summary>
/// test sparse filters (match single documents) </summary>
[Test]
public virtual void TestSparse()
{
for (int i = 0; i < 10; i++)
{
int id_start = Random().Next(Ir.MaxDoc - 1);
int id_end = id_start + 1;
Query query = TermRangeQuery.NewStringRange("id", Convert.ToString(id_start), Convert.ToString(id_end), true, true);
Filter expected = new QueryWrapperFilter(query);
Filter actual = new CachingWrapperFilter(expected);
AssertFilterEquals(expected, actual);
}
}
/// <summary>
/// test dense filters (match entire index) </summary>
[Test]
public virtual void TestDense()
{
Query query = new MatchAllDocsQuery();
Filter expected = new QueryWrapperFilter(query);
Filter actual = new CachingWrapperFilter(expected);
AssertFilterEquals(expected, actual);
}
[Test]
public virtual void TestCachingWorks()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir);
writer.Dispose();
IndexReader reader = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir));
AtomicReaderContext context = (AtomicReaderContext)reader.Context;
MockFilter filter = new MockFilter();
CachingWrapperFilter cacher = new CachingWrapperFilter(filter);
// first time, nested filter is called
DocIdSet strongRef = cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs);
Assert.IsTrue(filter.WasCalled(), "first time");
// make sure no exception if cache is holding the wrong docIdSet
cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs);
// second time, nested filter should not be called
filter.Clear();
cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs);
Assert.IsFalse(filter.WasCalled(), "second time");
reader.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestNullDocIdSet()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir);
writer.Dispose();
IndexReader reader = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir));
AtomicReaderContext context = (AtomicReaderContext)reader.Context;
Filter filter = new FilterAnonymousInnerClassHelper(this, context);
CachingWrapperFilter cacher = new CachingWrapperFilter(filter);
// the caching filter should return the empty set constant
//Assert.IsNull(cacher.GetDocIdSet(context, "second time", (context.AtomicReader).LiveDocs));
Assert.IsNull(cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs));
reader.Dispose();
dir.Dispose();
}
private class FilterAnonymousInnerClassHelper : Filter
{
private readonly TestCachingWrapperFilter OuterInstance;
private AtomicReaderContext Context;
public FilterAnonymousInnerClassHelper(TestCachingWrapperFilter outerInstance, AtomicReaderContext context)
{
this.OuterInstance = outerInstance;
this.Context = context;
}
public override DocIdSet GetDocIdSet(AtomicReaderContext context, Bits acceptDocs)
{
return null;
}
}
[Test]
public virtual void TestNullDocIdSetIterator()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir);
writer.Dispose();
IndexReader reader = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir));
AtomicReaderContext context = (AtomicReaderContext)reader.Context;
Filter filter = new FilterAnonymousInnerClassHelper2(this, context);
CachingWrapperFilter cacher = new CachingWrapperFilter(filter);
// the caching filter should return the empty set constant
Assert.IsNull(cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs));
reader.Dispose();
dir.Dispose();
}
private class FilterAnonymousInnerClassHelper2 : Filter
{
private readonly TestCachingWrapperFilter OuterInstance;
private AtomicReaderContext Context;
public FilterAnonymousInnerClassHelper2(TestCachingWrapperFilter outerInstance, AtomicReaderContext context)
{
this.OuterInstance = outerInstance;
this.Context = context;
}
public override DocIdSet GetDocIdSet(AtomicReaderContext context, Bits acceptDocs)
{
return new DocIdSetAnonymousInnerClassHelper(this);
}
private class DocIdSetAnonymousInnerClassHelper : DocIdSet
{
private readonly FilterAnonymousInnerClassHelper2 OuterInstance;
public DocIdSetAnonymousInnerClassHelper(FilterAnonymousInnerClassHelper2 outerInstance)
{
this.OuterInstance = outerInstance;
}
public override DocIdSetIterator GetIterator()
{
return null;
}
}
}
private static void AssertDocIdSetCacheable(IndexReader reader, Filter filter, bool shouldCacheable)
{
Assert.IsTrue(reader.Context is AtomicReaderContext);
AtomicReaderContext context = (AtomicReaderContext)reader.Context;
CachingWrapperFilter cacher = new CachingWrapperFilter(filter);
DocIdSet originalSet = filter.GetDocIdSet(context, (context.AtomicReader).LiveDocs);
DocIdSet cachedSet = cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs);
if (originalSet == null)
{
Assert.IsNull(cachedSet);
}
if (cachedSet == null)
{
Assert.IsTrue(originalSet == null || originalSet.GetIterator() == null);
}
else
{
Assert.IsTrue(cachedSet.Cacheable);
Assert.AreEqual(shouldCacheable, originalSet.Cacheable);
//System.out.println("Original: "+originalSet.getClass().getName()+" -- cached: "+cachedSet.getClass().getName());
if (originalSet.Cacheable)
{
Assert.AreEqual(originalSet.GetType(), cachedSet.GetType(), "Cached DocIdSet must be of same class like uncached, if cacheable");
}
else
{
Assert.IsTrue(cachedSet is FixedBitSet || cachedSet == null, "Cached DocIdSet must be an FixedBitSet if the original one was not cacheable");
}
}
}
[Test]
public virtual void TestIsCacheAble()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir);
writer.AddDocument(new Document());
writer.Dispose();
IndexReader reader = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir));
// not cacheable:
AssertDocIdSetCacheable(reader, new QueryWrapperFilter(new TermQuery(new Term("test", "value"))), false);
// returns default empty docidset, always cacheable:
AssertDocIdSetCacheable(reader, NumericRangeFilter.NewIntRange("test", Convert.ToInt32(10000), Convert.ToInt32(-10000), true, true), true);
// is cacheable:
AssertDocIdSetCacheable(reader, FieldCacheRangeFilter.NewIntRange("test", Convert.ToInt32(10), Convert.ToInt32(20), true, true), true);
// a fixedbitset filter is always cacheable
AssertDocIdSetCacheable(reader, new FilterAnonymousInnerClassHelper3(this), true);
reader.Dispose();
dir.Dispose();
}
private class FilterAnonymousInnerClassHelper3 : Filter
{
private readonly TestCachingWrapperFilter OuterInstance;
public FilterAnonymousInnerClassHelper3(TestCachingWrapperFilter outerInstance)
{
this.OuterInstance = outerInstance;
}
public override DocIdSet GetDocIdSet(AtomicReaderContext context, Bits acceptDocs)
{
return new FixedBitSet(context.Reader.MaxDoc);
}
}
[Test]
public virtual void TestEnforceDeletions()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(NewLogMergePolicy(10)));
// asserts below requires no unexpected merges:
// NOTE: cannot use writer.getReader because RIW (on
// flipping a coin) may give us a newly opened reader,
// but we use .reopen on this reader below and expect to
// (must) get an NRT reader:
DirectoryReader reader = DirectoryReader.Open(writer.w, true);
// same reason we don't wrap?
IndexSearcher searcher = NewSearcher(reader, false);
// add a doc, refresh the reader, and check that it's there
Document doc = new Document();
doc.Add(NewStringField("id", "1", Field.Store.YES));
writer.AddDocument(doc);
reader = RefreshReader(reader);
searcher = NewSearcher(reader, false);
TopDocs docs = searcher.Search(new MatchAllDocsQuery(), 1);
Assert.AreEqual(1, docs.TotalHits, "Should find a hit...");
Filter startFilter = new QueryWrapperFilter(new TermQuery(new Term("id", "1")));
CachingWrapperFilter filter = new CachingWrapperFilter(startFilter);
docs = searcher.Search(new MatchAllDocsQuery(), filter, 1);
Assert.IsTrue(filter.SizeInBytes() > 0);
Assert.AreEqual(1, docs.TotalHits, "[query + filter] Should find a hit...");
Query constantScore = new ConstantScoreQuery(filter);
docs = searcher.Search(constantScore, 1);
Assert.AreEqual(1, docs.TotalHits, "[just filter] Should find a hit...");
// make sure we get a cache hit when we reopen reader
// that had no change to deletions
// fake delete (deletes nothing):
writer.DeleteDocuments(new Term("foo", "bar"));
IndexReader oldReader = reader;
reader = RefreshReader(reader);
Assert.IsTrue(reader == oldReader);
int missCount = filter.MissCount;
docs = searcher.Search(constantScore, 1);
Assert.AreEqual(1, docs.TotalHits, "[just filter] Should find a hit...");
// cache hit:
Assert.AreEqual(missCount, filter.MissCount);
// now delete the doc, refresh the reader, and see that it's not there
writer.DeleteDocuments(new Term("id", "1"));
// NOTE: important to hold ref here so GC doesn't clear
// the cache entry! Else the assert below may sometimes
// fail:
oldReader = reader;
reader = RefreshReader(reader);
searcher = NewSearcher(reader, false);
missCount = filter.MissCount;
docs = searcher.Search(new MatchAllDocsQuery(), filter, 1);
Assert.AreEqual(0, docs.TotalHits, "[query + filter] Should *not* find a hit...");
// cache hit
Assert.AreEqual(missCount, filter.MissCount);
docs = searcher.Search(constantScore, 1);
Assert.AreEqual(0, docs.TotalHits, "[just filter] Should *not* find a hit...");
// apply deletes dynamically:
filter = new CachingWrapperFilter(startFilter);
writer.AddDocument(doc);
reader = RefreshReader(reader);
searcher = NewSearcher(reader, false);
docs = searcher.Search(new MatchAllDocsQuery(), filter, 1);
Assert.AreEqual(1, docs.TotalHits, "[query + filter] Should find a hit...");
missCount = filter.MissCount;
Assert.IsTrue(missCount > 0);
constantScore = new ConstantScoreQuery(filter);
docs = searcher.Search(constantScore, 1);
Assert.AreEqual(1, docs.TotalHits, "[just filter] Should find a hit...");
Assert.AreEqual(missCount, filter.MissCount);
writer.AddDocument(doc);
// NOTE: important to hold ref here so GC doesn't clear
// the cache entry! Else the assert below may sometimes
// fail:
oldReader = reader;
reader = RefreshReader(reader);
searcher = NewSearcher(reader, false);
docs = searcher.Search(new MatchAllDocsQuery(), filter, 1);
Assert.AreEqual(2, docs.TotalHits, "[query + filter] Should find 2 hits...");
Assert.IsTrue(filter.MissCount > missCount);
missCount = filter.MissCount;
constantScore = new ConstantScoreQuery(filter);
docs = searcher.Search(constantScore, 1);
Assert.AreEqual(2, docs.TotalHits, "[just filter] Should find a hit...");
Assert.AreEqual(missCount, filter.MissCount);
// now delete the doc, refresh the reader, and see that it's not there
writer.DeleteDocuments(new Term("id", "1"));
reader = RefreshReader(reader);
searcher = NewSearcher(reader, false);
docs = searcher.Search(new MatchAllDocsQuery(), filter, 1);
Assert.AreEqual(0, docs.TotalHits, "[query + filter] Should *not* find a hit...");
// CWF reused the same entry (it dynamically applied the deletes):
Assert.AreEqual(missCount, filter.MissCount);
docs = searcher.Search(constantScore, 1);
Assert.AreEqual(0, docs.TotalHits, "[just filter] Should *not* find a hit...");
// CWF reused the same entry (it dynamically applied the deletes):
Assert.AreEqual(missCount, filter.MissCount);
// NOTE: silliness to make sure JRE does not eliminate
// our holding onto oldReader to prevent
// CachingWrapperFilter's WeakHashMap from dropping the
// entry:
Assert.IsTrue(oldReader != null);
reader.Dispose();
writer.Dispose();
dir.Dispose();
}
private static DirectoryReader RefreshReader(DirectoryReader reader)
{
DirectoryReader oldReader = reader;
reader = DirectoryReader.OpenIfChanged(reader);
if (reader != null)
{
oldReader.Dispose();
return reader;
}
else
{
return oldReader;
}
}
}
}
| |
// ****************************************************************
// Copyright 2009, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using System.Collections;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// Helper class with properties and methods that supply
/// a number of constraints used in Asserts.
/// </summary>
public class ConstraintFactory
{
#region Not
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression Not
{
get { return Is.Not; }
}
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression No
{
get { return Has.No; }
}
#endregion
#region All
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them succeed.
/// </summary>
public ConstraintExpression All
{
get { return Is.All; }
}
#endregion
#region Some
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if at least one of them succeeds.
/// </summary>
public ConstraintExpression Some
{
get { return Has.Some; }
}
#endregion
#region None
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them fail.
/// </summary>
public ConstraintExpression None
{
get { return Has.None; }
}
#endregion
#region Exactly(n)
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding only if a specified number of them succeed.
/// </summary>
public static ConstraintExpression Exactly(int expectedCount)
{
return Has.Exactly(expectedCount);
}
#endregion
#region Property
/// <summary>
/// Returns a new PropertyConstraintExpression, which will either
/// test for the existence of the named property on the object
/// being tested or apply any following constraint to that property.
/// </summary>
public ResolvableConstraintExpression Property(string name)
{
return Has.Property(name);
}
#endregion
#region Length
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Length property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Length
{
get { return Has.Length; }
}
#endregion
#region Count
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Count property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Count
{
get { return Has.Count; }
}
#endregion
#region Message
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Message property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Message
{
get { return Has.Message; }
}
#endregion
#region InnerException
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the InnerException property of the object being tested.
/// </summary>
public ResolvableConstraintExpression InnerException
{
get { return Has.InnerException; }
}
#endregion
#region Attribute
/// <summary>
/// Returns a new AttributeConstraint checking for the
/// presence of a particular attribute on an object.
/// </summary>
public ResolvableConstraintExpression Attribute(Type expectedType)
{
return Has.Attribute(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a new AttributeConstraint checking for the
/// presence of a particular attribute on an object.
/// </summary>
public ResolvableConstraintExpression Attribute<T>()
{
return Attribute(typeof(T));
}
#endif
#endregion
#region Null
/// <summary>
/// Returns a constraint that tests for null
/// </summary>
public NullConstraint Null
{
get { return new NullConstraint(); }
}
#endregion
#region True
/// <summary>
/// Returns a constraint that tests for True
/// </summary>
public TrueConstraint True
{
get { return new TrueConstraint(); }
}
#endregion
#region False
/// <summary>
/// Returns a constraint that tests for False
/// </summary>
public FalseConstraint False
{
get { return new FalseConstraint(); }
}
#endregion
#region Positive
/// <summary>
/// Returns a constraint that tests for a positive value
/// </summary>
public GreaterThanConstraint Positive
{
get { return new GreaterThanConstraint(0); }
}
#endregion
#region Negative
/// <summary>
/// Returns a constraint that tests for a negative value
/// </summary>
public LessThanConstraint Negative
{
get { return new LessThanConstraint(0); }
}
#endregion
#region NaN
/// <summary>
/// Returns a constraint that tests for NaN
/// </summary>
public NaNConstraint NaN
{
get { return new NaNConstraint(); }
}
#endregion
#region Empty
/// <summary>
/// Returns a constraint that tests for empty
/// </summary>
public EmptyConstraint Empty
{
get { return new EmptyConstraint(); }
}
#endregion
#region Unique
/// <summary>
/// Returns a constraint that tests whether a collection
/// contains all unique items.
/// </summary>
public UniqueItemsConstraint Unique
{
get { return new UniqueItemsConstraint(); }
}
#endregion
#region BinarySerializable
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in binary format.
/// </summary>
public BinarySerializableConstraint BinarySerializable
{
get { return new BinarySerializableConstraint(); }
}
#endregion
#region XmlSerializable
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in xml format.
/// </summary>
public XmlSerializableConstraint XmlSerializable
{
get { return new XmlSerializableConstraint(); }
}
#endregion
#region EqualTo
/// <summary>
/// Returns a constraint that tests two items for equality
/// </summary>
public EqualConstraint EqualTo(object expected)
{
return new EqualConstraint(expected);
}
#endregion
#region SameAs
/// <summary>
/// Returns a constraint that tests that two references are the same object
/// </summary>
public SameAsConstraint SameAs(object expected)
{
return new SameAsConstraint(expected);
}
#endregion
#region GreaterThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than the suppled argument
/// </summary>
public GreaterThanConstraint GreaterThan(object expected)
{
return new GreaterThanConstraint(expected);
}
#endregion
#region GreaterThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the suppled argument
/// </summary>
public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the suppled argument
/// </summary>
public GreaterThanOrEqualConstraint AtLeast(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
#endregion
#region LessThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than the suppled argument
/// </summary>
public LessThanConstraint LessThan(object expected)
{
return new LessThanConstraint(expected);
}
#endregion
#region LessThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the suppled argument
/// </summary>
public LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the suppled argument
/// </summary>
public LessThanOrEqualConstraint AtMost(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
#endregion
#region TypeOf
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public ExactTypeConstraint TypeOf(Type expectedType)
{
return new ExactTypeConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public ExactTypeConstraint TypeOf<T>()
{
return new ExactTypeConstraint(typeof(T));
}
#endif
#endregion
#region InstanceOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf<T>()
{
return new InstanceOfTypeConstraint(typeof(T));
}
#endif
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
[Obsolete("Use InstanceOf(expectedType)")]
public InstanceOfTypeConstraint InstanceOfType(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
[Obsolete("Use InstanceOf<T>()")]
public InstanceOfTypeConstraint InstanceOfType<T>()
{
return new InstanceOfTypeConstraint(typeof(T));
}
#endif
#endregion
#region AssignableFrom
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableFromConstraint AssignableFrom(Type expectedType)
{
return new AssignableFromConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableFromConstraint AssignableFrom<T>()
{
return new AssignableFromConstraint(typeof(T));
}
#endif
#endregion
#region AssignableTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableToConstraint AssignableTo(Type expectedType)
{
return new AssignableToConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableToConstraint AssignableTo<T>()
{
return new AssignableToConstraint(typeof(T));
}
#endif
#endregion
#region EquivalentTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a collection containing the same elements as the
/// collection supplied as an argument.
/// </summary>
public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
{
return new CollectionEquivalentConstraint(expected);
}
#endregion
#region SubsetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a subset of the collection supplied as an argument.
/// </summary>
public CollectionSubsetConstraint SubsetOf(IEnumerable expected)
{
return new CollectionSubsetConstraint(expected);
}
#endregion
#region Ordered
/// <summary>
/// Returns a constraint that tests whether a collection is ordered
/// </summary>
public CollectionOrderedConstraint Ordered
{
get { return new CollectionOrderedConstraint(); }
}
#endregion
#region Member
/// <summary>
/// Returns a new CollectionContainsConstraint checking for the
/// presence of a particular object in the collection.
/// </summary>
public CollectionContainsConstraint Member(object expected)
{
return new CollectionContainsConstraint(expected);
}
/// <summary>
/// Returns a new CollectionContainsConstraint checking for the
/// presence of a particular object in the collection.
/// </summary>
public CollectionContainsConstraint Contains(object expected)
{
return new CollectionContainsConstraint(expected);
}
#endregion
#region Contains
/// <summary>
/// Returns a new ContainsConstraint. This constraint
/// will, in turn, make use of the appropriate second-level
/// constraint, depending on the type of the actual argument.
/// This overload is only used if the item sought is a string,
/// since any other type implies that we are looking for a
/// collection member.
/// </summary>
public ContainsConstraint Contains(string expected)
{
return new ContainsConstraint(expected);
}
#endregion
#region StringContaining
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
public SubstringConstraint StringContaining(string expected)
{
return new SubstringConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
public SubstringConstraint ContainsSubstring(string expected)
{
return new SubstringConstraint(expected);
}
#endregion
#region DoesNotContain
/// <summary>
/// Returns a constraint that fails if the actual
/// value contains the substring supplied as an argument.
/// </summary>
public SubstringConstraint DoesNotContain(string expected)
{
return new ConstraintExpression().Not.ContainsSubstring(expected);
}
#endregion
#region StartsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StartsWith(string expected)
{
return new StartsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StringStarting(string expected)
{
return new StartsWithConstraint(expected);
}
#endregion
#region DoesNotStartWith
/// <summary>
/// Returns a constraint that fails if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint DoesNotStartWith(string expected)
{
return new ConstraintExpression().Not.StartsWith(expected);
}
#endregion
#region EndsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint EndsWith(string expected)
{
return new EndsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint StringEnding(string expected)
{
return new EndsWithConstraint(expected);
}
#endregion
#region DoesNotEndWith
/// <summary>
/// Returns a constraint that fails if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint DoesNotEndWith(string expected)
{
return new ConstraintExpression().Not.EndsWith(expected);
}
#endregion
#region Matches
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the Regex pattern supplied as an argument.
/// </summary>
public RegexConstraint Matches(string pattern)
{
return new RegexConstraint(pattern);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the Regex pattern supplied as an argument.
/// </summary>
public RegexConstraint StringMatching(string pattern)
{
return new RegexConstraint(pattern);
}
#endregion
#region DoesNotMatch
/// <summary>
/// Returns a constraint that fails if the actual
/// value matches the pattern supplied as an argument.
/// </summary>
public RegexConstraint DoesNotMatch(string pattern)
{
return new ConstraintExpression().Not.Matches(pattern);
}
#endregion
#region SamePath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same as an expected path after canonicalization.
/// </summary>
public SamePathConstraint SamePath(string expected)
{
return new SamePathConstraint(expected);
}
#endregion
#region SubPath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same path or under an expected path after canonicalization.
/// </summary>
public SubPathConstraint SubPath(string expected)
{
return new SubPathConstraint(expected);
}
#endregion
#region SamePathOrUnder
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same path or under an expected path after canonicalization.
/// </summary>
public SamePathOrUnderConstraint SamePathOrUnder(string expected)
{
return new SamePathOrUnderConstraint(expected);
}
#endregion
#region InRange
#if !CLR_2_0 && !CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// within a specified range.
/// </summary>
public RangeConstraint InRange(IComparable from, IComparable to)
{
return new RangeConstraint(from, to);
}
#endif
#endregion
#region InRange<T>
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// within a specified range.
/// </summary>
public RangeConstraint<T> InRange<T>(T from, T to) where T : IComparable<T>
{
return new RangeConstraint<T>(from, to);
}
#endif
#endregion
}
}
| |
using System;
using NUnit.Framework;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Crypto.Tests
{
internal class DHTestKeyParameters
: DHKeyParameters
{
public DHTestKeyParameters(
bool isPrivate,
DHParameters parameters)
: base(isPrivate, parameters)
{
}
}
internal class ElGamalTestKeyParameters
: ElGamalKeyParameters
{
public ElGamalTestKeyParameters(
bool isPrivate,
ElGamalParameters parameters)
: base(isPrivate, parameters)
{
}
}
[TestFixture]
public class EqualsHashCodeTest
: SimpleTest
{
private static object Other = new object();
public override string Name
{
get { return "EqualsHashCode"; }
}
private void doTest(
object a,
object equalsA,
object notEqualsA)
{
if (a.Equals(null))
{
Fail("a equaled null");
}
if (!a.Equals(equalsA) || !equalsA.Equals(a))
{
Fail("equality failed");
}
if (a.Equals(Other))
{
Fail("other inequality failed");
}
if (a.Equals(notEqualsA) || notEqualsA.Equals(a))
{
Fail("inequality failed");
}
if (a.GetHashCode() != equalsA.GetHashCode())
{
Fail("hashCode equality failed");
}
}
[Test]
public void TestDH()
{
BigInteger g512 = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
BigInteger p512 = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);
DHParameters dhParams = new DHParameters(p512, g512);
DHKeyGenerationParameters parameters = new DHKeyGenerationParameters(new SecureRandom(), dhParams); DHKeyPairGenerator kpGen = new DHKeyPairGenerator();
kpGen.Init(parameters);
AsymmetricCipherKeyPair pair = kpGen.GenerateKeyPair();
DHPublicKeyParameters pu1 = (DHPublicKeyParameters)pair.Public;
DHPrivateKeyParameters pv1 = (DHPrivateKeyParameters)pair.Private;
DHPublicKeyParameters pu2 = new DHPublicKeyParameters(pu1.Y, pu1.Parameters);
DHPrivateKeyParameters pv2 = new DHPrivateKeyParameters(pv1.X, pv1.Parameters);
DHPublicKeyParameters pu3 = new DHPublicKeyParameters(pv1.X, pu1.Parameters);
DHPrivateKeyParameters pv3 = new DHPrivateKeyParameters(pu1.Y, pu1.Parameters);
doTest(pu1, pu2, pu3);
doTest(pv1, pv2, pv3);
DHParameters pr1 = pu1.Parameters;
DHParameters pr2 = new DHParameters(
pr1.P, pr1.G, pr1.Q, pr1.M, pr1.L, pr1.J, pr1.ValidationParameters);
DHParameters pr3 = new DHParameters(
pr1.P.Add(BigInteger.Two), pr1.G, pr1.Q, pr1.M, pr1.L, pr1.J, pr1.ValidationParameters);
doTest(pr1, pr2, pr3);
pr3 = new DHParameters(
pr1.P, pr1.G.Add(BigInteger.One), pr1.Q, pr1.M, pr1.L, pr1.J, pr1.ValidationParameters);
doTest(pr1, pr2, pr3);
pu2 = new DHPublicKeyParameters(pu1.Y, pr2);
pv2 = new DHPrivateKeyParameters(pv1.X, pr2);
doTest(pu1, pu2, pu3);
doTest(pv1, pv2, pv3);
DHValidationParameters vp1 = new DHValidationParameters(new byte[20], 1024);
DHValidationParameters vp2 = new DHValidationParameters(new byte[20], 1024);
DHValidationParameters vp3 = new DHValidationParameters(new byte[24], 1024);
doTest(vp1, vp1, vp3);
doTest(vp1, vp2, vp3);
byte[] bytes = new byte[20];
bytes[0] = 1;
vp3 = new DHValidationParameters(bytes, 1024);
doTest(vp1, vp2, vp3);
vp3 = new DHValidationParameters(new byte[20], 2048);
doTest(vp1, vp2, vp3);
DHTestKeyParameters k1 = new DHTestKeyParameters(false, null);
DHTestKeyParameters k2 = new DHTestKeyParameters(false, null);
DHTestKeyParameters k3 = new DHTestKeyParameters(false, pu1.Parameters);
doTest(k1, k2, k3);
}
[Test]
public void TestElGamal()
{
BigInteger g512 = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
BigInteger p512 = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);
ElGamalParameters dhParams = new ElGamalParameters(p512, g512);
ElGamalKeyGenerationParameters parameters = new ElGamalKeyGenerationParameters(new SecureRandom(), dhParams); ElGamalKeyPairGenerator kpGen = new ElGamalKeyPairGenerator();
kpGen.Init(parameters);
AsymmetricCipherKeyPair pair = kpGen.GenerateKeyPair();
ElGamalPublicKeyParameters pu1 = (ElGamalPublicKeyParameters)pair.Public;
ElGamalPrivateKeyParameters pv1 = (ElGamalPrivateKeyParameters)pair.Private;
ElGamalPublicKeyParameters pu2 = new ElGamalPublicKeyParameters(pu1.Y, pu1.Parameters);
ElGamalPrivateKeyParameters pv2 = new ElGamalPrivateKeyParameters(pv1.X, pv1.Parameters);
ElGamalPublicKeyParameters pu3 = new ElGamalPublicKeyParameters(pv1.X, pu1.Parameters);
ElGamalPrivateKeyParameters pv3 = new ElGamalPrivateKeyParameters(pu1.Y, pu1.Parameters);
doTest(pu1, pu2, pu3);
doTest(pv1, pv2, pv3);
ElGamalParameters pr1 = pu1.Parameters;
ElGamalParameters pr2 = new ElGamalParameters(pr1.P, pr1.G);
ElGamalParameters pr3 = new ElGamalParameters(pr1.G, pr1.P);
doTest(pr1, pr2, pr3);
pu2 = new ElGamalPublicKeyParameters(pu1.Y, pr2);
pv2 = new ElGamalPrivateKeyParameters(pv1.X, pr2);
doTest(pu1, pu2, pu3);
doTest(pv1, pv2, pv3);
ElGamalTestKeyParameters k1 = new ElGamalTestKeyParameters(false, null);
ElGamalTestKeyParameters k2 = new ElGamalTestKeyParameters(false, null);
ElGamalTestKeyParameters k3 = new ElGamalTestKeyParameters(false, pu1.Parameters);
doTest(k1, k2, k3);
}
[Test]
public void TestDsa()
{
BigInteger a = BigInteger.ValueOf(1), b = BigInteger.ValueOf(2), c = BigInteger.ValueOf(3);
DsaParameters dsaP1 = new DsaParameters(a, b, c);
DsaParameters dsaP2 = new DsaParameters(a, b, c);
DsaParameters dsaP3 = new DsaParameters(b, c, a);
doTest(dsaP1, dsaP2, dsaP3);
DsaValidationParameters vp1 = new DsaValidationParameters(new byte[20], 1024);
DsaValidationParameters vp2 = new DsaValidationParameters(new byte[20], 1024);
DsaValidationParameters vp3 = new DsaValidationParameters(new byte[24], 1024);
doTest(vp1, vp1, vp3);
doTest(vp1, vp2, vp3);
byte[] bytes = new byte[20];
bytes[0] = 1;
vp3 = new DsaValidationParameters(bytes, 1024);
doTest(vp1, vp2, vp3);
vp3 = new DsaValidationParameters(new byte[20], 2048);
doTest(vp1, vp2, vp3);
}
[Test]
public void TestGost3410()
{
BigInteger a = BigInteger.ValueOf(1), b = BigInteger.ValueOf(2), c = BigInteger.ValueOf(3);
Gost3410Parameters g1 = new Gost3410Parameters(a, b, c);
Gost3410Parameters g2 = new Gost3410Parameters(a, b, c);
Gost3410Parameters g3 = new Gost3410Parameters(a, c, c);
doTest(g1, g2, g3);
Gost3410ValidationParameters v1 = new Gost3410ValidationParameters(100, 1);
Gost3410ValidationParameters v2 = new Gost3410ValidationParameters(100, 1);
Gost3410ValidationParameters v3 = new Gost3410ValidationParameters(101, 1);
doTest(v1, v2, v3);
v3 = new Gost3410ValidationParameters(100, 2);
doTest(v1, v2, v3);
v1 = new Gost3410ValidationParameters(100L, 1L);
v2 = new Gost3410ValidationParameters(100L, 1L);
v3 = new Gost3410ValidationParameters(101L, 1L);
doTest(v1, v2, v3);
v3 = new Gost3410ValidationParameters(100L, 2L);
doTest(v1, v2, v3);
}
public override void PerformTest()
{
TestDH();
TestElGamal();
TestGost3410();
TestDsa();
}
public static void Main(
string[] args)
{
RunTest(new EqualsHashCodeTest());
}
}
}
| |
// 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.
////////////////////////////////////////////////////////////////////////////
//
// DateTimeFormatInfoScanner
//
// Scan a specified DateTimeFormatInfo to search for data used in DateTime.Parse()
//
// The data includes:
//
// DateWords: such as "de" used in es-ES (Spanish) LongDatePattern.
// Postfix: such as "ta" used in fi-FI after the month name.
//
// This class is shared among mscorlib.dll and sysglobl.dll.
// Use conditional CULTURE_AND_REGIONINFO_BUILDER_ONLY to differentiate between
// methods for mscorlib.dll and sysglobl.dll.
//
////////////////////////////////////////////////////////////////////////////
using System.Collections.Generic;
using System.Text;
namespace System.Globalization
{
//
// from LocaleEx.txt header
//
//; IFORMATFLAGS
//; Parsing/formatting flags.
internal enum FORMATFLAGS
{
None = 0x00000000,
UseGenitiveMonth = 0x00000001,
UseLeapYearMonth = 0x00000002,
UseSpacesInMonthNames = 0x00000004,
UseHebrewParsing = 0x00000008,
UseSpacesInDayNames = 0x00000010, // Has spaces or non-breaking space in the day names.
UseDigitPrefixInTokens = 0x00000020, // Has token starting with numbers.
}
internal enum CalendarId : ushort
{
UNINITIALIZED_VALUE = 0,
GREGORIAN = 1, // Gregorian (localized) calendar
GREGORIAN_US = 2, // Gregorian (U.S.) calendar
JAPAN = 3, // Japanese Emperor Era calendar
/* SSS_WARNINGS_OFF */
TAIWAN = 4, // Taiwan Era calendar /* SSS_WARNINGS_ON */
KOREA = 5, // Korean Tangun Era calendar
HIJRI = 6, // Hijri (Arabic Lunar) calendar
THAI = 7, // Thai calendar
HEBREW = 8, // Hebrew (Lunar) calendar
GREGORIAN_ME_FRENCH = 9, // Gregorian Middle East French calendar
GREGORIAN_ARABIC = 10, // Gregorian Arabic calendar
GREGORIAN_XLIT_ENGLISH = 11, // Gregorian Transliterated English calendar
GREGORIAN_XLIT_FRENCH = 12,
// Note that all calendars after this point are MANAGED ONLY for now.
JULIAN = 13,
JAPANESELUNISOLAR = 14,
CHINESELUNISOLAR = 15,
SAKA = 16, // reserved to match Office but not implemented in our code
LUNAR_ETO_CHN = 17, // reserved to match Office but not implemented in our code
LUNAR_ETO_KOR = 18, // reserved to match Office but not implemented in our code
LUNAR_ETO_ROKUYOU = 19, // reserved to match Office but not implemented in our code
KOREANLUNISOLAR = 20,
TAIWANLUNISOLAR = 21,
PERSIAN = 22,
UMALQURA = 23,
LAST_CALENDAR = 23 // Last calendar ID
}
internal class DateTimeFormatInfoScanner
{
// Special prefix-like flag char in DateWord array.
// Use char in PUA area since we won't be using them in real data.
// The char used to tell a read date word or a month postfix. A month postfix
// is "ta" in the long date pattern like "d. MMMM'ta 'yyyy" for fi-FI.
// In this case, it will be stored as "\xfffeta" in the date word array.
internal const char MonthPostfixChar = '\xe000';
// Add ignorable symbol in a DateWord array.
// hu-HU has:
// shrot date pattern: yyyy. MM. dd.;yyyy-MM-dd;yy-MM-dd
// long date pattern: yyyy. MMMM d.
// Here, "." is the date separator (derived from short date pattern). However,
// "." also appear at the end of long date pattern. In this case, we just
// "." as ignorable symbol so that the DateTime.Parse() state machine will not
// treat the additional date separator at the end of y,m,d pattern as an error
// condition.
internal const char IgnorableSymbolChar = '\xe001';
// Known CJK suffix
internal const string CJKYearSuff = "\u5e74";
internal const string CJKMonthSuff = "\u6708";
internal const string CJKDaySuff = "\u65e5";
internal const string KoreanYearSuff = "\ub144";
internal const string KoreanMonthSuff = "\uc6d4";
internal const string KoreanDaySuff = "\uc77c";
internal const string KoreanHourSuff = "\uc2dc";
internal const string KoreanMinuteSuff = "\ubd84";
internal const string KoreanSecondSuff = "\ucd08";
internal const string CJKHourSuff = "\u6642";
internal const string ChineseHourSuff = "\u65f6";
internal const string CJKMinuteSuff = "\u5206";
internal const string CJKSecondSuff = "\u79d2";
// The collection fo date words & postfix.
internal List<string> m_dateWords = new List<string>();
// Hashtable for the known words.
private static volatile Dictionary<string, string> s_knownWords;
static Dictionary<string, string> KnownWords
{
get
{
if (s_knownWords == null)
{
Dictionary<string, string> temp = new Dictionary<string, string>();
// Add known words into the hash table.
// Skip these special symbols.
temp.Add("/", string.Empty);
temp.Add("-", string.Empty);
temp.Add(".", string.Empty);
// Skip known CJK suffixes.
temp.Add(CJKYearSuff, string.Empty);
temp.Add(CJKMonthSuff, string.Empty);
temp.Add(CJKDaySuff, string.Empty);
temp.Add(KoreanYearSuff, string.Empty);
temp.Add(KoreanMonthSuff, string.Empty);
temp.Add(KoreanDaySuff, string.Empty);
temp.Add(KoreanHourSuff, string.Empty);
temp.Add(KoreanMinuteSuff, string.Empty);
temp.Add(KoreanSecondSuff, string.Empty);
temp.Add(CJKHourSuff, string.Empty);
temp.Add(ChineseHourSuff, string.Empty);
temp.Add(CJKMinuteSuff, string.Empty);
temp.Add(CJKSecondSuff, string.Empty);
s_knownWords = temp;
}
return (s_knownWords);
}
}
////////////////////////////////////////////////////////////////////////////
//
// Parameters:
// pattern: The pattern to be scanned.
// currentIndex: the current index to start the scan.
//
// Returns:
// Return the index with the first character that is a letter, which will
// be the start of a date word.
// Note that the index can be pattern.Length if we reach the end of the string.
//
////////////////////////////////////////////////////////////////////////////
internal static int SkipWhiteSpacesAndNonLetter(string pattern, int currentIndex)
{
while (currentIndex < pattern.Length)
{
char ch = pattern[currentIndex];
if (ch == '\\')
{
// Escaped character. Look ahead one character.
currentIndex++;
if (currentIndex < pattern.Length)
{
ch = pattern[currentIndex];
if (ch == '\'')
{
// Skip the leading single quote. We will
// stop at the first letter.
continue;
}
// Fall thru to check if this is a letter.
}
else
{
// End of string
break;
}
}
if (char.IsLetter(ch) || ch == '\'' || ch == '.')
{
break;
}
// Skip the current char since it is not a letter.
currentIndex++;
}
return (currentIndex);
}
////////////////////////////////////////////////////////////////////////////
//
// A helper to add the found date word or month postfix into ArrayList for date words.
//
// Parameters:
// formatPostfix: What kind of postfix this is.
// Possible values:
// null: This is a regular date word
// "MMMM": month postfix
// word: The date word or postfix to be added.
//
////////////////////////////////////////////////////////////////////////////
internal void AddDateWordOrPostfix(string formatPostfix, string str)
{
if (str.Length > 0)
{
// Some cultures use . like an abbreviation
if (str.Equals("."))
{
AddIgnorableSymbols(".");
return;
}
string words;
if (KnownWords.TryGetValue(str, out words) == false)
{
if (m_dateWords == null)
{
m_dateWords = new List<string>();
}
if (formatPostfix == "MMMM")
{
// Add the word into the ArrayList as "\xfffe" + real month postfix.
string temp = MonthPostfixChar + str;
if (!m_dateWords.Contains(temp))
{
m_dateWords.Add(temp);
}
}
else
{
if (!m_dateWords.Contains(str))
{
m_dateWords.Add(str);
}
if (str[str.Length - 1] == '.')
{
// Old version ignore the trialing dot in the date words. Support this as well.
string strWithoutDot = str.Substring(0, str.Length - 1);
if (!m_dateWords.Contains(strWithoutDot))
{
m_dateWords.Add(strWithoutDot);
}
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the pattern from the specified index and add the date word/postfix
// when appropriate.
//
// Parameters:
// pattern: The pattern to be scanned.
// index: The starting index to be scanned.
// formatPostfix: The kind of postfix to be scanned.
// Possible values:
// null: This is a regular date word
// "MMMM": month postfix
//
//
////////////////////////////////////////////////////////////////////////////
internal int AddDateWords(string pattern, int index, string formatPostfix)
{
// Skip any whitespaces so we will start from a letter.
int newIndex = SkipWhiteSpacesAndNonLetter(pattern, index);
if (newIndex != index && formatPostfix != null)
{
// There are whitespaces. This will not be a postfix.
formatPostfix = null;
}
index = newIndex;
// This is the first char added into dateWord.
// Skip all non-letter character. We will add the first letter into DateWord.
StringBuilder dateWord = new StringBuilder();
// We assume that date words should start with a letter.
// Skip anything until we see a letter.
while (index < pattern.Length)
{
char ch = pattern[index];
if (ch == '\'')
{
// We have seen the end of quote. Add the word if we do not see it before,
// and break the while loop.
AddDateWordOrPostfix(formatPostfix, dateWord.ToString());
index++;
break;
}
else if (ch == '\\')
{
//
// Escaped character. Look ahead one character
//
// Skip escaped backslash.
index++;
if (index < pattern.Length)
{
dateWord.Append(pattern[index]);
index++;
}
}
else if (char.IsWhiteSpace(ch))
{
// Found a whitespace. We have to add the current date word/postfix.
AddDateWordOrPostfix(formatPostfix, dateWord.ToString());
if (formatPostfix != null)
{
// Done with postfix. The rest will be regular date word.
formatPostfix = null;
}
// Reset the dateWord.
dateWord.Length = 0;
index++;
}
else
{
dateWord.Append(ch);
index++;
}
}
return (index);
}
////////////////////////////////////////////////////////////////////////////
//
// A simple helper to find the repeat count for a specified char.
//
////////////////////////////////////////////////////////////////////////////
internal static int ScanRepeatChar(string pattern, char ch, int index, out int count)
{
count = 1;
while (++index < pattern.Length && pattern[index] == ch)
{
count++;
}
// Return the updated position.
return (index);
}
////////////////////////////////////////////////////////////////////////////
//
// Add the text that is a date separator but is treated like ignroable symbol.
// E.g.
// hu-HU has:
// shrot date pattern: yyyy. MM. dd.;yyyy-MM-dd;yy-MM-dd
// long date pattern: yyyy. MMMM d.
// Here, "." is the date separator (derived from short date pattern). However,
// "." also appear at the end of long date pattern. In this case, we just
// "." as ignorable symbol so that the DateTime.Parse() state machine will not
// treat the additional date separator at the end of y,m,d pattern as an error
// condition.
//
////////////////////////////////////////////////////////////////////////////
internal void AddIgnorableSymbols(string text)
{
if (m_dateWords == null)
{
// Create the date word array.
m_dateWords = new List<string>();
}
// Add the ignorable symbol into the ArrayList.
string temp = IgnorableSymbolChar + text;
if (!m_dateWords.Contains(temp))
{
m_dateWords.Add(temp);
}
}
//
// Flag used to trace the date patterns (yy/yyyyy/M/MM/MMM/MMM/d/dd) that we have seen.
//
private enum FoundDatePattern
{
None = 0x0000,
FoundYearPatternFlag = 0x0001,
FoundMonthPatternFlag = 0x0002,
FoundDayPatternFlag = 0x0004,
FoundYMDPatternFlag = 0x0007, // FoundYearPatternFlag | FoundMonthPatternFlag | FoundDayPatternFlag;
}
// Check if we have found all of the year/month/day pattern.
private FoundDatePattern _ymdFlags = FoundDatePattern.None;
////////////////////////////////////////////////////////////////////////////
//
// Given a date format pattern, scan for date word or postfix.
//
// A date word should be always put in a single quoted string. And it will
// start from a letter, so whitespace and symbols will be ignored before
// the first letter.
//
// Examples of date word:
// 'de' in es-SP: dddd, dd' de 'MMMM' de 'yyyy
// "\x0443." in bg-BG: dd.M.yyyy '\x0433.'
//
// Example of postfix:
// month postfix:
// "ta" in fi-FI: d. MMMM'ta 'yyyy
// Currently, only month postfix is supported.
//
// Usage:
// Always call this with Framework-style pattern, instead of Windows style pattern.
// Windows style pattern uses '' for single quote, while .NET uses \'
//
////////////////////////////////////////////////////////////////////////////
internal void ScanDateWord(string pattern)
{
// Check if we have found all of the year/month/day pattern.
_ymdFlags = FoundDatePattern.None;
int i = 0;
while (i < pattern.Length)
{
char ch = pattern[i];
int chCount;
switch (ch)
{
case '\'':
// Find a beginning quote. Search until the end quote.
i = AddDateWords(pattern, i + 1, null);
break;
case 'M':
i = ScanRepeatChar(pattern, 'M', i, out chCount);
if (chCount >= 4)
{
if (i < pattern.Length && pattern[i] == '\'')
{
i = AddDateWords(pattern, i + 1, "MMMM");
}
}
_ymdFlags |= FoundDatePattern.FoundMonthPatternFlag;
break;
case 'y':
i = ScanRepeatChar(pattern, 'y', i, out chCount);
_ymdFlags |= FoundDatePattern.FoundYearPatternFlag;
break;
case 'd':
i = ScanRepeatChar(pattern, 'd', i, out chCount);
if (chCount <= 2)
{
// Only count "d" & "dd".
// ddd, dddd are day names. Do not count them.
_ymdFlags |= FoundDatePattern.FoundDayPatternFlag;
}
break;
case '\\':
// Found a escaped char not in a quoted string. Skip the current backslash
// and its next character.
i += 2;
break;
case '.':
if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag)
{
// If we find a dot immediately after the we have seen all of the y, m, d pattern.
// treat it as a ignroable symbol. Check for comments in AddIgnorableSymbols for
// more details.
AddIgnorableSymbols(".");
_ymdFlags = FoundDatePattern.None;
}
i++;
break;
default:
if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag && !char.IsWhiteSpace(ch))
{
// We are not seeing "." after YMD. Clear the flag.
_ymdFlags = FoundDatePattern.None;
}
// We are not in quote. Skip the current character.
i++;
break;
}
}
}
////////////////////////////////////////////////////////////////////////////
//
// Given a DTFI, get all of the date words from date patterns and time patterns.
//
////////////////////////////////////////////////////////////////////////////
internal string[] GetDateWordsOfDTFI(DateTimeFormatInfo dtfi)
{
// Enumarate all LongDatePatterns, and get the DateWords and scan for month postfix.
string[] datePatterns = dtfi.GetAllDateTimePatterns('D');
int i;
// Scan the long date patterns
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the short date patterns
datePatterns = dtfi.GetAllDateTimePatterns('d');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the YearMonth patterns.
datePatterns = dtfi.GetAllDateTimePatterns('y');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the month/day pattern
ScanDateWord(dtfi.MonthDayPattern);
// Scan the long time patterns.
datePatterns = dtfi.GetAllDateTimePatterns('T');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the short time patterns.
datePatterns = dtfi.GetAllDateTimePatterns('t');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
string[] result = null;
if (m_dateWords != null && m_dateWords.Count > 0)
{
result = new string[m_dateWords.Count];
for (i = 0; i < m_dateWords.Count; i++)
{
result[i] = m_dateWords[i];
}
}
return (result);
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the month names to see if genitive month names are used, and return
// the format flag.
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagGenitiveMonth(string[] monthNames, string[] genitveMonthNames, string[] abbrevMonthNames, string[] genetiveAbbrevMonthNames)
{
// If we have different names in regular and genitive month names, use genitive month flag.
return ((!EqualStringArrays(monthNames, genitveMonthNames) || !EqualStringArrays(abbrevMonthNames, genetiveAbbrevMonthNames))
? FORMATFLAGS.UseGenitiveMonth : 0);
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the month names to see if spaces are used or start with a digit, and return the format flag
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagUseSpaceInMonthNames(string[] monthNames, string[] genitveMonthNames, string[] abbrevMonthNames, string[] genetiveAbbrevMonthNames)
{
FORMATFLAGS formatFlags = 0;
formatFlags |= (ArrayElementsBeginWithDigit(monthNames) ||
ArrayElementsBeginWithDigit(genitveMonthNames) ||
ArrayElementsBeginWithDigit(abbrevMonthNames) ||
ArrayElementsBeginWithDigit(genetiveAbbrevMonthNames)
? FORMATFLAGS.UseDigitPrefixInTokens : 0);
formatFlags |= (ArrayElementsHaveSpace(monthNames) ||
ArrayElementsHaveSpace(genitveMonthNames) ||
ArrayElementsHaveSpace(abbrevMonthNames) ||
ArrayElementsHaveSpace(genetiveAbbrevMonthNames)
? FORMATFLAGS.UseSpacesInMonthNames : 0);
return (formatFlags);
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the day names and set the correct format flag.
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagUseSpaceInDayNames(string[] dayNames, string[] abbrevDayNames)
{
return ((ArrayElementsHaveSpace(dayNames) ||
ArrayElementsHaveSpace(abbrevDayNames))
? FORMATFLAGS.UseSpacesInDayNames : 0);
}
////////////////////////////////////////////////////////////////////////////
//
// Check the calendar to see if it is HebrewCalendar and set the Hebrew format flag if necessary.
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagUseHebrewCalendar(int calID)
{
return (calID == (int)CalendarId.HEBREW ?
FORMATFLAGS.UseHebrewParsing | FORMATFLAGS.UseLeapYearMonth : 0);
}
//-----------------------------------------------------------------------------
// EqualStringArrays
// compares two string arrays and return true if all elements of the first
// array equals to all elmentsof the second array.
// otherwise it returns false.
//-----------------------------------------------------------------------------
private static bool EqualStringArrays(string[] array1, string[] array2)
{
// Shortcut if they're the same array
if (array1 == array2)
{
return true;
}
// This is effectively impossible
if (array1.Length != array2.Length)
{
return false;
}
// Check each string
for (int i = 0; i < array1.Length; i++)
{
if (!array1[i].Equals(array2[i]))
{
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
// ArrayElementsHaveSpace
// It checks all input array elements if any of them has space character
// returns true if found space character in one of the array elements.
// otherwise returns false.
//-----------------------------------------------------------------------------
private static bool ArrayElementsHaveSpace(string[] array)
{
for (int i = 0; i < array.Length; i++)
{
// it is faster to check for space character manually instead of calling IndexOf
// so we don't have to go to native code side.
for (int j = 0; j < array[i].Length; j++)
{
if (char.IsWhiteSpace(array[i][j]))
{
return true;
}
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////
//
// Check if any element of the array start with a digit.
//
////////////////////////////////////////////////////////////////////////////
private static bool ArrayElementsBeginWithDigit(string[] array)
{
for (int i = 0; i < array.Length; i++)
{
// it is faster to check for space character manually instead of calling IndexOf
// so we don't have to go to native code side.
if (array[i].Length > 0 &&
array[i][0] >= '0' && array[i][0] <= '9')
{
int index = 1;
while (index < array[i].Length && array[i][index] >= '0' && array[i][index] <= '9')
{
// Skip other digits.
index++;
}
if (index == array[i].Length)
{
return (false);
}
if (index == array[i].Length - 1)
{
// Skip known CJK month suffix.
// CJK uses month name like "1\x6708", since \x6708 is a known month suffix,
// we don't need the UseDigitPrefixInTokens since it is slower.
switch (array[i][index])
{
case '\x6708': // CJKMonthSuff
case '\xc6d4': // KoreanMonthSuff
return (false);
}
}
if (index == array[i].Length - 4)
{
// Skip known CJK month suffix.
// Starting with Windows 8, the CJK months for some cultures looks like: "1' \x6708'"
// instead of just "1\x6708"
if (array[i][index] == '\'' && array[i][index + 1] == ' ' &&
array[i][index + 2] == '\x6708' && array[i][index + 3] == '\'')
{
return (false);
}
}
return (true);
}
}
return false;
}
}
}
| |
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SuperSocket.Channel;
using SuperSocket.Client;
using SuperSocket.ProtoBase;
namespace SuperSocket.Client.Proxy
{
/// <summary>
/// https://tools.ietf.org/html/rfc1928
/// https://en.wikipedia.org/wiki/SOCKS
/// </summary>
public class Socks5Connector : ProxyConnectorBase
{
private string _username;
private string _password;
readonly static byte[] _authenHandshakeRequest = new byte[] { 0x05, 0x02, 0x00, 0x02 };
public Socks5Connector(EndPoint proxyEndPoint)
: base(proxyEndPoint)
{
}
public Socks5Connector(EndPoint proxyEndPoint, string username, string password)
: this(proxyEndPoint)
{
_username = username;
_password = password;
}
protected override async ValueTask<ConnectState> ConnectProxyAsync(EndPoint remoteEndPoint, ConnectState state, CancellationToken cancellationToken)
{
var channel = state.CreateChannel<Socks5Pack>(new Socks5AuthPipelineFilter(), new ChannelOptions { ReadAsDemand = true });
channel.Start();
var packStream = channel.GetPackageStream();
await channel.SendAsync(_authenHandshakeRequest);
var response = await packStream.ReceiveAsync();
if (!HandleResponse(response, Socket5ResponseType.Handshake, out string errorMessage))
{
await channel.CloseAsync(CloseReason.ProtocolError);
return new ConnectState
{
Result = false,
Exception = new Exception(errorMessage)
};
}
if (response.Status == 0x02)// need pass auth
{
var passAuthenRequest = GetPassAuthenBytes();
await channel.SendAsync(passAuthenRequest);
response = await packStream.ReceiveAsync();
if (!HandleResponse(response, Socket5ResponseType.AuthUserName, out errorMessage))
{
await channel.CloseAsync(CloseReason.ProtocolError);
return new ConnectState
{
Result = false,
Exception = new Exception(errorMessage)
};
}
}
var endPointRequest = GetEndPointBytes(remoteEndPoint);
await channel.SendAsync(endPointRequest);
response = await packStream.ReceiveAsync();
if (!HandleResponse(response, Socket5ResponseType.AuthEndPoint, out errorMessage))
{
await channel.CloseAsync(CloseReason.ProtocolError);
return new ConnectState
{
Result = false,
Exception = new Exception(errorMessage)
};
}
await channel.DetachAsync();
return state;
}
private bool HandleResponse(Socks5Pack response, Socket5ResponseType responseType, out string errorMessage)
{
errorMessage = null;
if (responseType == Socket5ResponseType.Handshake)
{
if (response.Status != 0x00 && response.Status != 0x02)
{
errorMessage = $"failed to connect to proxy , protocol violation";
return false;
}
}
else if (responseType == Socket5ResponseType.AuthUserName)
{
if (response.Status != 0x00)
{
errorMessage = $"failed to connect to proxy , username/password combination rejected";
return false;
}
}
else
{
if (response.Status != 0x00)
{
switch (response.Status)
{
case (0x02):
errorMessage = "connection not allowed by ruleset";
break;
case (0x03):
errorMessage = "network unreachable";
break;
case (0x04):
errorMessage = "host unreachable";
break;
case (0x05):
errorMessage = "connection refused by destination host";
break;
case (0x06):
errorMessage = "TTL expired";
break;
case (0x07):
errorMessage = "command not supported / protocol error";
break;
case (0x08):
errorMessage = "address type not supported";
break;
default:
errorMessage = "general failure";
break;
}
errorMessage = $"failed to connect to proxy , { errorMessage }";
return false;
}
}
return true;
}
private ArraySegment<byte> GetPassAuthenBytes()
{
var buffer = new byte[3 + Encoding.ASCII.GetMaxByteCount(_username.Length) + (string.IsNullOrEmpty(_password) ? 0 : Encoding.ASCII.GetMaxByteCount(_password.Length))];
var actualLength = 0;
buffer[0] = 0x01;
var len = Encoding.ASCII.GetBytes(_username, 0, _username.Length, buffer, 2);
buffer[1] = (byte)len;
actualLength = len + 2;
if (!string.IsNullOrEmpty(_password))
{
len = Encoding.ASCII.GetBytes(_password, 0, _password.Length, buffer, actualLength + 1);
buffer[actualLength] = (byte)len;
actualLength += len + 1;
}
else
{
buffer[actualLength] = 0x00;
actualLength++;
}
return new ArraySegment<byte>(buffer, 0, actualLength);
}
private byte[] GetEndPointBytes(EndPoint remoteEndPoint)
{
var targetEndPoint = remoteEndPoint;
byte[] buffer;
int actualLength;
int port = 0;
if (targetEndPoint is IPEndPoint)
{
var endPoint = targetEndPoint as IPEndPoint;
port = endPoint.Port;
if (endPoint.AddressFamily == AddressFamily.InterNetwork)
{
buffer = new byte[10];
buffer[3] = 0x01;
endPoint.Address.TryWriteBytes(buffer.AsSpan().Slice(4), out var bytesWritten);
}
else if (endPoint.AddressFamily == AddressFamily.InterNetworkV6)
{
buffer = new byte[22];
buffer[3] = 0x04;
endPoint.Address.TryWriteBytes(buffer.AsSpan().Slice(4), out var bytesWritten);
}
else
{
throw new Exception("unknown address family");
}
actualLength = buffer.Length;
}
else
{
var endPoint = targetEndPoint as DnsEndPoint;
port = endPoint.Port;
var maxLen = 7 + Encoding.ASCII.GetMaxByteCount(endPoint.Host.Length);
buffer = new byte[maxLen];
buffer[3] = 0x03;
buffer[4] = (byte)endPoint.Host.Length;
actualLength = 5;
actualLength += Encoding.ASCII.GetBytes(endPoint.Host, 0, endPoint.Host.Length, buffer, actualLength);
actualLength += 2;
}
buffer[0] = 0x05;
buffer[1] = 0x01;
buffer[2] = 0x00;
buffer[actualLength - 2] = (byte)(port / 256);
buffer[actualLength - 1] = (byte)(port % 256);
return buffer;
}
enum Socket5ResponseType
{
Handshake,
AuthUserName,
AuthEndPoint,
}
public class Socks5Address
{
public IPAddress IPAddress { get; set; }
public string DomainName { get; set; }
}
public class Socks5Pack
{
public byte Version { get; set; }
public byte Status { get; set; }
public byte Reserve { get; set; }
public Socks5Address DestAddr { get; set; }
public short DestPort { get; set; }
}
public class Socks5AuthPipelineFilter : FixedSizePipelineFilter<Socks5Pack>
{
public int AuthStep { get; set; }
public Socks5AuthPipelineFilter()
: base(2)
{
}
protected override Socks5Pack DecodePackage(ref ReadOnlySequence<byte> buffer)
{
var reader = new SequenceReader<byte>(buffer);
reader.TryRead(out byte version);
reader.TryRead(out byte status);
if (AuthStep == 0)
NextFilter = new Socks5AuthPipelineFilter { AuthStep = 1 };
else
NextFilter = new Socks5AddressPipelineFilter();
return new Socks5Pack
{
Version = version,
Status = status
};
}
}
public class Socks5AddressPipelineFilter : FixedHeaderPipelineFilter<Socks5Pack>
{
public Socks5AddressPipelineFilter()
: base(5)
{
}
protected override int GetBodyLengthFromHeader(ref ReadOnlySequence<byte> buffer)
{
var reader = new SequenceReader<byte>(buffer);
reader.Advance(3);
reader.TryRead(out byte addressType);
if (addressType == 0x01)
return 6 - 1;
if (addressType == 0x04)
return 18 - 1;
if (addressType == 0x03)
{
reader.TryRead(out byte domainLen);
return domainLen + 2;
}
throw new Exception($"Unsupported addressType: {addressType}");
}
protected override Socks5Pack DecodePackage(ref ReadOnlySequence<byte> buffer)
{
var reader = new SequenceReader<byte>(buffer);
reader.TryRead(out byte version);
reader.TryRead(out byte status);
reader.TryRead(out byte reserve);
reader.TryRead(out byte addressType);
var address = new Socks5Address();
if (addressType == 0x01)
{
var addrLen = 4;
address.IPAddress = new IPAddress(reader.Sequence.Slice(reader.Consumed, addrLen).ToArray());
reader.Advance(addrLen);
}
else if (addressType == 0x04)
{
var addrLen = 16;
address.IPAddress = new IPAddress(reader.Sequence.Slice(reader.Consumed, addrLen).ToArray());
reader.Advance(addrLen);
}
else if (addressType == 0x03)
{
reader.TryRead(out byte addrLen);
var seq = reader.Sequence.Slice(reader.Consumed, addrLen);
address.DomainName = seq.GetString(Encoding.ASCII);
reader.Advance(addrLen);
}
else
{
throw new Exception($"Unsupported addressType: {addressType}");
}
reader.TryReadBigEndian(out short port);
return new Socks5Pack
{
Version = version,
Status = status,
Reserve = reserve,
DestAddr = address,
DestPort = port
};
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using Cetera.IO;
namespace Cetera.Image
{
public enum Format : byte
{
RGBA8888, RGB888,
RGBA5551, RGB565, RGBA4444,
LA88, HL88, L8, A8, LA44,
L4, A4, ETC1, ETC1A4
}
public enum Orientation : byte
{
Default,
TransposeTile = 1,
Rotate90 = 4,
Transpose = 8
}
public class ImageSettings
{
public int Width { get; set; }
public int Height { get; set; }
public Format Format { get; set; }
public Orientation Orientation { get; set; } = Orientation.Default;
public bool PadToPowerOf2 { get; set; } = true;
/// <summary>
/// This is currently a hack
/// </summary>
public void SetFormat<T>(T originalFormat) where T : struct, IConvertible
{
Format = ConvertFormat(originalFormat);
}
public static Format ConvertFormat<T>(T originalFormat) where T : struct, IConvertible
{
return (Format)Enum.Parse(typeof(Format), originalFormat.ToString());
}
}
public class Common
{
static int Clamp(int value, int min, int max) => Math.Min(Math.Max(value, min), max - 1);
static IEnumerable<Color> GetColorsFromTexture(byte[] tex, Format format)
{
using (var br = new BinaryReaderX(new MemoryStream(tex)))
{
var etc1decoder = new ETC1.Decoder();
while (true)
{
int a = 255, r = 255, g = 255, b = 255;
switch (format)
{
case Format.L8:
b = g = r = br.ReadByte();
break;
case Format.A8:
a = br.ReadByte();
break;
case Format.LA44:
a = br.ReadNibble() * 17;
b = g = r = br.ReadNibble() * 17;
break;
case Format.LA88:
a = br.ReadByte();
b = g = r = br.ReadByte();
break;
case Format.HL88:
g = br.ReadByte();
r = br.ReadByte();
break;
case Format.RGB565:
var s = br.ReadUInt16();
b = (s % 32) * 33 / 4;
g = (s >> 5) % 64 * 65 / 16;
r = (s >> 11) * 33 / 4;
break;
case Format.RGB888:
b = br.ReadByte();
g = br.ReadByte();
r = br.ReadByte();
break;
case Format.RGBA5551:
var s2 = br.ReadUInt16();
a = (s2 & 1) * 255;
b = (s2 >> 1) % 32 * 33 / 4;
g = (s2 >> 6) % 32 * 33 / 4;
r = (s2 >> 11) % 32 * 33 / 4;
break;
case Format.RGBA4444:
a = br.ReadNibble() * 17;
b = br.ReadNibble() * 17;
g = br.ReadNibble() * 17;
r = br.ReadNibble() * 17;
break;
case Format.RGBA8888:
a = br.ReadByte();
b = br.ReadByte();
g = br.ReadByte();
r = br.ReadByte();
break;
case Format.ETC1:
case Format.ETC1A4:
yield return etc1decoder.Get(() =>
{
var alpha = (format == Format.ETC1A4) ? br.ReadUInt64() : ulong.MaxValue;
return new ETC1.PixelData { Alpha = alpha, Block = br.ReadStruct<ETC1.Block>() };
});
continue;
case Format.L4:
b = g = r = br.ReadNibble() * 17;
break;
case Format.A4:
a = br.ReadNibble() * 17;
break;
default:
throw new NotSupportedException($"Unknown image format {format}");
}
yield return Color.FromArgb(a, r, g, b);
}
}
}
static IEnumerable<Point> GetPointSequence(ImageSettings settings)
{
int strideWidth = (settings.Width + 7) & ~7;
int strideHeight = (settings.Height + 7) & ~7;
if (settings.PadToPowerOf2)
{
strideWidth = 2 << (int)Math.Log(strideWidth - 1, 2);
strideHeight = 2 << (int)Math.Log(strideHeight - 1, 2);
}
int stride = (int)settings.Orientation < 4 ? strideWidth : strideHeight;
for (int i = 0; i < strideWidth * strideHeight; i++)
{
int x_out = (i / 64 % (stride / 8)) * 8;
int y_out = (i / 64 / (stride / 8)) * 8;
int x_in = (i / 4 & 4) | (i / 2 & 2) | (i & 1);
int y_in = (i / 8 & 4) | (i / 4 & 2) | (i / 2 & 1);
switch (settings.Orientation)
{
case Orientation.Default:
yield return new Point(x_out + x_in, y_out + y_in);
break;
case Orientation.TransposeTile:
yield return new Point(x_out + y_in, y_out + x_in);
break;
case Orientation.Rotate90:
yield return new Point(y_out + y_in, stride - 1 - (x_out + x_in));
break;
case Orientation.Transpose:
yield return new Point(y_out + y_in, x_out + x_in);
break;
default:
throw new NotSupportedException($"Unknown orientation format {settings.Orientation}");
}
}
}
public static Bitmap Load(byte[] tex, ImageSettings settings)
{
int width = settings.Width, height = settings.Height;
var colors = GetColorsFromTexture(tex, settings.Format);
var points = GetPointSequence(settings);
// Now we just need to merge the points with the colors
var bmp = new Bitmap(width, height);
var data = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
unsafe
{
var ptr = (int*)data.Scan0;
foreach (var pair in points.Zip(colors, Tuple.Create))
{
int x = pair.Item1.X, y = pair.Item1.Y;
if (0 <= x && x < width && 0 <= y && y < height)
{
ptr[data.Stride * y / 4 + x] = pair.Item2.ToArgb();
}
}
}
bmp.UnlockBits(data);
return bmp;
}
public static byte[] Save(Bitmap bmp, ImageSettings settings)
{
settings.Width = bmp.Width;
settings.Height = bmp.Height;
var points = GetPointSequence(settings);
var ms = new MemoryStream();
var etc1encoder = new ETC1.Encoder();
using (var bw = new BinaryWriterX(ms))
{
foreach (var point in points)
{
int x = Clamp(point.X, 0, bmp.Width);
int y = Clamp(point.Y, 0, bmp.Height);
var color = bmp.GetPixel(x, y);
//if (color.A == 0) color = default(Color); // daigasso seems to need this
switch (settings.Format)
{
case Format.L8:
bw.Write(color.G);
break;
case Format.A8:
bw.Write(color.A);
break;
case Format.LA44:
bw.WriteNibble(color.A / 16);
bw.WriteNibble(color.G / 16);
break;
case Format.LA88:
bw.Write(color.A);
bw.Write(color.G);
break;
case Format.HL88:
bw.Write(color.G);
bw.Write(color.R);
break;
case Format.RGB565:
bw.Write((short)((color.R / 8 << 11) | (color.G / 4 << 5) | (color.B / 8)));
break;
case Format.RGB888:
bw.Write(color.B);
bw.Write(color.G);
bw.Write(color.R);
break;
case Format.RGBA5551:
bw.Write((short)((color.R / 8 << 11) | (color.G / 8 << 6) | (color.B / 8 << 1) | color.A / 128));
break;
case Format.RGBA4444:
bw.WriteNibble(color.A / 16);
bw.WriteNibble(color.B / 16);
bw.WriteNibble(color.G / 16);
bw.WriteNibble(color.R / 16);
break;
case Format.RGBA8888:
bw.Write(color.A);
bw.Write(color.B);
bw.Write(color.G);
bw.Write(color.R);
break;
case Format.ETC1:
case Format.ETC1A4:
etc1encoder.Set(color, data =>
{
if (settings.Format == Format.ETC1A4) bw.Write(data.Alpha);
bw.WriteStruct(data.Block);
});
break;
case Format.L4:
bw.WriteNibble(color.G / 16);
break;
case Format.A4:
bw.WriteNibble(color.A / 16);
break;
default:
throw new NotSupportedException();
}
}
}
return ms.ToArray();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
using System;
using System.Data;
using System.Threading.Tasks;
using System.Threading;
namespace System.Data.Common
{
public abstract class DbCommand : IDbCommand,
IDisposable
{
protected DbCommand() : base()
{
}
~DbCommand()
{
Dispose(disposing: false);
}
abstract public string CommandText
{
get;
set;
}
abstract public int CommandTimeout
{
get;
set;
}
abstract public CommandType CommandType
{
get;
set;
}
public DbConnection Connection
{
get
{
return DbConnection;
}
set
{
DbConnection = value;
}
}
abstract protected DbConnection DbConnection
{
get;
set;
}
abstract protected DbParameterCollection DbParameterCollection
{
get;
}
abstract protected DbTransaction DbTransaction
{
get;
set;
}
public abstract bool DesignTimeVisible
{
get;
set;
}
public DbParameterCollection Parameters
{
get
{
return DbParameterCollection;
}
}
public DbTransaction Transaction
{
get
{
return DbTransaction;
}
set
{
DbTransaction = value;
}
}
abstract public UpdateRowSource UpdatedRowSource
{
get;
set;
}
IDbConnection IDbCommand.Connection
{
get
{
return DbConnection;
}
set
{
DbConnection = (DbConnection)value;
}
}
IDbTransaction IDbCommand.Transaction
{
get
{
return DbTransaction;
}
set
{
DbTransaction = (DbTransaction)value;
}
}
IDataParameterCollection IDbCommand.Parameters
{
get
{
return (DbParameterCollection)DbParameterCollection;
}
}
internal void CancelIgnoreFailure()
{
// This method is used to route CancellationTokens to the Cancel method.
// Cancellation is a suggestion, and exceptions should be ignored
// rather than allowed to be unhandled, as the exceptions cannot be
// routed to the caller. These errors will be observed in the regular
// method instead.
try
{
Cancel();
}
catch (Exception)
{
}
}
abstract public void Cancel();
public DbParameter CreateParameter()
{
return CreateDbParameter();
}
abstract protected DbParameter CreateDbParameter();
abstract protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior);
abstract public int ExecuteNonQuery();
public DbDataReader ExecuteReader()
{
return (DbDataReader)ExecuteDbDataReader(CommandBehavior.Default);
}
public DbDataReader ExecuteReader(CommandBehavior behavior)
{
return (DbDataReader)ExecuteDbDataReader(behavior);
}
public Task<int> ExecuteNonQueryAsync()
{
return ExecuteNonQueryAsync(CancellationToken.None);
}
public virtual Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return TaskHelpers.FromCancellation<int>(cancellationToken);
}
else
{
CancellationTokenRegistration registration = new CancellationTokenRegistration();
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(s => ((DbCommand)s).CancelIgnoreFailure(), this);
}
try
{
return Task.FromResult<int>(ExecuteNonQuery());
}
catch (Exception e)
{
return TaskHelpers.FromException<int>(e);
}
finally
{
registration.Dispose();
}
}
}
public Task<DbDataReader> ExecuteReaderAsync()
{
return ExecuteReaderAsync(CommandBehavior.Default, CancellationToken.None);
}
public Task<DbDataReader> ExecuteReaderAsync(CancellationToken cancellationToken)
{
return ExecuteReaderAsync(CommandBehavior.Default, cancellationToken);
}
public Task<DbDataReader> ExecuteReaderAsync(CommandBehavior behavior)
{
return ExecuteReaderAsync(behavior, CancellationToken.None);
}
public Task<DbDataReader> ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
{
return ExecuteDbDataReaderAsync(behavior, cancellationToken);
}
protected virtual Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return TaskHelpers.FromCancellation<DbDataReader>(cancellationToken);
}
else
{
CancellationTokenRegistration registration = new CancellationTokenRegistration();
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(s => ((DbCommand)s).CancelIgnoreFailure(), this);
}
try
{
return Task.FromResult<DbDataReader>(ExecuteReader(behavior));
}
catch (Exception e)
{
return TaskHelpers.FromException<DbDataReader>(e);
}
finally
{
registration.Dispose();
}
}
}
public Task<object> ExecuteScalarAsync()
{
return ExecuteScalarAsync(CancellationToken.None);
}
public virtual Task<object> ExecuteScalarAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return TaskHelpers.FromCancellation<object>(cancellationToken);
}
else
{
CancellationTokenRegistration registration = new CancellationTokenRegistration();
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(s => ((DbCommand)s).CancelIgnoreFailure(), this);
}
try
{
return Task.FromResult<object>(ExecuteScalar());
}
catch (Exception e)
{
return TaskHelpers.FromException<object>(e);
}
finally
{
registration.Dispose();
}
}
}
abstract public object ExecuteScalar();
abstract public void Prepare();
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
IDbDataParameter IDbCommand.CreateParameter()
{
return CreateDbParameter();
}
IDataReader IDbCommand.ExecuteReader()
{
return (DbDataReader)ExecuteDbDataReader(CommandBehavior.Default);
}
IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior)
{
return (DbDataReader)ExecuteDbDataReader(behavior);
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* 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.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression test for history and warm up using the data available in open source.
/// </summary>
/// <meta name="tag" content="history and warm up" />
/// <meta name="tag" content="history" />
/// <meta name="tag" content="regression test" />
/// <meta name="tag" content="warm up" />
public class IndicatorWarmupAlgorithm : QCAlgorithm
{
private const string SPY = "SPY";
private const string GOOG = "GOOG";
private const string IBM = "IBM";
private const string BAC = "BAC";
private const string GOOGL = "GOOGL";
private readonly Dictionary<Symbol, SymbolData> _sd = new Dictionary<Symbol, SymbolData>();
public override void Initialize()
{
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 11);
SetCash(1000000);
AddSecurity(SecurityType.Equity, SPY, Resolution.Minute);
AddSecurity(SecurityType.Equity, IBM, Resolution.Minute);
AddSecurity(SecurityType.Equity, BAC, Resolution.Minute);
AddSecurity(SecurityType.Equity, GOOG, Resolution.Daily);
AddSecurity(SecurityType.Equity, GOOGL, Resolution.Daily);
foreach (var security in Securities)
{
_sd.Add(security.Key, new SymbolData(security.Key, this));
}
// we want to warm up our algorithm
SetWarmup(SymbolData.RequiredBarsWarmup);
}
public override void OnData(Slice data)
{
// we are only using warmup for indicator spooling, so wait for us to be warm then continue
if (IsWarmingUp) return;
foreach (var sd in _sd.Values)
{
var lastPriceTime = sd.Close.Current.Time;
// only make decisions when we have data on our requested resolution
if (lastPriceTime.RoundDown(sd.Security.Resolution.ToTimeSpan()) == lastPriceTime)
{
sd.Update();
}
}
}
public override void OnOrderEvent(OrderEvent fill)
{
SymbolData sd;
if (_sd.TryGetValue(fill.Symbol, out sd))
{
sd.OnOrderEvent(fill);
}
}
class SymbolData
{
public const int RequiredBarsWarmup = 40;
public const decimal PercentTolerance = 0.001m;
public const decimal PercentGlobalStopLoss = 0.01m;
private const int LotSize = 10;
public readonly Symbol Symbol;
public readonly Security Security;
public decimal Quantity
{
get { return Security.Holdings.Quantity; }
}
public readonly Identity Close;
public readonly AverageDirectionalIndex ADX;
public readonly ExponentialMovingAverage EMA;
public readonly MovingAverageConvergenceDivergence MACD;
private readonly QCAlgorithm _algorithm;
private OrderTicket _currentStopLoss;
public SymbolData(Symbol symbol, QCAlgorithm algorithm)
{
Symbol = symbol;
Security = algorithm.Securities[symbol];
Close = algorithm.Identity(symbol);
ADX = algorithm.ADX(symbol, 14);
EMA = algorithm.EMA(symbol, 14);
MACD = algorithm.MACD(symbol, 12, 26, 9, MovingAverageType.Simple);
// if we're receiving daily
_algorithm = algorithm;
}
public bool IsReady
{
get { return Close.IsReady && ADX.IsReady & EMA.IsReady && MACD.IsReady; }
}
public bool IsUptrend
{
get
{
const decimal tolerance = 1 + PercentTolerance;
return MACD.Signal > MACD*tolerance
&& EMA > Close*tolerance;
}
}
public bool IsDowntrend
{
get
{
const decimal tolerance = 1 - PercentTolerance;
return MACD.Signal < MACD*tolerance
&& EMA < Close*tolerance;
}
}
public void OnOrderEvent(OrderEvent fill)
{
if (fill.Status != OrderStatus.Filled)
{
return;
}
// if we just finished entering, place a stop loss as well
if (Security.Invested)
{
var stop = Security.Holdings.IsLong
? fill.FillPrice*(1 - PercentGlobalStopLoss)
: fill.FillPrice*(1 + PercentGlobalStopLoss);
_currentStopLoss = _algorithm.StopMarketOrder(Symbol, -Quantity, stop, "StopLoss at: " + stop);
}
// check for an exit, cancel the stop loss
else
{
if (_currentStopLoss != null && _currentStopLoss.Status.IsOpen())
{
// cancel our current stop loss
_currentStopLoss.Cancel("Exited position");
_currentStopLoss = null;
}
}
}
public void Update()
{
OrderTicket ticket;
TryEnter(out ticket);
TryExit(out ticket);
}
public bool TryEnter(out OrderTicket ticket)
{
ticket = null;
if (Security.Invested)
{
// can't enter if we're already in
return false;
}
int qty = 0;
decimal limit = 0m;
if (IsUptrend)
{
// 100 order lots
qty = LotSize;
limit = Security.Low;
}
else if (IsDowntrend)
{
limit = Security.High;
qty = -LotSize;
}
if (qty != 0)
{
ticket = _algorithm.LimitOrder(Symbol, qty, limit, "TryEnter at: " + limit);
}
return qty != 0;
}
public bool TryExit(out OrderTicket ticket)
{
const decimal exitTolerance = 1 + 2 * PercentTolerance;
ticket = null;
if (!Security.Invested)
{
// can't exit if we haven't entered
return false;
}
decimal limit = 0m;
if (Security.Holdings.IsLong && Close*exitTolerance < EMA)
{
limit = Security.High;
}
else if (Security.Holdings.IsShort && Close > EMA*exitTolerance)
{
limit = Security.Low;
}
if (limit != 0)
{
ticket = _algorithm.LimitOrder(Symbol, -Quantity, limit, "TryExit at: " + limit);
}
return -Quantity != 0;
}
}
}
}
| |
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
namespace ClickHouse.Ado.Impl.ATG.Enums {
internal class Token {
public int kind; // token kind
public int pos; // token position in bytes in the source text (starting at 0)
public int charPos; // token position in characters in the source text (starting at 0)
public int col; // token column (starting at 1)
public int line; // token line (starting at 1)
public string val; // token value
public Token next; // ML 2005-03-11 Tokens are kept in linked list
}
//-----------------------------------------------------------------------------------
// Buffer
//-----------------------------------------------------------------------------------
internal class Buffer {
// This Buffer supports the following cases:
// 1) seekable stream (file)
// a) whole stream in buffer
// b) part of stream in buffer
// 2) non seekable stream (network, console)
public const int EOF = char.MaxValue + 1;
const int MIN_BUFFER_LENGTH = 1024; // 1KB
const int MAX_BUFFER_LENGTH = MIN_BUFFER_LENGTH * 64; // 64KB
byte[] buf; // input buffer
int bufStart; // position of first byte in buffer relative to input stream
int bufLen; // length of buffer
int fileLen; // length of input stream (may change if the stream is no file)
int bufPos; // current position in buffer
Stream stream; // input stream (seekable)
bool isUserStream; // was the stream opened by the user?
public Buffer (Stream s, bool isUserStream) {
stream = s; this.isUserStream = isUserStream;
if (stream.CanSeek) {
fileLen = (int) stream.Length;
bufLen = Math.Min(fileLen, MAX_BUFFER_LENGTH);
bufStart = Int32.MaxValue; // nothing in the buffer so far
} else {
fileLen = bufLen = bufStart = 0;
}
buf = new byte[(bufLen>0) ? bufLen : MIN_BUFFER_LENGTH];
if (fileLen > 0) Pos = 0; // setup buffer to position 0 (start)
else bufPos = 0; // index 0 is already after the file, thus Pos = 0 is invalid
if (bufLen == fileLen && stream.CanSeek) Close();
}
protected Buffer(Buffer b) { // called in UTF8Buffer constructor
buf = b.buf;
bufStart = b.bufStart;
bufLen = b.bufLen;
fileLen = b.fileLen;
bufPos = b.bufPos;
stream = b.stream;
// keep destructor from closing the stream
b.stream = null;
isUserStream = b.isUserStream;
}
~Buffer() { Close(); }
protected void Close() {
if (!isUserStream && stream != null) {
#if NETSTANDARD15 || NETCOREAPP11
stream.Dispose();
#else
stream.Close();
#endif
stream = null;
}
}
public virtual int Read () {
if (bufPos < bufLen) {
return buf[bufPos++];
} else if (Pos < fileLen) {
Pos = Pos; // shift buffer start to Pos
return buf[bufPos++];
} else if (stream != null && !stream.CanSeek && ReadNextStreamChunk() > 0) {
return buf[bufPos++];
} else {
return EOF;
}
}
public int Peek () {
int curPos = Pos;
int ch = Read();
Pos = curPos;
return ch;
}
// beg .. begin, zero-based, inclusive, in byte
// end .. end, zero-based, exclusive, in byte
public string GetString (int beg, int end) {
int len = 0;
char[] buf = new char[end - beg];
int oldPos = Pos;
Pos = beg;
while (Pos < end) buf[len++] = (char) Read();
Pos = oldPos;
return new String(buf, 0, len);
}
public int Pos {
get { return bufPos + bufStart; }
set {
if (value >= fileLen && stream != null && !stream.CanSeek) {
// Wanted position is after buffer and the stream
// is not seek-able e.g. network or console,
// thus we have to read the stream manually till
// the wanted position is in sight.
while (value >= fileLen && ReadNextStreamChunk() > 0);
}
if (value < 0 || value > fileLen) {
throw new FatalError("buffer out of bounds access, position: " + value);
}
if (value >= bufStart && value < bufStart + bufLen) { // already in buffer
bufPos = value - bufStart;
} else if (stream != null) { // must be swapped in
stream.Seek(value, SeekOrigin.Begin);
bufLen = stream.Read(buf, 0, buf.Length);
bufStart = value; bufPos = 0;
} else {
// set the position to the end of the file, Pos will return fileLen.
bufPos = fileLen - bufStart;
}
}
}
// Read the next chunk of bytes from the stream, increases the buffer
// if needed and updates the fields fileLen and bufLen.
// Returns the number of bytes read.
private int ReadNextStreamChunk() {
int free = buf.Length - bufLen;
if (free == 0) {
// in the case of a growing input stream
// we can neither seek in the stream, nor can we
// foresee the maximum length, thus we must adapt
// the buffer size on demand.
byte[] newBuf = new byte[bufLen * 2];
Array.Copy(buf, newBuf, bufLen);
buf = newBuf;
free = bufLen;
}
int read = stream.Read(buf, bufLen, free);
if (read > 0) {
fileLen = bufLen = (bufLen + read);
return read;
}
// end of stream reached
return 0;
}
}
//-----------------------------------------------------------------------------------
// UTF8Buffer
//-----------------------------------------------------------------------------------
internal class UTF8Buffer: Buffer {
public UTF8Buffer(Buffer b): base(b) {}
public override int Read() {
int ch;
do {
ch = base.Read();
// until we find a utf8 start (0xxxxxxx or 11xxxxxx)
} while ((ch >= 128) && ((ch & 0xC0) != 0xC0) && (ch != EOF));
if (ch < 128 || ch == EOF) {
// nothing to do, first 127 chars are the same in ascii and utf8
// 0xxxxxxx or end of file character
} else if ((ch & 0xF0) == 0xF0) {
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
int c1 = ch & 0x07; ch = base.Read();
int c2 = ch & 0x3F; ch = base.Read();
int c3 = ch & 0x3F; ch = base.Read();
int c4 = ch & 0x3F;
ch = (((((c1 << 6) | c2) << 6) | c3) << 6) | c4;
} else if ((ch & 0xE0) == 0xE0) {
// 1110xxxx 10xxxxxx 10xxxxxx
int c1 = ch & 0x0F; ch = base.Read();
int c2 = ch & 0x3F; ch = base.Read();
int c3 = ch & 0x3F;
ch = (((c1 << 6) | c2) << 6) | c3;
} else if ((ch & 0xC0) == 0xC0) {
// 110xxxxx 10xxxxxx
int c1 = ch & 0x1F; ch = base.Read();
int c2 = ch & 0x3F;
ch = (c1 << 6) | c2;
}
return ch;
}
}
//-----------------------------------------------------------------------------------
// Scanner
//-----------------------------------------------------------------------------------
internal class Scanner {
const char EOL = '\n';
const int eofSym = 0; /* pdt */
const int maxT = 5;
const int noSym = 5;
char valCh; // current input character (for token.val)
public Buffer buffer; // scanner buffer
Token t; // current token
int ch; // current input character
int pos; // byte position of current character
int charPos; // position by unicode characters starting with 0
int col; // column number of current character
int line; // line number of current character
int oldEols; // EOLs that appeared in a comment;
static readonly Dictionary<int,int> start; // maps first token character to start state
Token tokens; // list of tokens already peeked (first token is a dummy)
Token pt; // current peek token
char[] tval = new char[128]; // text of current token
int tlen; // length of current token
static Scanner() {
start = new Dictionary<int,int>(128);
for (int i = 48; i <= 57; ++i) start[i] = 4;
start[39] = 1;
for (int i = 43; i <= 43; ++i) start[i] = 3;
for (int i = 45; i <= 45; ++i) start[i] = 3;
start[61] = 6;
start[44] = 7;
start[Buffer.EOF] = -1;
}
public Scanner (string fileName) {
try {
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
buffer = new Buffer(stream, false);
Init();
} catch (IOException) {
throw new FatalError("Cannot open file " + fileName);
}
}
public Scanner (Stream s) {
buffer = new Buffer(s, true);
Init();
}
void Init() {
pos = -1; line = 1; col = 0; charPos = -1;
oldEols = 0;
NextCh();
if (ch == 0xEF) { // check optional byte order mark for UTF-8
NextCh(); int ch1 = ch;
NextCh(); int ch2 = ch;
if (ch1 != 0xBB || ch2 != 0xBF) {
throw new FatalError(String.Format("illegal byte order mark: EF {0,2:X} {1,2:X}", ch1, ch2));
}
buffer = new UTF8Buffer(buffer); col = 0; charPos = -1;
NextCh();
}
pt = tokens = new Token(); // first token is a dummy
}
void NextCh() {
if (oldEols > 0) { ch = EOL; oldEols--; }
else {
pos = buffer.Pos;
// buffer reads unicode chars, if UTF8 has been detected
ch = buffer.Read(); col++; charPos++;
// replace isolated '\r' by '\n' in order to make
// eol handling uniform across Windows, Unix and Mac
if (ch == '\r' && buffer.Peek() != '\n') ch = EOL;
if (ch == EOL) { line++; col = 0; }
}
if (ch != Buffer.EOF) {
valCh = (char) ch;
ch = char.ToLower((char) ch);
}
}
void AddCh() {
if (tlen >= tval.Length) {
char[] newBuf = new char[2 * tval.Length];
Array.Copy(tval, 0, newBuf, 0, tval.Length);
tval = newBuf;
}
if (ch != Buffer.EOF) {
tval[tlen++] = valCh;
NextCh();
}
}
void CheckLiteral() {
switch (t.val.ToLower()) {
default: break;
}
}
Token NextToken() {
while (ch == ' ' ||
ch >= 9 && ch <= 10 || ch == 13
) NextCh();
int recKind = noSym;
int recEnd = pos;
t = new Token();
t.pos = pos; t.col = col; t.line = line; t.charPos = charPos;
int state;
if (start.ContainsKey(ch)) { state = (int) start[ch]; }
else { state = 0; }
tlen = 0; AddCh();
switch (state) {
case -1: { t.kind = eofSym; break; } // NextCh already done
case 0: {
if (recKind != noSym) {
tlen = recEnd - t.pos;
SetScannerBehindT();
}
t.kind = recKind; break;
} // NextCh already done
case 1:
if (ch <= '&' || ch >= '(' && ch <= '[' || ch >= ']' && ch <= 65535) {AddCh(); goto case 1;}
else if (ch == 39) {AddCh(); goto case 2;}
else if (ch == 92) {AddCh(); goto case 5;}
else {goto case 0;}
case 2:
{t.kind = 1; break;}
case 3:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 4;}
else {goto case 0;}
case 4:
recEnd = pos; recKind = 2;
if (ch >= '0' && ch <= '9') {AddCh(); goto case 4;}
else {t.kind = 2; break;}
case 5:
if (ch == 39 || ch == 92) {AddCh(); goto case 1;}
else {goto case 0;}
case 6:
{t.kind = 3; break;}
case 7:
{t.kind = 4; break;}
}
t.val = new String(tval, 0, tlen);
return t;
}
private void SetScannerBehindT() {
buffer.Pos = t.pos;
NextCh();
line = t.line; col = t.col; charPos = t.charPos;
for (int i = 0; i < tlen; i++) NextCh();
}
// get the next token (possibly a token already seen during peeking)
public Token Scan () {
if (tokens.next == null) {
return NextToken();
} else {
pt = tokens = tokens.next;
return tokens;
}
}
// peek for the next token, ignore pragmas
public Token Peek () {
do {
if (pt.next == null) {
pt.next = NextToken();
}
pt = pt.next;
} while (pt.kind > maxT); // skip pragmas
return pt;
}
// make sure that peeking starts at the current scan position
public void ResetPeek () { pt = tokens; }
} // end Scanner
}
| |
// Copyright 2012 Applied Geographics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using GeoAPI.Geometries;
using AppGeo.Clients;
using AppGeo.Clients.ArcIms.ArcXml;
namespace AppGeo.Clients.ArcIms
{
public class ArcImsMap : CommonMap
{
private ArcImsService _service;
private string _coordinateSystem = null;
private LayerList _layerList = new LayerList();
private Layers _layers = new Layers();
private Layer _acetateLayer = new Layer("__acetate", LayerType.Acetate);
private bool _accessImageFromHost = true;
public Color BackgroundColor = Color.Empty;
public bool Transparent = false;
public ArcImsMap(ArcImsService service, int width, int height, Envelope extent) : this((ArcImsDataFrame)service.DefaultDataFrame, width, height, extent) { }
public ArcImsMap(ArcImsDataFrame dataFrame, int width, int height, Envelope extent)
{
_service = dataFrame.Service as ArcImsService;
DataFrame = dataFrame;
Width = width;
Height = height;
Extent = extent;
}
public bool AccessImageFromHost
{
get
{
return _accessImageFromHost;
}
set
{
_accessImageFromHost = value;
}
}
public string CoordinateSystem
{
get
{
return _coordinateSystem;
}
set
{
if (value == "")
{
_coordinateSystem = null;
}
else
{
_coordinateSystem = value;
}
}
}
public ArcImsService Service
{
get
{
return _service;
}
}
public void AddGraphic(IGeometry shape, Symbol symbol)
{
AddGraphic(shape, symbol, false);
}
public void AddGraphic(IGeometry shape, Symbol symbol, bool inPixels)
{
ArcXml.Object o = new ArcXml.Object(shape, symbol);
o.Units = inPixels ? ObjectUnits.Pixel : ObjectUnits.Database;
_acetateLayer.Add(o);
}
public void AddGraphic(Text text, TextMarkerSymbol symbol)
{
AddGraphic(text, symbol, false);
}
public void AddGraphic(Text text, TextMarkerSymbol symbol, bool inPixels)
{
ArcXml.Object o = new ArcXml.Object(text, symbol);
o.Units = inPixels ? ObjectUnits.Pixel : ObjectUnits.Database;
_acetateLayer.Add(o);
}
public void AddGraphic(NorthArrow northArrow)
{
_acetateLayer.Add(northArrow);
}
public void AddGraphic(ScaleBar scaleBar)
{
_acetateLayer.Add(scaleBar);
}
public override void AddLayer(string layerId)
{
AddLayer(layerId, "");
}
public override void AddLayer(string layerId, string definitionQuery)
{
ArcImsLayer layer = DataFrame.Layers.FirstOrDefault(lyr => lyr.ID == layerId) as ArcImsLayer;
if (layer == null)
{
throw new ArcImsException(String.Format("No layer with an ID of \"{0}\" exists in the dataFrame of this ArcImsMap.", layerId));
}
AddLayer(layer, definitionQuery);
}
public override void AddLayer(CommonLayer layer)
{
AddLayer(layer, "");
}
public override void AddLayer(CommonLayer layer, string definitionQuery)
{
ArcImsLayer arcImsLayer = layer as ArcImsLayer;
if (arcImsLayer == null)
{
throw new ArcImsException(String.Format("A {0} cannot be added to an ArcImsMap.", layer.GetType().Name));
}
AddLayer(arcImsLayer, definitionQuery);
}
public void AddLayer(ArcImsLayer layer)
{
AddLayer(layer, null, LayerQueryMode.None);
}
public void AddLayer(ArcImsLayer layer, string definitionQuery)
{
if (String.IsNullOrEmpty(definitionQuery))
{
AddLayer(layer, null, LayerQueryMode.None);
}
else
{
AddLayer(layer, definitionQuery, LayerQueryMode.Definition);
}
}
public void AddLayer(ArcImsLayer layer, string query, LayerQueryMode queryMode)
{
AddLayer(layer, query, queryMode, null);
}
public void AddLayer(ArcImsLayer layer, Renderer renderer)
{
AddLayer(layer, null, LayerQueryMode.None, renderer);
}
public void AddLayer(ArcImsLayer layer, string query, LayerQueryMode queryMode, Renderer renderer)
{
int nextLayerNo = 0;
// layers from other services and data frames are not allowed
if (layer.DataFrame != DataFrame)
{
throw new ArcImsException("The specified ArcImsLayer is not in the same service and dataframe as the ArcImsMap.");
}
// queries and renderers are only allow on feature layers
SpatialQuery spatialQuery = null;
if (!String.IsNullOrEmpty(query) && queryMode != LayerQueryMode.None)
{
if (layer.Type != CommonLayerType.Feature)
{
throw new ArcImsException("Definition and selection queries are only allowed on feature layers");
}
spatialQuery = new SpatialQuery(query);
}
if (renderer != null && layer.Type != CommonLayerType.Feature)
{
throw new ArcImsException("Custom renderers are only allowed on feature layers");
}
// add all group layers that contain this layer
ArcImsLayer parent = layer.Parent as ArcImsLayer;
while (parent != null)
{
AddLayer(new LayerDef(parent.ID));
parent = parent.Parent as ArcImsLayer;
}
// handle queries and renderers
LayerDef layerDef = new LayerDef(layer.ID);
if (spatialQuery != null)
{
if (queryMode == LayerQueryMode.Definition)
{
layerDef.Query = spatialQuery;
layerDef.Renderer = renderer;
}
if (queryMode == LayerQueryMode.Selection)
{
Layer axlLayer = new Layer(String.Format("__{0}", nextLayerNo++));
axlLayer.Query = spatialQuery;
axlLayer.Dataset = new Dataset(layer.ID);
if (_service.IsArcMap)
{
layerDef.Renderer = renderer;
}
else
{
axlLayer.Renderer = renderer;
}
AddLayer(axlLayer);
}
}
else
{
layerDef.Renderer = renderer;
}
AddLayer(layerDef);
}
public void AddLayer(LayerDef layerDef)
{
if (!_layerList.Contains(layerDef.ID))
{
_layerList.Add(layerDef);
}
}
public void AddLayer(Layer layer)
{
_layers.Add(layer);
}
public void AddLayer(LayerDef layerDef, Layer layer)
{
_layerList.Add(layerDef);
_layers.Add(layer);
}
public void AddLayers(ICollection<ArcImsLayer> layers)
{
AddLayers(layers.Cast<CommonLayer>().ToList());
}
public override void AddLayerAndChildren(string layerId)
{
ArcImsLayer layer = DataFrame.Layers.FirstOrDefault(lyr => lyr.ID == layerId) as ArcImsLayer;
if (layer == null)
{
throw new ArcImsException(String.Format("No layer with an ID of \"{0}\" exists in the dataFrame of this ArcImsMap.", layerId));
}
AddLayerAndChildren(layer);
}
public override void AddLayerAndChildren(CommonLayer layer)
{
ArcImsLayer arcImsLayer = layer as ArcImsLayer;
if (arcImsLayer == null)
{
throw new ArcImsException(String.Format("A {0} cannot be added to an ArcImsMap.", layer.GetType().Name));
}
AddLayer(arcImsLayer);
if (arcImsLayer.Children != null && arcImsLayer.Children.Count > 0)
{
foreach (CommonLayer child in arcImsLayer.Children)
{
AddLayerAndChildren(child);
}
}
}
public override void Clear()
{
_layerList.Clear();
_layers.Clear();
_acetateLayer.Objects.Clear();
}
public override string GetImageUrl()
{
GetImage getImage = PrepareGetImage();
ArcXml.Image image = (ArcXml.Image)_service.Send(getImage);
string url = image.Output.Url;
if (_accessImageFromHost)
{
UriBuilder hostBuilder = new UriBuilder(_service.Host.ServerUrl);
UriBuilder urlBuilder = new UriBuilder(url);
urlBuilder.Host = hostBuilder.Host;
url = urlBuilder.ToString();
}
return url;
}
public override byte[] GetImageBytes()
{
string imageUrl = GetImageUrl();
WebClient webClient = new WebClient();
webClient.Credentials = _service.Host.Credentials;
try
{
byte[] image = webClient.DownloadData(imageUrl);
return image;
}
catch (Exception ex)
{
throw new ArcImsException("Unable to retrieve map image", ex);
}
}
private GetImage PrepareGetImage()
{
// create a new GetImage request, set the extent and image size
GetImage getImage = new GetImage();
getImage.Properties.ImageSize.Width = Width;
getImage.Properties.ImageSize.Height = Height;
getImage.Properties.Envelope = VisibleExtent;
if (Resolution != 1)
{
if (_service.IsArcMap)
{
getImage.Properties.ImageSize.Width = Convert.ToInt32(Width * Resolution);
getImage.Properties.ImageSize.Height = Convert.ToInt32(Height * Resolution);
getImage.Properties.ImageSize.Dpi = Convert.ToInt32(DataFrame.Dpi * Resolution);
}
else
{
getImage.Properties.ImageSize.PrintWidth = Convert.ToInt32(Width * Resolution);
getImage.Properties.ImageSize.PrintHeight = Convert.ToInt32(Height * Resolution);
getImage.Properties.ImageSize.ScaleSymbols = true;
}
}
getImage.DataFrame = DataFrame.Name;
// set the projection if necessary
if (_coordinateSystem != null)
{
FeatureCoordSys featSys = new FeatureCoordSys();
FilterCoordSys filtSys = new FilterCoordSys();
string csType = _coordinateSystem.Substring(0, 6);
if (csType == "PROJCS" || csType == "GEOGCS")
{
featSys.String = _coordinateSystem;
filtSys.String = _coordinateSystem;
}
else
{
featSys.ID = _coordinateSystem;
filtSys.ID = _coordinateSystem;
}
getImage.Properties.FeatureCoordSys = featSys;
getImage.Properties.FilterCoordSys = filtSys;
}
// set the background color if one was specified
if (BackgroundColor != Color.Empty)
{
getImage.Properties.Background = new Background(BackgroundColor);
if (Transparent)
{
getImage.Properties.Background.TransparentColor = BackgroundColor;
}
}
// set the image format if one was specified
if (ImageType != CommonImageType.Default)
{
getImage.Properties.Output = new Output();
switch (ImageType)
{
case CommonImageType.Jpg: getImage.Properties.Output.Type = ArcXml.ImageType.Jpg; break;
case CommonImageType.Png: getImage.Properties.Output.Type = ArcXml.ImageType.Png24; break;
}
}
// add layers to the request that were specified in code
getImage.Properties.LayerList = (LayerList)_layerList.Clone();
if (_layers.Count > 0)
{
getImage.Layers = (Layers)_layers.Clone();
}
if (_acetateLayer.Objects != null && _acetateLayer.Objects.Count > 0)
{
if (getImage.Layers == null)
{
getImage.Layers = new Layers();
}
getImage.Layers.Add((Layer)_acetateLayer.Clone());
getImage.Properties.LayerList.Add(new LayerDef(_acetateLayer.ID));
}
return getImage;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;
using System.Collections;
using Thinktecture.Tools.Web.Services.CodeGeneration;
using Thinktecture.Tools.Web.Services.Wscf.Environment;
namespace Thinktecture.Tools.Web.Services.ContractFirst
{
/// <summary>
/// Summary description for WebServiceCodeGenOptions.
/// </summary>
public class WebServiceCodeGenDialogNew : Form
{
private Button button1;
private Button button2;
private GroupBox groupBox2;
private Label label1;
private TextBox tbDestinationFilename;
private Label label2;
private TextBox tbDestinationNamespace;
private ToolTip cfTooltip;
private Panel panel1;
private GroupBox groupBox5;
private Label label4;
private Button bnBrowse;
private OpenFileDialog openFileDialogWSDL;
private IContainer components;
private CheckBox cbSettings;
private CheckBox cbSeperateFiles;
private PictureBox pbWizard;
private ComboBox cbWsdlLocation;
private System.Windows.Forms.CheckBox cbOverwrite;
private System.Windows.Forms.PictureBox pbWscf;
private System.Windows.Forms.CheckBox cbAdjustCasing;
private System.Windows.Forms.CheckBox cbMultipleFiles;
private System.Windows.Forms.CheckBox cbCollections;
private System.Windows.Forms.CheckBox cbProperties;
private System.Windows.Forms.RadioButton rbServer;
private System.Windows.Forms.RadioButton rbClient;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox4;
private CheckBox cbOrderIds;
private CheckBox cbAsync;
private CheckBox cbDataBinding;
private ArrayList wsdlFileCache;
private CheckBox cbGenericList;
private bool externalFile = false;
private string wsdlLocation = "";
private string wsdlPath = "";
private CheckBox cbEnableWsdlEndpoint;
private GroupBox gbServiceBehavior;
private CheckBox cbUseSynchronizationContext;
private Label label3;
private Label label5;
private ComboBox cbConcurrencyMode;
private ComboBox cbInstanceContextMode;
private CheckBox cbGenerateSvcFile;
private CheckBox cbFormatSoapActions;
private GroupBox gbServiceMethodImplementation;
private RadioButton rbAbstractMethods;
private RadioButton rbNotImplementedException;
private RadioButton rbPartialClassMethodCalls;
private CheckBox cbVirtualProperties;
private bool isLoading = true;
public WebServiceCodeGenDialogNew()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
// Initialize the .wsdl file cache.
wsdlFileCache = new ArrayList();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WebServiceCodeGenDialogNew));
this.cbSeperateFiles = new System.Windows.Forms.CheckBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.tbDestinationNamespace = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
this.tbDestinationFilename = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.cfTooltip = new System.Windows.Forms.ToolTip(this.components);
this.cbSettings = new System.Windows.Forms.CheckBox();
this.pbWscf = new System.Windows.Forms.PictureBox();
this.cbAdjustCasing = new System.Windows.Forms.CheckBox();
this.cbMultipleFiles = new System.Windows.Forms.CheckBox();
this.cbCollections = new System.Windows.Forms.CheckBox();
this.cbProperties = new System.Windows.Forms.CheckBox();
this.rbServer = new System.Windows.Forms.RadioButton();
this.rbClient = new System.Windows.Forms.RadioButton();
this.cbOverwrite = new System.Windows.Forms.CheckBox();
this.cbAsync = new System.Windows.Forms.CheckBox();
this.cbDataBinding = new System.Windows.Forms.CheckBox();
this.cbOrderIds = new System.Windows.Forms.CheckBox();
this.cbGenericList = new System.Windows.Forms.CheckBox();
this.cbEnableWsdlEndpoint = new System.Windows.Forms.CheckBox();
this.cbUseSynchronizationContext = new System.Windows.Forms.CheckBox();
this.cbConcurrencyMode = new System.Windows.Forms.ComboBox();
this.cbInstanceContextMode = new System.Windows.Forms.ComboBox();
this.cbGenerateSvcFile = new System.Windows.Forms.CheckBox();
this.cbFormatSoapActions = new System.Windows.Forms.CheckBox();
this.gbServiceMethodImplementation = new System.Windows.Forms.GroupBox();
this.rbAbstractMethods = new System.Windows.Forms.RadioButton();
this.rbPartialClassMethodCalls = new System.Windows.Forms.RadioButton();
this.rbNotImplementedException = new System.Windows.Forms.RadioButton();
this.panel1 = new System.Windows.Forms.Panel();
this.pbWizard = new System.Windows.Forms.PictureBox();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.cbWsdlLocation = new System.Windows.Forms.ComboBox();
this.bnBrowse = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.openFileDialogWSDL = new System.Windows.Forms.OpenFileDialog();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.gbServiceBehavior = new System.Windows.Forms.GroupBox();
this.label3 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.cbVirtualProperties = new System.Windows.Forms.CheckBox();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pbWscf)).BeginInit();
this.gbServiceMethodImplementation.SuspendLayout();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pbWizard)).BeginInit();
this.groupBox5.SuspendLayout();
this.groupBox1.SuspendLayout();
this.gbServiceBehavior.SuspendLayout();
this.groupBox4.SuspendLayout();
this.SuspendLayout();
//
// cbSeperateFiles
//
this.cbSeperateFiles.Location = new System.Drawing.Point(0, 0);
this.cbSeperateFiles.Name = "cbSeperateFiles";
this.cbSeperateFiles.Size = new System.Drawing.Size(104, 24);
this.cbSeperateFiles.TabIndex = 0;
this.cfTooltip.SetToolTip(this.cbSeperateFiles, "Generates collection-based members instead of arrays.");
//
// button1
//
this.button1.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;
this.button1.Enabled = false;
this.button1.Location = new System.Drawing.Point(401, 575);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(77, 28);
this.button1.TabIndex = 5;
this.button1.Text = "Generate";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.button2.Location = new System.Drawing.Point(484, 575);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(77, 28);
this.button2.TabIndex = 6;
this.button2.Text = "Cancel";
//
// tbDestinationNamespace
//
this.tbDestinationNamespace.Location = new System.Drawing.Point(152, 49);
this.tbDestinationNamespace.Name = "tbDestinationNamespace";
this.tbDestinationNamespace.Size = new System.Drawing.Size(392, 20);
this.tbDestinationNamespace.TabIndex = 3;
this.cfTooltip.SetToolTip(this.tbDestinationNamespace, "Please enter the name of .NET namespace for the client proxy.");
//
// groupBox2
//
this.groupBox2.Controls.Add(this.tbDestinationNamespace);
this.groupBox2.Controls.Add(this.label2);
this.groupBox2.Controls.Add(this.tbDestinationFilename);
this.groupBox2.Controls.Add(this.label1);
this.groupBox2.Location = new System.Drawing.Point(8, 486);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(553, 80);
this.groupBox2.TabIndex = 2;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Files and namespaces ";
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 26);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(118, 16);
this.label2.TabIndex = 0;
this.label2.Text = "Destination file name";
//
// tbDestinationFilename
//
this.tbDestinationFilename.Location = new System.Drawing.Point(152, 26);
this.tbDestinationFilename.Name = "tbDestinationFilename";
this.tbDestinationFilename.Size = new System.Drawing.Size(392, 20);
this.tbDestinationFilename.TabIndex = 1;
this.cfTooltip.SetToolTip(this.tbDestinationFilename, "Please enter the name of .NET proxy file that gets generated.");
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 52);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(118, 16);
this.label1.TabIndex = 2;
this.label1.Text = "Destination namespace";
//
// cbSettings
//
this.cbSettings.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.cbSettings.Location = new System.Drawing.Point(10, 579);
this.cbSettings.Name = "cbSettings";
this.cbSettings.Size = new System.Drawing.Size(128, 23);
this.cbSettings.TabIndex = 3;
this.cbSettings.Text = "Remember settings";
this.cfTooltip.SetToolTip(this.cbSettings, "Save dialog settings for future use.");
this.cbSettings.CheckedChanged += new System.EventHandler(this.cbSettings_CheckedChanged);
//
// pbWscf
//
this.pbWscf.Image = ((System.Drawing.Image)(resources.GetObject("pbWscf.Image")));
this.pbWscf.Location = new System.Drawing.Point(462, 4);
this.pbWscf.Name = "pbWscf";
this.pbWscf.Size = new System.Drawing.Size(104, 32);
this.pbWscf.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pbWscf.TabIndex = 11;
this.pbWscf.TabStop = false;
this.cfTooltip.SetToolTip(this.pbWscf, "http://www.thinktecture.com/");
this.pbWscf.Click += new System.EventHandler(this.pbWscf_Click);
//
// cbAdjustCasing
//
this.cbAdjustCasing.Location = new System.Drawing.Point(144, 75);
this.cbAdjustCasing.Name = "cbAdjustCasing";
this.cbAdjustCasing.Size = new System.Drawing.Size(102, 24);
this.cbAdjustCasing.TabIndex = 5;
this.cbAdjustCasing.Text = "Adjust casing";
this.cfTooltip.SetToolTip(this.cbAdjustCasing, "Ensures that generated .NET types follow the .NET guidelines for casing.");
//
// cbMultipleFiles
//
this.cbMultipleFiles.Location = new System.Drawing.Point(425, 49);
this.cbMultipleFiles.Name = "cbMultipleFiles";
this.cbMultipleFiles.Size = new System.Drawing.Size(96, 24);
this.cbMultipleFiles.TabIndex = 9;
this.cbMultipleFiles.Text = "Separate files";
this.cfTooltip.SetToolTip(this.cbMultipleFiles, "Generates each data type into its own seperate source file.");
//
// cbCollections
//
this.cbCollections.Location = new System.Drawing.Point(299, 23);
this.cbCollections.Name = "cbCollections";
this.cbCollections.Size = new System.Drawing.Size(80, 24);
this.cbCollections.TabIndex = 6;
this.cbCollections.Text = "Collections";
this.cfTooltip.SetToolTip(this.cbCollections, "Generates collection-based members instead of arrays.");
this.cbCollections.CheckedChanged += new System.EventHandler(this.cbCollections_CheckedChanged);
//
// cbProperties
//
this.cbProperties.Location = new System.Drawing.Point(16, 24);
this.cbProperties.Name = "cbProperties";
this.cbProperties.Size = new System.Drawing.Size(115, 23);
this.cbProperties.TabIndex = 0;
this.cbProperties.Text = "Public properties";
this.cfTooltip.SetToolTip(this.cbProperties, "Generate public properties in your data classes instead of public fields.");
//
// rbServer
//
this.rbServer.Location = new System.Drawing.Point(148, 19);
this.rbServer.Name = "rbServer";
this.rbServer.Size = new System.Drawing.Size(112, 24);
this.rbServer.TabIndex = 1;
this.rbServer.Text = "Service-side stub";
this.cfTooltip.SetToolTip(this.rbServer, "Select this to generate the service-side stub");
this.rbServer.CheckedChanged += new System.EventHandler(this.rbServer_CheckedChanged);
//
// rbClient
//
this.rbClient.Location = new System.Drawing.Point(17, 19);
this.rbClient.Name = "rbClient";
this.rbClient.Size = new System.Drawing.Size(111, 24);
this.rbClient.TabIndex = 0;
this.rbClient.Text = "Client-side proxy";
this.cfTooltip.SetToolTip(this.rbClient, "Select this to generate the client-side proxy");
this.rbClient.CheckedChanged += new System.EventHandler(this.rbClient_CheckedChanged);
//
// cbOverwrite
//
this.cbOverwrite.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.cbOverwrite.Location = new System.Drawing.Point(136, 578);
this.cbOverwrite.Name = "cbOverwrite";
this.cbOverwrite.Size = new System.Drawing.Size(144, 24);
this.cbOverwrite.TabIndex = 4;
this.cbOverwrite.Text = "Overwrite existing files";
this.cfTooltip.SetToolTip(this.cbOverwrite, "Overwrite all files upon code generation.");
this.cbOverwrite.CheckedChanged += new System.EventHandler(this.cbOverwrite_CheckedChanged);
//
// cbAsync
//
this.cbAsync.AutoSize = true;
this.cbAsync.Location = new System.Drawing.Point(299, 53);
this.cbAsync.Name = "cbAsync";
this.cbAsync.Size = new System.Drawing.Size(98, 17);
this.cbAsync.TabIndex = 7;
this.cbAsync.Text = "Async methods";
this.cfTooltip.SetToolTip(this.cbAsync, "Creates Begin and End methods for the asynchronous invocation of Web Services.");
this.cbAsync.UseVisualStyleBackColor = true;
//
// cbDataBinding
//
this.cbDataBinding.AutoSize = true;
this.cbDataBinding.Location = new System.Drawing.Point(16, 79);
this.cbDataBinding.Name = "cbDataBinding";
this.cbDataBinding.Size = new System.Drawing.Size(86, 17);
this.cbDataBinding.TabIndex = 2;
this.cbDataBinding.Text = "Data binding";
this.cfTooltip.SetToolTip(this.cbDataBinding, "Implement INotifyPropertyChanged interface on all generated types to enable data " +
"binding.");
this.cbDataBinding.UseVisualStyleBackColor = true;
this.cbDataBinding.CheckedChanged += new System.EventHandler(this.cbDataBinding_CheckedChanged);
//
// cbOrderIds
//
this.cbOrderIds.AutoSize = true;
this.cbOrderIds.Location = new System.Drawing.Point(144, 53);
this.cbOrderIds.Name = "cbOrderIds";
this.cbOrderIds.Size = new System.Drawing.Size(99, 17);
this.cbOrderIds.TabIndex = 4;
this.cbOrderIds.Text = "Order identifiers";
this.cfTooltip.SetToolTip(this.cbOrderIds, "Generate explicit order identifiers on particle members.");
this.cbOrderIds.UseVisualStyleBackColor = true;
//
// cbGenericList
//
this.cbGenericList.AutoSize = true;
this.cbGenericList.Location = new System.Drawing.Point(425, 27);
this.cbGenericList.Name = "cbGenericList";
this.cbGenericList.Size = new System.Drawing.Size(61, 17);
this.cbGenericList.TabIndex = 8;
this.cbGenericList.Text = "List<T>";
this.cfTooltip.SetToolTip(this.cbGenericList, "Generates List<T>-based members instead of arrays.");
this.cbGenericList.UseVisualStyleBackColor = true;
this.cbGenericList.CheckedChanged += new System.EventHandler(this.cbGenericList_CheckedChanged);
//
// cbEnableWsdlEndpoint
//
this.cbEnableWsdlEndpoint.Location = new System.Drawing.Point(320, 49);
this.cbEnableWsdlEndpoint.Name = "cbEnableWsdlEndpoint";
this.cbEnableWsdlEndpoint.Size = new System.Drawing.Size(160, 24);
this.cbEnableWsdlEndpoint.TabIndex = 5;
this.cbEnableWsdlEndpoint.Text = "Enable WSDL Endpoint";
this.cfTooltip.SetToolTip(this.cbEnableWsdlEndpoint, "Adds the configuration required to expose the WSDL file as metadata service endpo" +
"int.");
//
// cbUseSynchronizationContext
//
this.cbUseSynchronizationContext.Checked = true;
this.cbUseSynchronizationContext.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbUseSynchronizationContext.Location = new System.Drawing.Point(320, 22);
this.cbUseSynchronizationContext.Name = "cbUseSynchronizationContext";
this.cbUseSynchronizationContext.Size = new System.Drawing.Size(191, 24);
this.cbUseSynchronizationContext.TabIndex = 4;
this.cbUseSynchronizationContext.Text = "Use Synchronization Context ";
this.cfTooltip.SetToolTip(this.cbUseSynchronizationContext, "Specifies whether to use the current synchronization context to choose the thread" +
" of execution. ");
this.cbUseSynchronizationContext.UseVisualStyleBackColor = true;
//
// cbConcurrencyMode
//
this.cbConcurrencyMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbConcurrencyMode.FormattingEnabled = true;
this.cbConcurrencyMode.Items.AddRange(new object[] {
"Single",
"Multiple",
"Reentrant"});
this.cbConcurrencyMode.Location = new System.Drawing.Point(139, 24);
this.cbConcurrencyMode.Name = "cbConcurrencyMode";
this.cbConcurrencyMode.Size = new System.Drawing.Size(154, 21);
this.cbConcurrencyMode.TabIndex = 1;
this.cfTooltip.SetToolTip(this.cbConcurrencyMode, "Determines whether a service supports one thread, multiple threads, or reentrant " +
"calls. ");
//
// cbInstanceContextMode
//
this.cbInstanceContextMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbInstanceContextMode.FormattingEnabled = true;
this.cbInstanceContextMode.Items.AddRange(new object[] {
"PerCall",
"PerSession",
"Single"});
this.cbInstanceContextMode.Location = new System.Drawing.Point(139, 51);
this.cbInstanceContextMode.Name = "cbInstanceContextMode";
this.cbInstanceContextMode.Size = new System.Drawing.Size(154, 21);
this.cbInstanceContextMode.TabIndex = 3;
this.cfTooltip.SetToolTip(this.cbInstanceContextMode, "Specifies the number of service instances available for handling calls that are c" +
"ontained in incoming messages. ");
//
// cbGenerateSvcFile
//
this.cbGenerateSvcFile.AutoSize = true;
this.cbGenerateSvcFile.Location = new System.Drawing.Point(320, 79);
this.cbGenerateSvcFile.Name = "cbGenerateSvcFile";
this.cbGenerateSvcFile.Size = new System.Drawing.Size(109, 17);
this.cbGenerateSvcFile.TabIndex = 6;
this.cbGenerateSvcFile.Text = "Generate .svc file";
this.cfTooltip.SetToolTip(this.cbGenerateSvcFile, "Determines if a .svc file will be generated for hosting in IIS and WAS.");
this.cbGenerateSvcFile.UseVisualStyleBackColor = true;
//
// cbFormatSoapActions
//
this.cbFormatSoapActions.AutoSize = true;
this.cbFormatSoapActions.Location = new System.Drawing.Point(144, 27);
this.cbFormatSoapActions.Name = "cbFormatSoapActions";
this.cbFormatSoapActions.Size = new System.Drawing.Size(128, 17);
this.cbFormatSoapActions.TabIndex = 3;
this.cbFormatSoapActions.Text = "Format SOAP Actions";
this.cfTooltip.SetToolTip(this.cbFormatSoapActions, "Applies the standard WCF format for SOAP actions: <namespace>/<service>/<operatio" +
"n>[Response]");
this.cbFormatSoapActions.UseVisualStyleBackColor = true;
//
// gbServiceMethodImplementation
//
this.gbServiceMethodImplementation.Controls.Add(this.rbAbstractMethods);
this.gbServiceMethodImplementation.Controls.Add(this.rbPartialClassMethodCalls);
this.gbServiceMethodImplementation.Controls.Add(this.rbNotImplementedException);
this.gbServiceMethodImplementation.Location = new System.Drawing.Point(8, 276);
this.gbServiceMethodImplementation.Name = "gbServiceMethodImplementation";
this.gbServiceMethodImplementation.Size = new System.Drawing.Size(536, 95);
this.gbServiceMethodImplementation.TabIndex = 4;
this.gbServiceMethodImplementation.TabStop = false;
this.gbServiceMethodImplementation.Text = "Service Method Implementation";
this.cfTooltip.SetToolTip(this.gbServiceMethodImplementation, "Determines if the operation methods on the service class will throw a NotImplemen" +
"tedException, call an implementation method in a partial class, or will be defin" +
"ed as abstract methods.");
//
// rbAbstractMethods
//
this.rbAbstractMethods.AutoSize = true;
this.rbAbstractMethods.Location = new System.Drawing.Point(16, 66);
this.rbAbstractMethods.Name = "rbAbstractMethods";
this.rbAbstractMethods.Size = new System.Drawing.Size(501, 17);
this.rbAbstractMethods.TabIndex = 2;
this.rbAbstractMethods.Text = "Generate an abstract service class and abstract methods that can be implemented i" +
"n a derived class.";
this.rbAbstractMethods.UseVisualStyleBackColor = true;
//
// rbPartialClassMethodCalls
//
this.rbPartialClassMethodCalls.AutoSize = true;
this.rbPartialClassMethodCalls.Location = new System.Drawing.Point(16, 43);
this.rbPartialClassMethodCalls.Name = "rbPartialClassMethodCalls";
this.rbPartialClassMethodCalls.Size = new System.Drawing.Size(497, 17);
this.rbPartialClassMethodCalls.TabIndex = 1;
this.rbPartialClassMethodCalls.Text = "Generate a partial service class with calls to partial methods that must be imple" +
"mented in another file.";
this.rbPartialClassMethodCalls.UseVisualStyleBackColor = true;
//
// rbNotImplementedException
//
this.rbNotImplementedException.AutoSize = true;
this.rbNotImplementedException.Checked = true;
this.rbNotImplementedException.Location = new System.Drawing.Point(16, 20);
this.rbNotImplementedException.Name = "rbNotImplementedException";
this.rbNotImplementedException.Size = new System.Drawing.Size(491, 17);
this.rbNotImplementedException.TabIndex = 0;
this.rbNotImplementedException.TabStop = true;
this.rbNotImplementedException.Text = "Generate a regular service class with methods that throw a NotImplementedExceptio" +
"n in their body.";
this.rbNotImplementedException.UseVisualStyleBackColor = true;
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.White;
this.panel1.Controls.Add(this.pbWscf);
this.panel1.Controls.Add(this.pbWizard);
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(648, 40);
this.panel1.TabIndex = 10;
//
// pbWizard
//
this.pbWizard.Image = ((System.Drawing.Image)(resources.GetObject("pbWizard.Image")));
this.pbWizard.Location = new System.Drawing.Point(10, 3);
this.pbWizard.Name = "pbWizard";
this.pbWizard.Size = new System.Drawing.Size(40, 32);
this.pbWizard.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pbWizard.TabIndex = 10;
this.pbWizard.TabStop = false;
//
// groupBox5
//
this.groupBox5.Controls.Add(this.cbWsdlLocation);
this.groupBox5.Controls.Add(this.bnBrowse);
this.groupBox5.Controls.Add(this.label4);
this.groupBox5.Location = new System.Drawing.Point(8, 48);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(553, 49);
this.groupBox5.TabIndex = 0;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Contract information ";
//
// cbWsdlLocation
//
this.cbWsdlLocation.Enabled = false;
this.cbWsdlLocation.Location = new System.Drawing.Point(96, 18);
this.cbWsdlLocation.MaxDropDownItems = 10;
this.cbWsdlLocation.Name = "cbWsdlLocation";
this.cbWsdlLocation.Size = new System.Drawing.Size(404, 21);
this.cbWsdlLocation.TabIndex = 1;
this.cbWsdlLocation.SelectedIndexChanged += new System.EventHandler(this.cbWsdlLocation_SelectedIndexChanged);
this.cbWsdlLocation.TextChanged += new System.EventHandler(this.tbWSDLLocation_TextChanged);
this.cbWsdlLocation.MouseMove += new System.Windows.Forms.MouseEventHandler(this.cbWsdlLocation_MouseMove);
//
// bnBrowse
//
this.bnBrowse.Location = new System.Drawing.Point(512, 17);
this.bnBrowse.Name = "bnBrowse";
this.bnBrowse.Size = new System.Drawing.Size(32, 23);
this.bnBrowse.TabIndex = 2;
this.bnBrowse.Text = "...";
this.bnBrowse.Click += new System.EventHandler(this.bnBrowse_Click);
//
// label4
//
this.label4.Location = new System.Drawing.Point(8, 21);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(87, 20);
this.label4.TabIndex = 0;
this.label4.Text = "WSDL location:";
//
// openFileDialogWSDL
//
this.openFileDialogWSDL.Filter = "WSDL files|*.wsdl|All Files|*.*";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.gbServiceMethodImplementation);
this.groupBox1.Controls.Add(this.gbServiceBehavior);
this.groupBox1.Controls.Add(this.rbServer);
this.groupBox1.Controls.Add(this.groupBox4);
this.groupBox1.Controls.Add(this.rbClient);
this.groupBox1.Location = new System.Drawing.Point(8, 103);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(553, 377);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Code generation ";
//
// gbServiceBehavior
//
this.gbServiceBehavior.Controls.Add(this.cbGenerateSvcFile);
this.gbServiceBehavior.Controls.Add(this.cbEnableWsdlEndpoint);
this.gbServiceBehavior.Controls.Add(this.cbUseSynchronizationContext);
this.gbServiceBehavior.Controls.Add(this.label3);
this.gbServiceBehavior.Controls.Add(this.label5);
this.gbServiceBehavior.Controls.Add(this.cbConcurrencyMode);
this.gbServiceBehavior.Controls.Add(this.cbInstanceContextMode);
this.gbServiceBehavior.Enabled = false;
this.gbServiceBehavior.Location = new System.Drawing.Point(8, 162);
this.gbServiceBehavior.Name = "gbServiceBehavior";
this.gbServiceBehavior.Size = new System.Drawing.Size(536, 107);
this.gbServiceBehavior.TabIndex = 3;
this.gbServiceBehavior.TabStop = false;
this.gbServiceBehavior.Text = "Service Behavior";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(16, 27);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(97, 13);
this.label3.TabIndex = 0;
this.label3.Text = "Concurrency Mode";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(16, 54);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(117, 13);
this.label5.TabIndex = 2;
this.label5.Text = "Instance Context Mode";
//
// groupBox4
//
this.groupBox4.Controls.Add(this.cbVirtualProperties);
this.groupBox4.Controls.Add(this.cbGenericList);
this.groupBox4.Controls.Add(this.cbAsync);
this.groupBox4.Controls.Add(this.cbDataBinding);
this.groupBox4.Controls.Add(this.cbFormatSoapActions);
this.groupBox4.Controls.Add(this.cbOrderIds);
this.groupBox4.Controls.Add(this.cbCollections);
this.groupBox4.Controls.Add(this.cbMultipleFiles);
this.groupBox4.Controls.Add(this.cbProperties);
this.groupBox4.Controls.Add(this.cbAdjustCasing);
this.groupBox4.Location = new System.Drawing.Point(8, 49);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(536, 107);
this.groupBox4.TabIndex = 2;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Options ";
//
// cbVirtualProperties
//
this.cbVirtualProperties.Location = new System.Drawing.Point(16, 50);
this.cbVirtualProperties.Name = "cbVirtualProperties";
this.cbVirtualProperties.Size = new System.Drawing.Size(115, 23);
this.cbVirtualProperties.TabIndex = 1;
this.cbVirtualProperties.Text = "Virtual properties";
this.cfTooltip.SetToolTip(this.cbVirtualProperties, "If properties are generated mark them as virtual.");
this.cbVirtualProperties.CheckedChanged += new System.EventHandler(this.cbVirtualProperties_CheckedChanged);
//
// WebServiceCodeGenDialogNew
//
this.AcceptButton = this.button1;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.button2;
this.ClientSize = new System.Drawing.Size(570, 611);
this.Controls.Add(this.cbOverwrite);
this.Controls.Add(this.groupBox5);
this.Controls.Add(this.panel1);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.cbSettings);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "WebServiceCodeGenDialogNew";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "WSCF.blue Code Generation 1.0 ";
this.Closed += new System.EventHandler(this.WebServiceCodeGenOptions_Closed);
this.Load += new System.EventHandler(this.WebServiceCodeGenOptions_Load);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pbWscf)).EndInit();
this.gbServiceMethodImplementation.ResumeLayout(false);
this.gbServiceMethodImplementation.PerformLayout();
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pbWizard)).EndInit();
this.groupBox5.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.gbServiceBehavior.ResumeLayout(false);
this.gbServiceBehavior.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private void button1_Click(object sender, EventArgs e)
{
if(rbClient.Checked || rbServer.Checked)
{
if(tbDestinationNamespace.Text.Length == 0 ||
tbDestinationFilename.Text.Length == 0 ||
!ValidationHelper.IsWindowsFileName(tbDestinationFilename.Text) ||
!ValidationHelper.IsDotNetNamespace(tbDestinationNamespace.Text) ||
cbWsdlLocation.Text.Length == 0)
{
this.DialogResult = DialogResult.None;
button1.DialogResult = DialogResult.None;
MessageBox.Show("Sorry, please enter valid values.",
"Web Services Contract-First code generation", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
else
{
this.DialogResult = DialogResult.OK;
this.Close();
}
}
else
{
this.DialogResult = DialogResult.None;
button1.DialogResult = DialogResult.None;
MessageBox.Show("Please choose code generation options.",
"Web Services Contract-First code generation", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
private void WebServiceCodeGenOptions_Load(object sender, EventArgs e)
{
if(wsdlLocation.Length == 0)
{
cbWsdlLocation.Enabled = true;
cbWsdlLocation.Focus();
}
if(!cbWsdlLocation.Enabled) bnBrowse.Enabled = false;
cbConcurrencyMode.SelectedIndex = 0;
cbInstanceContextMode.SelectedIndex = 0;
LoadFormValues();
if(rbClient.Checked || rbServer.Checked) button1.Enabled = true;
isLoading = false;
gbServiceBehavior.DataBindings.Add("Enabled", rbServer, "Checked");
gbServiceMethodImplementation.DataBindings.Add("Enabled", rbServer, "Checked");
}
private void ttPicBox_Click(object sender, EventArgs e)
{
Process.Start("http://www.thinktecture.com/");
}
private void bnBrowse_Click(object sender, EventArgs e)
{
if(openFileDialogWSDL.ShowDialog() == DialogResult.OK)
{
AddWsdlFileToCache(openFileDialogWSDL.FileName);
}
}
private void SaveFormValues()
{
ConfigurationManager config = ConfigurationManager.GetConfigurationManager("WSCF05");
config.Write("ClientCode", rbClient.Checked.ToString());
config.Write("ServerCode", rbServer.Checked.ToString());
config.Write("Properties", cbProperties.Checked.ToString());
config.Write("VirtualProperties", cbVirtualProperties.Checked.ToString());
config.Write("FormatSoapActions", cbFormatSoapActions.Checked.ToString());
config.Write("Collections", cbCollections.Checked.ToString());
config.Write("GenericList", cbGenericList.Checked.ToString());
config.Write("DataBinding", cbDataBinding.Checked.ToString());
config.Write("OrderIdentifiers", cbOrderIds.Checked.ToString());
config.Write("AsyncMethods", cbAsync.Checked.ToString());
config.Write("MultipleFiles", cbMultipleFiles.Checked.ToString());
config.Write("AdjustCasing", cbAdjustCasing.Checked.ToString());
config.Write("ConcurrencyMode", cbConcurrencyMode.Text);
config.Write("InstanceContextMode", cbInstanceContextMode.Text);
config.Write("UseSynchronizationContext", cbUseSynchronizationContext.Checked.ToString());
config.Write("EnableWsdlEndpoint", cbEnableWsdlEndpoint.Checked.ToString());
config.Write("GenerateSvcFile", cbGenerateSvcFile.Checked.ToString());
config.Write("MethodImplementation", MethodImplementation.ToString());
config.Write("DestinationFilename", tbDestinationFilename.Text);
config.Write("DestinationNamespace", tbDestinationNamespace.Text);
config.Write("Overwrite", cbOverwrite.Checked.ToString());
// BDS: Modified the code to store the values pasted to the combo box.
if(cbWsdlLocation.SelectedItem != null)
{
config.Write("WSDLLocation",
wsdlFileCache[cbWsdlLocation.SelectedIndex].ToString());
wsdlPath = wsdlFileCache[cbWsdlLocation.SelectedIndex].ToString();
}
else
{
config.Write("WSDLLocation", cbWsdlLocation.Text);
wsdlPath = cbWsdlLocation.Text;
}
config.Write("RememberSettings", cbSettings.Checked.ToString());
string wsdlUrlsString = "";
// Add the current item.
if(cbWsdlLocation.SelectedItem == null)
{
string fname = AddWsdlFileToCache(cbWsdlLocation.Text);
}
foreach(string path in wsdlFileCache)
{
wsdlUrlsString += path + ";";
}
config.Write("WsdlUrls", wsdlUrlsString);
config.Persist();
}
private void LoadFormValues()
{
ConfigurationManager config = ConfigurationManager.GetConfigurationManager("WSCF05");
string wsdlUrls = config.Read("WsdlUrls");
//if (wsdlUrls.Length > 0)
//{
cbWsdlLocation.Items.Clear();
wsdlUrls = wsdlUrls.Trim(';');
string[] urls = wsdlUrls.Split(';');
// BDS: Changed this code to use new wsdl file cache.
for(int urlIndex = 0; urlIndex < urls.Length; urlIndex++)
{
string fname = AddWsdlFileToCache(urls[urlIndex]);
}
if(cbWsdlLocation.Items.Count > 0)
{
cbWsdlLocation.SelectedIndex = 0;
}
if(wsdlLocation.Length > 0)
{
if(!wsdlFileCache.Contains(wsdlLocation))
{
string fname = AddWsdlFileToCache(wsdlLocation);
}
else
{
int wsdlIndex = wsdlFileCache.IndexOf(wsdlLocation);
cbWsdlLocation.SelectedIndex = wsdlIndex;
}
}
//}
if (config.ReadBoolean("RememberSettings"))
{
cbSettings.Checked = config.ReadBoolean("RememberSettings");
rbClient.Checked = config.ReadBoolean("ClientCode");
rbServer.Checked = config.ReadBoolean("ServerCode");
cbProperties.Checked = config.ReadBoolean("Properties");
cbVirtualProperties.Checked = config.ReadBoolean("VirtualProperties");
cbFormatSoapActions.Checked = config.ReadBoolean("FormatSoapActions");
cbCollections.Checked = config.ReadBoolean("Collections");
cbGenericList.Checked = config.ReadBoolean("GenericList");
cbDataBinding.Checked = config.ReadBoolean("DataBinding");
cbOrderIds.Checked = config.ReadBoolean("OrderIdentifiers");
cbAsync.Checked = config.ReadBoolean("AsyncMethods");
cbMultipleFiles.Checked = config.ReadBoolean("MultipleFiles");
cbAdjustCasing.Checked = config.ReadBoolean("AdjustCasing");
cbConcurrencyMode.SelectedItem = config.Read("ConcurrencyMode", "Single");
cbInstanceContextMode.SelectedItem = config.Read("InstanceContextMode", "PerCall");
cbUseSynchronizationContext.Checked = config.ReadBoolean("UseSynchronizationContext");
cbEnableWsdlEndpoint.Checked = config.ReadBoolean("EnableWsdlEndpoint");
cbGenerateSvcFile.Checked = config.ReadBoolean("GenerateSvcFile");
string methodImplementationValue = config.Read("MethodImplementation", MethodImplementation.NotImplementedException.ToString());
MethodImplementation methodImplementation = (MethodImplementation)Enum.Parse(typeof(MethodImplementation), methodImplementationValue);
if (methodImplementation == MethodImplementation.NotImplementedException)
{
rbNotImplementedException.Checked = true;
}
if (methodImplementation == MethodImplementation.PartialClassMethodCalls)
{
rbPartialClassMethodCalls.Checked = true;
}
if (methodImplementation == MethodImplementation.AbstractMethods)
{
rbAbstractMethods.Checked = true;
}
tbDestinationFilename.Text = config.Read("DestinationFilename");
tbDestinationNamespace.Text = config.Read("DestinationNamespace");
cbOverwrite.Checked = config.ReadBoolean("Overwrite");
}
}
private void ttPicBox_MouseEnter(object sender, EventArgs e)
{
Cursor.Current = Cursors.Hand;
}
private void ttPicBox_MouseLeave(object sender, EventArgs e)
{
Cursor.Current = Cursors.Default;
}
private void ttPicBox_MouseMove(object sender, MouseEventArgs e)
{
}
private void tbWSDLLocation_TextChanged(object sender, EventArgs e)
{
}
private void WebServiceCodeGenOptions_Closed(object sender, EventArgs e)
{
// BDS: Save the values only if the OK button is clicked.
if(this.DialogResult == DialogResult.OK)
{
SaveFormValues();
}
}
private void cbWsdlLocation_SelectedIndexChanged(object sender, System.EventArgs e)
{
}
/// <summary>
/// Disply the location of the WSDL when moving the mouse over the combo box.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">Event arguments.</param>
private void cbWsdlLocation_MouseMove(object sender, MouseEventArgs e)
{
if(cbWsdlLocation.SelectedIndex >= 0)
{
cfTooltip.SetToolTip(cbWsdlLocation,
wsdlFileCache[cbWsdlLocation.SelectedIndex].ToString());
}
}
/// <summary>
/// Adds a wsdl file info to the wsdl file cache.
/// </summary>
/// <param name="path">Path of the wsdl file to add.</param>
/// <returns>A string indicating the name of the wsdl file.</returns>
/// <author>BDS - thinktecture</author>
private string AddWsdlFileToCache(string path)
{
if(path.LastIndexOf("\\") > 0 && path.ToLower().EndsWith(".wsdl"))
{
if(wsdlFileCache.Count == 10)
{
wsdlFileCache.RemoveAt(0);
cbWsdlLocation.Items.RemoveAt(0);
}
string fname = path.Substring(path.LastIndexOf("\\") + 1);
wsdlFileCache.Add(path);
cbWsdlLocation.SelectedIndex = cbWsdlLocation.Items.Add(fname);
return fname;
}
return "";
}
private string GetFileNameFromPath(string path)
{
string fname = "";
if(path.LastIndexOf("\\") < path.Length - 1)
{
fname = path.Substring(path.LastIndexOf("\\") + 1);
}
return fname;
}
private void cbOverwrite_CheckedChanged(object sender, System.EventArgs e)
{
if (!isLoading)
{
if (cbOverwrite.Checked)
{
if (MessageBox.Show(this,
"This will overwrite the existing files in the project. Are you sure you want to enable this option anyway?",
"Web Services Contract-First code generation",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.No)
{
cbOverwrite.Checked = false;
}
}
}
}
private void pbWscf_Click(object sender, System.EventArgs e)
{
Process.Start("http://www.thinktecture.com/");
}
public bool ServiceCode
{
get { return rbServer.Checked; }
}
public bool ClientCode
{
get { return rbClient.Checked; }
}
public string DestinationFilename
{
get { return tbDestinationFilename.Text; }
set { tbDestinationFilename.Text = value; }
}
public string DestinationNamespace
{
get { return tbDestinationNamespace.Text; }
set { tbDestinationNamespace.Text = value; }
}
public bool GenerateProperties
{
get { return cbProperties.Checked; }
}
public bool VirtualProperties
{
get { return cbVirtualProperties.Checked; }
}
public bool FormatSoapActions
{
get { return cbFormatSoapActions.Checked; }
}
public bool Collections
{
get { return cbCollections.Checked; }
}
public string WsdlLocation
{
get { return cbWsdlLocation.Text; }
set { wsdlLocation = value; }
}
public bool ExternalFile
{
get { return externalFile; }
}
public bool GenerateMultipleFiles
{
get { return cbMultipleFiles.Checked; }
}
public string WsdlPath
{
get { return this.wsdlPath; }
}
public bool Overwrite
{
get { return this.cbOverwrite.Checked; }
}
public bool ChangeCasing
{
get { return this.cbAdjustCasing.Checked; }
}
public bool EnableDataBinding
{
get { return this.cbDataBinding.Checked; }
}
public bool OrderIdentifiers
{
get { return this.cbOrderIds.Checked; }
}
public bool AsyncMethods
{
get { return this.cbAsync.Checked; }
}
public bool GenericList
{
get { return this.cbGenericList.Checked; }
}
public bool EnabledWsdlEndpoint
{
get { return this.cbEnableWsdlEndpoint.Checked; }
}
public string InstanceContextMode
{
get { return cbInstanceContextMode.Text; }
}
public string ConcurrencyMode
{
get { return cbConcurrencyMode.Text; }
}
public bool UseSynchronizationContext
{
get { return cbUseSynchronizationContext.Checked; }
}
public bool GenerateSvcFile
{
get { return cbGenerateSvcFile.Checked; }
}
public MethodImplementation MethodImplementation
{
get
{
if (rbNotImplementedException.Checked)
{
return MethodImplementation.NotImplementedException;
}
if (rbPartialClassMethodCalls.Checked)
{
return MethodImplementation.PartialClassMethodCalls;
}
if (rbAbstractMethods.Checked)
{
return MethodImplementation.AbstractMethods;
}
return MethodImplementation.NotImplementedException;
}
}
private void cbDataBinding_CheckedChanged(object sender, EventArgs e)
{
if (cbDataBinding.Checked)
{
cbProperties.Checked = true;
cbProperties.Enabled = false;
}
else
{
if (!cbVirtualProperties.Checked)
{
cbProperties.Enabled = true;
}
}
}
private void cbVirtualProperties_CheckedChanged(object sender, EventArgs e)
{
if (cbVirtualProperties.Checked)
{
cbProperties.Checked = true;
cbProperties.Enabled = false;
}
else
{
if (!cbDataBinding.Checked)
{
cbProperties.Enabled = true;
}
}
}
private void cbSettings_CheckedChanged(object sender, EventArgs e)
{
}
private void cbCollections_CheckedChanged(object sender, EventArgs e)
{
if (cbGenericList.Checked)
{
cbGenericList.Checked = !cbCollections.Checked;
}
}
private void cbGenericList_CheckedChanged(object sender, EventArgs e)
{
if (cbCollections.Checked)
{
cbCollections.Checked = !cbGenericList.Checked;
}
}
private void rbClient_CheckedChanged(object sender, EventArgs e)
{
button1.Enabled = true;
}
private void rbServer_CheckedChanged(object sender, EventArgs e)
{
button1.Enabled = true;
}
}
}
| |
//Copyright 2010-2015 Joshua Scoggins. All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are
//permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
//THIS SOFTWARE IS PROVIDED BY Joshua Scoggins ``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 Joshua Scoggins OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
//CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
//ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
//ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//The views and conclusions contained in the software and documentation are those of the
//authors and should not be interpreted as representing official policies, either expressed
//or implied, of Joshua Scoggins.
//
//Define the MATH_FORMULA use flag
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Libraries.Extensions
{
#if MATH_FORMULA
public static partial class Extensions
{
public static decimal LinearFibonacci(this decimal value)
{
if(value == 0.0M)
return 0.0M;
if(value == 1.0M)
return 1.0M;
decimal v0 = 0.0M;
decimal v1 = 1.0M;
for(decimal factor = 2; factor <= value; factor++)
{
decimal result = v0 + v1;
if((result + 1) > value)
return result;
else
{
v0 = v1;
v1 = result;
}
}
return v1;
}
public static double LinearFibonacci(this double value)
{
if(value == 0.0)
return 0.0;
if(value == 1.0)
return 1.0;
double v0 = 0.0;
double v1 = 1.0;
for(double factor = 2; factor <= value; factor++)
{
double result = v0 + v1;
if((result + 1) > value)
return result;
else
{
v0 = v1;
v1 = result;
}
}
return v1;
}
public static float LinearFibonacci(this float value)
{
if(value == 0.0f)
return 0.0f;
if(value == 1.0)
return 1.0f;
float v0 = 0.0f;
float v1 = 1.0f;
for(float factor = 2; factor <= value; factor++)
{
float result = v0 + v1;
if((result + 1) > value)
return result;
else
{
v0 = v1;
v1 = result;
}
}
return v1;
}
public static long LinearFibonacci(this long value)
{
if(value == 0L)
return 0L;
if(value == 1L)
return 1L;
long v0 = 0L;
long v1 = 1L;
for(long factor = 2; factor <= value; factor++)
{
long result = v0 + v1;
if((result + 1) > value)
return result;
else
{
v0 = v1;
v1 = result;
}
}
return v1;
}
public static ulong LinearFibonacci(this ulong value)
{
if(value == 0L)
return 0L;
if(value == 1L)
return 1L;
ulong v0 = 0L;
ulong v1 = 1L;
for(ulong factor = 2; factor <= value; factor++)
{
ulong result = v0 + v1;
if((result + 1) > value)
return result;
else
{
v0 = v1;
v1 = result;
}
}
return v1;
}
public static int LinearFibonacci(this int value)
{
if(value == 0)
return 0;
if(value == 1)
return 1;
int v0 = 0;
int v1 = 1;
for(int factor = 2; factor <= value; factor++)
{
int result = v0 + v1;
if((result + 1) > value)
return result;
else
{
v0 = v1;
v1 = result;
}
}
return v1;
}
public static uint LinearFibonacci(this uint value)
{
if(value == 0)
return 0;
if(value == 1)
return 1;
uint v0 = 0;
uint v1 = 1;
for(uint factor = 2; factor <= value; factor++)
{
uint result = v0 + v1;
if((result + 1) > value)
return result;
else
{
v0 = v1;
v1 = result;
}
}
return v1;
}
public static decimal LinearFactorial(this decimal value)
{
if(value == 1.0M)
return value;
decimal _base = 1.0M;
decimal curr = _base;
for(decimal factor = _base; factor <= value;
curr = (curr * factor), factor++);
return curr;
}
public static double LinearFactorial(this double value)
{
if(value == 1.0)
return value;
double _base = 1.0;
double curr = _base;
for(double factor = _base; factor <= value;
curr = (curr * factor), factor++);
return curr;
}
public static float LinearFactorial(this float value)
{
if(value == 1.0f)
return value;
float _base = 1.0f;
float curr = _base;
for(float factor = _base; factor <= value;
curr = (curr * factor), factor++);
return curr;
}
public static long LinearFactorial(this long value)
{
if(value == 1L)
return value;
long _base = 1L;
long curr = _base;
for(long factor = _base; factor <= value;
curr = (curr * factor), factor++);
return curr;
}
public static ulong LinearFactorial(this ulong value)
{
if(value == 1L)
return value;
ulong _base = 1L;
ulong curr = _base;
for(ulong factor = _base; factor <= value;
curr = (curr * factor), factor++);
return curr;
}
public static int LinearFactorial(this int value)
{
if(value == 1)
return value;
int _base = 1;
int curr = _base;
for(int factor = _base; factor <= value;
curr = (curr * factor), factor++);
return curr;
}
public static uint LinearFactorial(this uint value)
{
if(value == 1)
return value;
uint _base = 1;
uint curr = _base;
for(uint factor = _base; factor <= value;
curr = (curr * factor), factor++);
return curr;
}
public static Func<decimal,decimal,decimal> FirstDerivative(this Func<decimal,decimal> fn)
{
return (x,h) => (1.0M / (2.0M * h)) * ((fn(x + h) - fn(x - h)));
}
public static Func<double,double,double> FirstDerivative(this Func<double,double> fn)
{
return (x,h) => (1.0 / (2.0 * h)) * ((fn(x + h) - fn(x - h)));
}
public static Func<float,float,float> FirstDerivative(this Func<float,float> fn)
{
return (x,h) => (1.0f / (2.0f * h)) * ((fn(x + h) - fn(x - h)));
}
public static Func<long,long,long> FirstDerivative(this Func<long,long> fn)
{
return (x,h) => (1L / (2L * h)) * ((fn(x + h) - fn(x - h)));
}
public static Func<ulong,ulong,ulong> FirstDerivative(this Func<ulong,ulong> fn)
{
return (x,h) => (1L / (2L * h)) * ((fn(x + h) - fn(x - h)));
}
public static Func<int,int,int> FirstDerivative(this Func<int,int> fn)
{
return (x,h) => (1 / (2 * h)) * ((fn(x + h) - fn(x - h)));
}
public static Func<uint,uint,uint> FirstDerivative(this Func<uint,uint> fn)
{
return (x,h) => (1 / (2 * h)) * ((fn(x + h) - fn(x - h)));
}
public static Func<decimal,decimal,decimal> SecondDerivative(this Func<decimal,decimal> fn)
{
return (x,h) => ((1.0M / (h * h)) * ((fn(x + h) - (2.0M * fn(x))) + fn(x - h)));
}
public static Func<double,double,double> SecondDerivative(this Func<double,double> fn)
{
return (x,h) => ((1.0 / (h * h)) * ((fn(x + h) - (2.0 * fn(x))) + fn(x - h)));
}
public static Func<float,float,float> SecondDerivative(this Func<float,float> fn)
{
return (x,h) => ((1.0f / (h * h)) * ((fn(x + h) - (2.0f * fn(x))) + fn(x - h)));
}
public static Func<long,long,long> SecondDerivative(this Func<long,long> fn)
{
return (x,h) => ((1L / (h * h)) * ((fn(x + h) - (2L * fn(x))) + fn(x - h)));
}
public static Func<ulong,ulong,ulong> SecondDerivative(this Func<ulong,ulong> fn)
{
return (x,h) => ((1L / (h * h)) * ((fn(x + h) - (2L * fn(x))) + fn(x - h)));
}
public static Func<int,int,int> SecondDerivative(this Func<int,int> fn)
{
return (x,h) => ((1 / (h * h)) * ((fn(x + h) - (2 * fn(x))) + fn(x - h)));
}
public static Func<uint,uint,uint> SecondDerivative(this Func<uint,uint> fn)
{
return (x,h) => ((1 / (h * h)) * ((fn(x + h) - (2 * fn(x))) + fn(x - h)));
}
}
#endif
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Invio.Xunit;
using Xunit;
namespace Invio.Immutable {
[UnitTest]
public sealed class SetPropertyHandlerTests : EnumerablePropertyHandlerTestsBase {
private static ISet<PropertyInfo> properties { get; }
private static Random random { get; }
static SetPropertyHandlerTests() {
var parent = typeof(FakeImmutable);
properties = ImmutableHashSet.Create(
parent.GetProperty(nameof(FakeImmutable.Array)),
parent.GetProperty(nameof(FakeImmutable.Enumerable)),
parent.GetProperty(nameof(FakeImmutable.Set)),
parent.GetProperty(nameof(FakeImmutable.ImmutableSet))
);
random = new Random();
}
public static IEnumerable<object[]> MatchingMemberData {
get {
yield return new object[] {
nameof(FakeImmutable.Array),
new object[] { "foo", "bar" },
new string[] { "foo", "bar" }
};
yield return new object[] {
nameof(FakeImmutable.Enumerable),
ImmutableList.Create<object>(String.Empty, 45m, DateTime.MinValue),
new object[] { 45m, String.Empty, DateTime.MinValue }
};
yield return new object[] {
nameof(FakeImmutable.Set),
new HashSet<string> { "12345", "Hello, World", "Bananas", "Bananas" },
ImmutableHashSet.Create("12345", "Hello, World", "Bananas", "12345")
};
yield return new object[] {
nameof(FakeImmutable.Set),
ImmutableHashSet.Create(new string[] { "foo", null }),
ImmutableHashSet.Create(new string[] { null, null, "foo" })
};
var guid = Guid.NewGuid();
yield return new object[] {
nameof(FakeImmutable.ImmutableSet),
ImmutableSortedSet.Create(guid, Guid.Empty),
ImmutableSortedSet.Create(Guid.Empty, guid)
};
}
}
[Theory]
[MemberData(nameof(MatchingMemberData))]
public void GetPropertyValueHashCode_Matches(
String propertyName,
IEnumerable leftPropertyValue,
IEnumerable rightPropertyValue) {
// Arrange
var handler = this.CreateHandler(propertyName);
var leftFake = this.NextFake().SetPropertyValue(propertyName, leftPropertyValue);
var rightFake = this.NextFake().SetPropertyValue(propertyName, rightPropertyValue);
// Act
var leftHashCode = handler.GetPropertyValueHashCode(leftFake);
var rightHashCode = handler.GetPropertyValueHashCode(rightFake);
// Assert
Assert.Equal(leftHashCode, rightHashCode);
}
[Theory]
[MemberData(nameof(MatchingMemberData))]
public void ArePropertyValuesEqual_Matches(
String propertyName,
IEnumerable leftPropertyValue,
IEnumerable rightPropertyValue) {
// Arrange
var handler = this.CreateHandler(propertyName);
var leftFake = this.NextFake().SetPropertyValue(propertyName, leftPropertyValue);
var rightFake = this.NextFake().SetPropertyValue(propertyName, rightPropertyValue);
// Act
var areEqual = handler.ArePropertyValuesEqual(leftFake, rightFake);
// Assert
Assert.True(areEqual);
}
public static IEnumerable<object[]> ArePropertyValuesEqual_MismatchedValues_MemberData {
get {
// Case of 'foo' differs
yield return new object[] {
nameof(FakeImmutable.Array),
new object[] { "foo", "bar" },
new string[] { "FOO", "bar" }
};
// One of the values is null
yield return new object[] {
nameof(FakeImmutable.Array),
new object[] { "foo", "bar" },
new string[] { null, "bar" }
};
// DateTime.MinValue vs. DateTime.MaxValue
yield return new object[] {
nameof(FakeImmutable.Enumerable),
ImmutableList.Create<object>(String.Empty, 45m, DateTime.MinValue),
new object[] { String.Empty, 45m, DateTime.MaxValue }
};
// 12345 => 54321
yield return new object[] {
nameof(FakeImmutable.Set),
new HashSet<string> { "12345", "Hello, World", "Bananas" },
ImmutableHashSet.Create("54321", "Hello, World", "Bananas")
};
// Distinct Guids
yield return new object[] {
nameof(FakeImmutable.ImmutableSet),
ImmutableSortedSet.Create(Guid.NewGuid(), Guid.Empty),
ImmutableSortedSet.Create(Guid.Empty, Guid.NewGuid())
};
}
}
[Theory]
[MemberData(nameof(ArePropertyValuesEqual_MismatchedValues_MemberData))]
public void ArePropertyValuesEqual_MismatchedValues(
String propertyName,
IEnumerable leftPropertyValue,
IEnumerable rightPropertyValue) {
// Arrange
var handler = this.CreateHandler(propertyName);
var leftFake = this.NextFake().SetPropertyValue(propertyName, leftPropertyValue);
var rightFake = this.NextFake().SetPropertyValue(propertyName, rightPropertyValue);
// Act
var areEqual = handler.ArePropertyValuesEqual(leftFake, rightFake);
// Assert
Assert.False(areEqual);
}
public static IEnumerable<object[]> ArePropertyValuesEqual_MismatchedSize_MemberData {
get {
// Trailing duplicate on left
yield return new object[] {
nameof(FakeImmutable.Array),
new object[] { "foo", "bar", "biz" },
new string[] { "foo", "bar" }
};
// Duplicate of 'foo' on right
yield return new object[] {
nameof(FakeImmutable.Array),
new object[] { "foo", "bar" },
new string[] { "foo", "bar", "foo" }
};
// Trailing duplicate on right
yield return new object[] {
nameof(FakeImmutable.Array),
new object[] { "foo", "bar" },
new string[] { "foo", "bar", "biz" }
};
// Leading duplicate on right
yield return new object[] {
nameof(FakeImmutable.Enumerable),
ImmutableList.Create<object>(String.Empty, 45m, DateTime.MinValue),
new object[] { String.Empty, String.Empty, 45m, DateTime.MinValue }
};
// Jagged on left
yield return new object[] {
nameof(FakeImmutable.Set),
new HashSet<string> { "12345", "Hello, World", "Bananas", "Apples" },
ImmutableSortedSet.Create<string>("12345", "Hello, World", "Bananas" )
};
// Jagged on right
var guid = Guid.NewGuid();
yield return new object[] {
nameof(FakeImmutable.ImmutableSet),
ImmutableHashSet.Create(Guid.Empty, guid),
ImmutableSortedSet.Create(Guid.NewGuid(), Guid.Empty, guid)
};
}
}
[Theory]
[MemberData(nameof(ArePropertyValuesEqual_MismatchedSize_MemberData))]
public void ArePropertyValuesEqual_MismatchedSize(
String propertyName,
IEnumerable leftPropertyValue,
IEnumerable rightPropertyValue) {
// Arrange
var handler = this.CreateHandler(propertyName);
var leftFake = this.NextFake().SetPropertyValue(propertyName, leftPropertyValue);
var rightFake = this.NextFake().SetPropertyValue(propertyName, rightPropertyValue);
// Act
var areEqual = handler.ArePropertyValuesEqual(leftFake, rightFake);
// Assert
Assert.False(areEqual);
}
protected override PropertyInfo NextValidPropertyInfo() {
return
properties
.Skip(random.Next(0, properties.Count))
.First();
}
protected override object NextParent() {
return this.NextFake();
}
private FakeImmutable NextFake() {
return new FakeImmutable(
new object[] { new object() },
ImmutableList.Create(DateTime.UtcNow),
new HashSet<string> { Guid.NewGuid().ToString(), Guid.NewGuid().ToString() },
ImmutableHashSet.Create(Guid.NewGuid())
);
}
private IPropertyHandler CreateHandler(string propertyName) {
return this.CreateHandler(typeof(FakeImmutable).GetProperty(propertyName));
}
protected override IPropertyHandler CreateHandler(PropertyInfo property) {
return new SetPropertyHandler(property);
}
private sealed class FakeImmutable : ImmutableBase<FakeImmutable> {
public object[] Array { get; }
public IEnumerable Enumerable { get; }
public ISet<string> Set { get; }
public IImmutableSet<Guid> ImmutableSet { get; }
public FakeImmutable(
object[] array = default(object[]),
IEnumerable enumerable = default(IEnumerable),
ISet<string> set = default(ISet<string>),
IImmutableSet<Guid> immutableSet = default(IImmutableSet<Guid>)) {
this.Array = array;
this.Enumerable = enumerable;
this.Set = set;
this.ImmutableSet = immutableSet;
}
public FakeImmutable SetPropertyValue(String propertyName, object propertyValue) {
return this.SetPropertyValueImpl(propertyName, propertyValue);
}
}
}
}
| |
/*
* 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;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
// using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Framework.Capabilities
{
/// <summary>
/// XXX Probably not a particularly nice way of allow us to get the scene presence from the scene (chiefly so that
/// we can popup a message on the user's client if the inventory service has permanently failed). But I didn't want
/// to just pass the whole Scene into CAPS.
/// </summary>
public delegate IClientAPI GetClientDelegate(UUID agentID);
public class Caps
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_httpListenerHostName;
private uint m_httpListenPort;
/// <summary>
/// This is the uuid portion of every CAPS path. It is used to make capability urls private to the requester.
/// </summary>
private string m_capsObjectPath;
public string CapsObjectPath { get { return m_capsObjectPath; } }
private CapsHandlers m_capsHandlers;
private Dictionary<string, PollServiceEventArgs> m_pollServiceHandlers
= new Dictionary<string, PollServiceEventArgs>();
private Dictionary<string, string> m_externalCapsHandlers = new Dictionary<string, string>();
private IHttpServer m_httpListener;
private UUID m_agentID;
private string m_regionName;
public UUID AgentID
{
get { return m_agentID; }
}
public string RegionName
{
get { return m_regionName; }
}
public string HostName
{
get { return m_httpListenerHostName; }
}
public uint Port
{
get { return m_httpListenPort; }
}
public IHttpServer HttpListener
{
get { return m_httpListener; }
}
public bool SSLCaps
{
get { return m_httpListener.UseSSL; }
}
public string SSLCommonName
{
get { return m_httpListener.SSLCommonName; }
}
public CapsHandlers CapsHandlers
{
get { return m_capsHandlers; }
}
public Dictionary<string, string> ExternalCapsHandlers
{
get { return m_externalCapsHandlers; }
}
public Caps(IHttpServer httpServer, string httpListen, uint httpPort, string capsPath,
UUID agent, string regionName)
{
m_capsObjectPath = capsPath;
m_httpListener = httpServer;
m_httpListenerHostName = httpListen;
m_httpListenPort = httpPort;
if (httpServer != null && httpServer.UseSSL)
{
m_httpListenPort = httpServer.SSLPort;
httpListen = httpServer.SSLCommonName;
httpPort = httpServer.SSLPort;
}
m_agentID = agent;
m_capsHandlers = new CapsHandlers(httpServer, httpListen, httpPort, (httpServer == null) ? false : httpServer.UseSSL);
m_regionName = regionName;
}
/// <summary>
/// Register a handler. This allows modules to register handlers.
/// </summary>
/// <param name="capName"></param>
/// <param name="handler"></param>
public void RegisterHandler(string capName, IRequestHandler handler)
{
//m_log.DebugFormat("[CAPS]: Registering handler for \"{0}\": path {1}", capName, handler.Path);
m_capsHandlers[capName] = handler;
}
public void RegisterPollHandler(string capName, PollServiceEventArgs pollServiceHandler)
{
// m_log.DebugFormat(
// "[CAPS]: Registering handler with name {0}, url {1} for {2}",
// capName, pollServiceHandler.Url, m_agentID, m_regionName);
m_pollServiceHandlers.Add(capName, pollServiceHandler);
m_httpListener.AddPollServiceHTTPHandler(pollServiceHandler.Url, pollServiceHandler);
// uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port;
// string protocol = "http";
// string hostName = m_httpListenerHostName;
//
// if (MainServer.Instance.UseSSL)
// {
// hostName = MainServer.Instance.SSLCommonName;
// port = MainServer.Instance.SSLPort;
// protocol = "https";
// }
// RegisterHandler(
// capName, String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, pollServiceHandler.Url));
}
/// <summary>
/// Register an external handler. The service for this capability is somewhere else
/// given by the URL.
/// </summary>
/// <param name="capsName"></param>
/// <param name="url"></param>
public void RegisterHandler(string capsName, string url)
{
m_externalCapsHandlers.Add(capsName, url);
}
/// <summary>
/// Remove all CAPS service handlers.
/// </summary>
public void DeregisterHandlers()
{
foreach (string capsName in m_capsHandlers.Caps)
{
m_capsHandlers.Remove(capsName);
}
foreach (PollServiceEventArgs handler in m_pollServiceHandlers.Values)
{
m_httpListener.RemovePollServiceHTTPHandler("", handler.Url);
}
}
public bool TryGetPollHandler(string name, out PollServiceEventArgs pollHandler)
{
return m_pollServiceHandlers.TryGetValue(name, out pollHandler);
}
public Dictionary<string, PollServiceEventArgs> GetPollHandlers()
{
return new Dictionary<string, PollServiceEventArgs>(m_pollServiceHandlers);
}
/// <summary>
/// Return an LLSD-serializable Hashtable describing the
/// capabilities and their handler details.
/// </summary>
/// <param name="excludeSeed">If true, then exclude the seed cap.</param>
public Hashtable GetCapsDetails(bool excludeSeed, List<string> requestedCaps)
{
Hashtable caps = CapsHandlers.GetCapsDetails(excludeSeed, requestedCaps);
lock (m_pollServiceHandlers)
{
foreach (KeyValuePair <string, PollServiceEventArgs> kvp in m_pollServiceHandlers)
{
if (!requestedCaps.Contains(kvp.Key))
continue;
string hostName = m_httpListenerHostName;
uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port;
string protocol = "http";
if (MainServer.Instance.UseSSL)
{
hostName = MainServer.Instance.SSLCommonName;
port = MainServer.Instance.SSLPort;
protocol = "https";
}
//
// caps.RegisterHandler("FetchInventoryDescendents2", String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, capUrl));
caps[kvp.Key] = string.Format("{0}://{1}:{2}{3}", protocol, hostName, port, kvp.Value.Url);
}
}
// Add the external too
foreach (KeyValuePair<string, string> kvp in ExternalCapsHandlers)
{
if (!requestedCaps.Contains(kvp.Key))
continue;
caps[kvp.Key] = kvp.Value;
}
return caps;
}
}
}
| |
// Copyright 2021 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 gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="RemarketingActionServiceClient"/> instances.</summary>
public sealed partial class RemarketingActionServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="RemarketingActionServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="RemarketingActionServiceSettings"/>.</returns>
public static RemarketingActionServiceSettings GetDefault() => new RemarketingActionServiceSettings();
/// <summary>
/// Constructs a new <see cref="RemarketingActionServiceSettings"/> object with default settings.
/// </summary>
public RemarketingActionServiceSettings()
{
}
private RemarketingActionServiceSettings(RemarketingActionServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetRemarketingActionSettings = existing.GetRemarketingActionSettings;
MutateRemarketingActionsSettings = existing.MutateRemarketingActionsSettings;
OnCopy(existing);
}
partial void OnCopy(RemarketingActionServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RemarketingActionServiceClient.GetRemarketingAction</c> and
/// <c>RemarketingActionServiceClient.GetRemarketingActionAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetRemarketingActionSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RemarketingActionServiceClient.MutateRemarketingActions</c> and
/// <c>RemarketingActionServiceClient.MutateRemarketingActionsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateRemarketingActionsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="RemarketingActionServiceSettings"/> object.</returns>
public RemarketingActionServiceSettings Clone() => new RemarketingActionServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="RemarketingActionServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class RemarketingActionServiceClientBuilder : gaxgrpc::ClientBuilderBase<RemarketingActionServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public RemarketingActionServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public RemarketingActionServiceClientBuilder()
{
UseJwtAccessWithScopes = RemarketingActionServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref RemarketingActionServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<RemarketingActionServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override RemarketingActionServiceClient Build()
{
RemarketingActionServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<RemarketingActionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<RemarketingActionServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private RemarketingActionServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return RemarketingActionServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<RemarketingActionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return RemarketingActionServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => RemarketingActionServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => RemarketingActionServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => RemarketingActionServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>RemarketingActionService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage remarketing actions.
/// </remarks>
public abstract partial class RemarketingActionServiceClient
{
/// <summary>
/// The default endpoint for the RemarketingActionService service, which is a host of "googleads.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default RemarketingActionService scopes.</summary>
/// <remarks>
/// The default RemarketingActionService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="RemarketingActionServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="RemarketingActionServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="RemarketingActionServiceClient"/>.</returns>
public static stt::Task<RemarketingActionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new RemarketingActionServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="RemarketingActionServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="RemarketingActionServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="RemarketingActionServiceClient"/>.</returns>
public static RemarketingActionServiceClient Create() => new RemarketingActionServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="RemarketingActionServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="RemarketingActionServiceSettings"/>.</param>
/// <returns>The created <see cref="RemarketingActionServiceClient"/>.</returns>
internal static RemarketingActionServiceClient Create(grpccore::CallInvoker callInvoker, RemarketingActionServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
RemarketingActionService.RemarketingActionServiceClient grpcClient = new RemarketingActionService.RemarketingActionServiceClient(callInvoker);
return new RemarketingActionServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC RemarketingActionService client</summary>
public virtual RemarketingActionService.RemarketingActionServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested remarketing action in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::RemarketingAction GetRemarketingAction(GetRemarketingActionRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested remarketing action in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::RemarketingAction> GetRemarketingActionAsync(GetRemarketingActionRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested remarketing action in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::RemarketingAction> GetRemarketingActionAsync(GetRemarketingActionRequest request, st::CancellationToken cancellationToken) =>
GetRemarketingActionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested remarketing action in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the remarketing action to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::RemarketingAction GetRemarketingAction(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetRemarketingAction(new GetRemarketingActionRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested remarketing action in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the remarketing action to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::RemarketingAction> GetRemarketingActionAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetRemarketingActionAsync(new GetRemarketingActionRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested remarketing action in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the remarketing action to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::RemarketingAction> GetRemarketingActionAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetRemarketingActionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested remarketing action in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the remarketing action to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::RemarketingAction GetRemarketingAction(gagvr::RemarketingActionName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetRemarketingAction(new GetRemarketingActionRequest
{
ResourceNameAsRemarketingActionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested remarketing action in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the remarketing action to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::RemarketingAction> GetRemarketingActionAsync(gagvr::RemarketingActionName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetRemarketingActionAsync(new GetRemarketingActionRequest
{
ResourceNameAsRemarketingActionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested remarketing action in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the remarketing action to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::RemarketingAction> GetRemarketingActionAsync(gagvr::RemarketingActionName resourceName, st::CancellationToken cancellationToken) =>
GetRemarketingActionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates or updates remarketing actions. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateRemarketingActionsResponse MutateRemarketingActions(MutateRemarketingActionsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates or updates remarketing actions. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateRemarketingActionsResponse> MutateRemarketingActionsAsync(MutateRemarketingActionsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates or updates remarketing actions. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateRemarketingActionsResponse> MutateRemarketingActionsAsync(MutateRemarketingActionsRequest request, st::CancellationToken cancellationToken) =>
MutateRemarketingActionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates or updates remarketing actions. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose remarketing actions are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual remarketing actions.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateRemarketingActionsResponse MutateRemarketingActions(string customerId, scg::IEnumerable<RemarketingActionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateRemarketingActions(new MutateRemarketingActionsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates or updates remarketing actions. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose remarketing actions are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual remarketing actions.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateRemarketingActionsResponse> MutateRemarketingActionsAsync(string customerId, scg::IEnumerable<RemarketingActionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateRemarketingActionsAsync(new MutateRemarketingActionsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates or updates remarketing actions. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose remarketing actions are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual remarketing actions.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateRemarketingActionsResponse> MutateRemarketingActionsAsync(string customerId, scg::IEnumerable<RemarketingActionOperation> operations, st::CancellationToken cancellationToken) =>
MutateRemarketingActionsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>RemarketingActionService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage remarketing actions.
/// </remarks>
public sealed partial class RemarketingActionServiceClientImpl : RemarketingActionServiceClient
{
private readonly gaxgrpc::ApiCall<GetRemarketingActionRequest, gagvr::RemarketingAction> _callGetRemarketingAction;
private readonly gaxgrpc::ApiCall<MutateRemarketingActionsRequest, MutateRemarketingActionsResponse> _callMutateRemarketingActions;
/// <summary>
/// Constructs a client wrapper for the RemarketingActionService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="RemarketingActionServiceSettings"/> used within this client.
/// </param>
public RemarketingActionServiceClientImpl(RemarketingActionService.RemarketingActionServiceClient grpcClient, RemarketingActionServiceSettings settings)
{
GrpcClient = grpcClient;
RemarketingActionServiceSettings effectiveSettings = settings ?? RemarketingActionServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetRemarketingAction = clientHelper.BuildApiCall<GetRemarketingActionRequest, gagvr::RemarketingAction>(grpcClient.GetRemarketingActionAsync, grpcClient.GetRemarketingAction, effectiveSettings.GetRemarketingActionSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetRemarketingAction);
Modify_GetRemarketingActionApiCall(ref _callGetRemarketingAction);
_callMutateRemarketingActions = clientHelper.BuildApiCall<MutateRemarketingActionsRequest, MutateRemarketingActionsResponse>(grpcClient.MutateRemarketingActionsAsync, grpcClient.MutateRemarketingActions, effectiveSettings.MutateRemarketingActionsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateRemarketingActions);
Modify_MutateRemarketingActionsApiCall(ref _callMutateRemarketingActions);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetRemarketingActionApiCall(ref gaxgrpc::ApiCall<GetRemarketingActionRequest, gagvr::RemarketingAction> call);
partial void Modify_MutateRemarketingActionsApiCall(ref gaxgrpc::ApiCall<MutateRemarketingActionsRequest, MutateRemarketingActionsResponse> call);
partial void OnConstruction(RemarketingActionService.RemarketingActionServiceClient grpcClient, RemarketingActionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC RemarketingActionService client</summary>
public override RemarketingActionService.RemarketingActionServiceClient GrpcClient { get; }
partial void Modify_GetRemarketingActionRequest(ref GetRemarketingActionRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateRemarketingActionsRequest(ref MutateRemarketingActionsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested remarketing action in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::RemarketingAction GetRemarketingAction(GetRemarketingActionRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetRemarketingActionRequest(ref request, ref callSettings);
return _callGetRemarketingAction.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested remarketing action in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::RemarketingAction> GetRemarketingActionAsync(GetRemarketingActionRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetRemarketingActionRequest(ref request, ref callSettings);
return _callGetRemarketingAction.Async(request, callSettings);
}
/// <summary>
/// Creates or updates remarketing actions. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateRemarketingActionsResponse MutateRemarketingActions(MutateRemarketingActionsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateRemarketingActionsRequest(ref request, ref callSettings);
return _callMutateRemarketingActions.Sync(request, callSettings);
}
/// <summary>
/// Creates or updates remarketing actions. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateRemarketingActionsResponse> MutateRemarketingActionsAsync(MutateRemarketingActionsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateRemarketingActionsRequest(ref request, ref callSettings);
return _callMutateRemarketingActions.Async(request, callSettings);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Data/Capture/CaptureAward.proto
#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 POGOProtos.Data.Capture {
/// <summary>Holder for reflection information generated from POGOProtos/Data/Capture/CaptureAward.proto</summary>
public static partial class CaptureAwardReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Data/Capture/CaptureAward.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CaptureAwardReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CipQT0dPUHJvdG9zL0RhdGEvQ2FwdHVyZS9DYXB0dXJlQXdhcmQucHJvdG8S",
"F1BPR09Qcm90b3MuRGF0YS5DYXB0dXJlGiNQT0dPUHJvdG9zL0VudW1zL0Fj",
"dGl2aXR5VHlwZS5wcm90byKCAQoMQ2FwdHVyZUF3YXJkEjkKDWFjdGl2aXR5",
"X3R5cGUYASADKA4yHi5QT0dPUHJvdG9zLkVudW1zLkFjdGl2aXR5VHlwZUIC",
"EAESDgoCeHAYAiADKAVCAhABEhEKBWNhbmR5GAMgAygFQgIQARIUCghzdGFy",
"ZHVzdBgEIAMoBUICEAFiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::POGOProtos.Enums.ActivityTypeReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Data.Capture.CaptureAward), global::POGOProtos.Data.Capture.CaptureAward.Parser, new[]{ "ActivityType", "Xp", "Candy", "Stardust" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class CaptureAward : pb::IMessage<CaptureAward> {
private static readonly pb::MessageParser<CaptureAward> _parser = new pb::MessageParser<CaptureAward>(() => new CaptureAward());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CaptureAward> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Data.Capture.CaptureAwardReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CaptureAward() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CaptureAward(CaptureAward other) : this() {
activityType_ = other.activityType_.Clone();
xp_ = other.xp_.Clone();
candy_ = other.candy_.Clone();
stardust_ = other.stardust_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CaptureAward Clone() {
return new CaptureAward(this);
}
/// <summary>Field number for the "activity_type" field.</summary>
public const int ActivityTypeFieldNumber = 1;
private static readonly pb::FieldCodec<global::POGOProtos.Enums.ActivityType> _repeated_activityType_codec
= pb::FieldCodec.ForEnum(10, x => (int) x, x => (global::POGOProtos.Enums.ActivityType) x);
private readonly pbc::RepeatedField<global::POGOProtos.Enums.ActivityType> activityType_ = new pbc::RepeatedField<global::POGOProtos.Enums.ActivityType>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::POGOProtos.Enums.ActivityType> ActivityType {
get { return activityType_; }
}
/// <summary>Field number for the "xp" field.</summary>
public const int XpFieldNumber = 2;
private static readonly pb::FieldCodec<int> _repeated_xp_codec
= pb::FieldCodec.ForInt32(18);
private readonly pbc::RepeatedField<int> xp_ = new pbc::RepeatedField<int>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<int> Xp {
get { return xp_; }
}
/// <summary>Field number for the "candy" field.</summary>
public const int CandyFieldNumber = 3;
private static readonly pb::FieldCodec<int> _repeated_candy_codec
= pb::FieldCodec.ForInt32(26);
private readonly pbc::RepeatedField<int> candy_ = new pbc::RepeatedField<int>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<int> Candy {
get { return candy_; }
}
/// <summary>Field number for the "stardust" field.</summary>
public const int StardustFieldNumber = 4;
private static readonly pb::FieldCodec<int> _repeated_stardust_codec
= pb::FieldCodec.ForInt32(34);
private readonly pbc::RepeatedField<int> stardust_ = new pbc::RepeatedField<int>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<int> Stardust {
get { return stardust_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CaptureAward);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CaptureAward other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!activityType_.Equals(other.activityType_)) return false;
if(!xp_.Equals(other.xp_)) return false;
if(!candy_.Equals(other.candy_)) return false;
if(!stardust_.Equals(other.stardust_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= activityType_.GetHashCode();
hash ^= xp_.GetHashCode();
hash ^= candy_.GetHashCode();
hash ^= stardust_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
activityType_.WriteTo(output, _repeated_activityType_codec);
xp_.WriteTo(output, _repeated_xp_codec);
candy_.WriteTo(output, _repeated_candy_codec);
stardust_.WriteTo(output, _repeated_stardust_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += activityType_.CalculateSize(_repeated_activityType_codec);
size += xp_.CalculateSize(_repeated_xp_codec);
size += candy_.CalculateSize(_repeated_candy_codec);
size += stardust_.CalculateSize(_repeated_stardust_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CaptureAward other) {
if (other == null) {
return;
}
activityType_.Add(other.activityType_);
xp_.Add(other.xp_);
candy_.Add(other.candy_);
stardust_.Add(other.stardust_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10:
case 8: {
activityType_.AddEntriesFrom(input, _repeated_activityType_codec);
break;
}
case 18:
case 16: {
xp_.AddEntriesFrom(input, _repeated_xp_codec);
break;
}
case 26:
case 24: {
candy_.AddEntriesFrom(input, _repeated_candy_codec);
break;
}
case 34:
case 32: {
stardust_.AddEntriesFrom(input, _repeated_stardust_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing Groups.
/// </summary>
internal partial class GroupsOperations : IServiceOperations<ApiManagementClient>, IGroupsOperations
{
/// <summary>
/// Initializes a new instance of the GroupsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal GroupsOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates new group.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='parameters'>
/// Required. Create parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> CreateAsync(string resourceGroupName, string serviceName, string gid, GroupCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (gid == null)
{
throw new ArgumentNullException("gid");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.Name.Length > 300)
{
throw new ArgumentOutOfRangeException("parameters.Name");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("gid", gid);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/groups/";
url = url + Uri.EscapeDataString(gid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject groupCreateParametersValue = new JObject();
requestDoc = groupCreateParametersValue;
groupCreateParametersValue["name"] = parameters.Name;
if (parameters.Description != null)
{
groupCreateParametersValue["description"] = parameters.Description;
}
if (parameters.Type != null)
{
groupCreateParametersValue["type"] = parameters.Type.Value.ToString();
}
if (parameters.ExternalId != null)
{
groupCreateParametersValue["externalId"] = parameters.ExternalId;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes specific group of the Api Management service instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string gid, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (gid == null)
{
throw new ArgumentNullException("gid");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("gid", gid);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/groups/";
url = url + Uri.EscapeDataString(gid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets specific group.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Get Group operation response details.
/// </returns>
public async Task<GroupGetResponse> GetAsync(string resourceGroupName, string serviceName, string gid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (gid == null)
{
throw new ArgumentNullException("gid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("gid", gid);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/groups/";
url = url + Uri.EscapeDataString(gid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GroupGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GroupGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
GroupContract valueInstance = new GroupContract();
result.Value = valueInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
valueInstance.IdPath = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
valueInstance.Name = nameInstance;
}
JToken descriptionValue = responseDoc["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
valueInstance.Description = descriptionInstance;
}
JToken builtInValue = responseDoc["builtIn"];
if (builtInValue != null && builtInValue.Type != JTokenType.Null)
{
bool builtInInstance = ((bool)builtInValue);
valueInstance.System = builtInInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true));
valueInstance.Type = typeInstance;
}
JToken externalIdValue = responseDoc["externalId"];
if (externalIdValue != null && externalIdValue.Type != JTokenType.Null)
{
string externalIdInstance = ((string)externalIdValue);
valueInstance.ExternalId = externalIdInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List all groups.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public async Task<GroupListResponse> ListAsync(string resourceGroupName, string serviceName, QueryParameters query, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("query", query);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/groups";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
List<string> odataFilter = new List<string>();
if (query != null && query.Filter != null)
{
odataFilter.Add(Uri.EscapeDataString(query.Filter));
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (query != null && query.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString()));
}
if (query != null && query.Skip != null)
{
queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString()));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GroupListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GroupListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
GroupPaged resultInstance = new GroupPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
GroupContract groupContractInstance = new GroupContract();
resultInstance.Values.Add(groupContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
groupContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
groupContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
groupContractInstance.Description = descriptionInstance;
}
JToken builtInValue = valueValue["builtIn"];
if (builtInValue != null && builtInValue.Type != JTokenType.Null)
{
bool builtInInstance = ((bool)builtInValue);
groupContractInstance.System = builtInInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true));
groupContractInstance.Type = typeInstance;
}
JToken externalIdValue = valueValue["externalId"];
if (externalIdValue != null && externalIdValue.Type != JTokenType.Null)
{
string externalIdInstance = ((string)externalIdValue);
groupContractInstance.ExternalId = externalIdInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List next groups page.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public async Task<GroupListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GroupListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GroupListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
GroupPaged resultInstance = new GroupPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
GroupContract groupContractInstance = new GroupContract();
resultInstance.Values.Add(groupContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
groupContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
groupContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
groupContractInstance.Description = descriptionInstance;
}
JToken builtInValue = valueValue["builtIn"];
if (builtInValue != null && builtInValue.Type != JTokenType.Null)
{
bool builtInInstance = ((bool)builtInValue);
groupContractInstance.System = builtInInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true));
groupContractInstance.Type = typeInstance;
}
JToken externalIdValue = valueValue["externalId"];
if (externalIdValue != null && externalIdValue.Type != JTokenType.Null)
{
string externalIdInstance = ((string)externalIdValue);
groupContractInstance.ExternalId = externalIdInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Patches specific group.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='parameters'>
/// Required. Update parameters.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> UpdateAsync(string resourceGroupName, string serviceName, string gid, GroupUpdateParameters parameters, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (gid == null)
{
throw new ArgumentNullException("gid");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name != null && parameters.Name.Length > 300)
{
throw new ArgumentOutOfRangeException("parameters.Name");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("gid", gid);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/groups/";
url = url + Uri.EscapeDataString(gid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject groupUpdateParametersValue = new JObject();
requestDoc = groupUpdateParametersValue;
if (parameters.Name != null)
{
groupUpdateParametersValue["name"] = parameters.Name;
}
if (parameters.Description != null)
{
groupUpdateParametersValue["description"] = parameters.Description;
}
if (parameters.Type != null)
{
groupUpdateParametersValue["type"] = parameters.Type.Value.ToString();
}
if (parameters.ExternalId != null)
{
groupUpdateParametersValue["externalId"] = parameters.ExternalId;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Copyright 2021 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 gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>GeoTargetConstant</c> resource.</summary>
public sealed partial class GeoTargetConstantName : gax::IResourceName, sys::IEquatable<GeoTargetConstantName>
{
/// <summary>The possible contents of <see cref="GeoTargetConstantName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>geoTargetConstants/{criterion_id}</c>.</summary>
Criterion = 1,
}
private static gax::PathTemplate s_criterion = new gax::PathTemplate("geoTargetConstants/{criterion_id}");
/// <summary>Creates a <see cref="GeoTargetConstantName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="GeoTargetConstantName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static GeoTargetConstantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new GeoTargetConstantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="GeoTargetConstantName"/> with the pattern <c>geoTargetConstants/{criterion_id}</c>.
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="GeoTargetConstantName"/> constructed from the provided ids.</returns>
public static GeoTargetConstantName FromCriterion(string criterionId) =>
new GeoTargetConstantName(ResourceNameType.Criterion, criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GeoTargetConstantName"/> with pattern
/// <c>geoTargetConstants/{criterion_id}</c>.
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="GeoTargetConstantName"/> with pattern
/// <c>geoTargetConstants/{criterion_id}</c>.
/// </returns>
public static string Format(string criterionId) => FormatCriterion(criterionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GeoTargetConstantName"/> with pattern
/// <c>geoTargetConstants/{criterion_id}</c>.
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="GeoTargetConstantName"/> with pattern
/// <c>geoTargetConstants/{criterion_id}</c>.
/// </returns>
public static string FormatCriterion(string criterionId) =>
s_criterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="GeoTargetConstantName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>geoTargetConstants/{criterion_id}</c></description></item></list>
/// </remarks>
/// <param name="geoTargetConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="GeoTargetConstantName"/> if successful.</returns>
public static GeoTargetConstantName Parse(string geoTargetConstantName) => Parse(geoTargetConstantName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="GeoTargetConstantName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>geoTargetConstants/{criterion_id}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="geoTargetConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="GeoTargetConstantName"/> if successful.</returns>
public static GeoTargetConstantName Parse(string geoTargetConstantName, bool allowUnparsed) =>
TryParse(geoTargetConstantName, allowUnparsed, out GeoTargetConstantName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GeoTargetConstantName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>geoTargetConstants/{criterion_id}</c></description></item></list>
/// </remarks>
/// <param name="geoTargetConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GeoTargetConstantName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string geoTargetConstantName, out GeoTargetConstantName result) =>
TryParse(geoTargetConstantName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GeoTargetConstantName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>geoTargetConstants/{criterion_id}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="geoTargetConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GeoTargetConstantName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string geoTargetConstantName, bool allowUnparsed, out GeoTargetConstantName result)
{
gax::GaxPreconditions.CheckNotNull(geoTargetConstantName, nameof(geoTargetConstantName));
gax::TemplatedResourceName resourceName;
if (s_criterion.TryParseName(geoTargetConstantName, out resourceName))
{
result = FromCriterion(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(geoTargetConstantName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private GeoTargetConstantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string criterionId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CriterionId = criterionId;
}
/// <summary>
/// Constructs a new instance of a <see cref="GeoTargetConstantName"/> class from the component parts of pattern
/// <c>geoTargetConstants/{criterion_id}</c>
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
public GeoTargetConstantName(string criterionId) : this(ResourceNameType.Criterion, criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CriterionId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.Criterion: return s_criterion.Expand(CriterionId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as GeoTargetConstantName);
/// <inheritdoc/>
public bool Equals(GeoTargetConstantName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(GeoTargetConstantName a, GeoTargetConstantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(GeoTargetConstantName a, GeoTargetConstantName b) => !(a == b);
}
public partial class GeoTargetConstant
{
/// <summary>
/// <see cref="gagvr::GeoTargetConstantName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal GeoTargetConstantName ResourceNameAsGeoTargetConstantName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::GeoTargetConstantName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::GeoTargetConstantName"/>-typed view over the <see cref="ParentGeoTarget"/> resource name
/// property.
/// </summary>
internal GeoTargetConstantName ParentGeoTargetAsGeoTargetConstantName
{
get => string.IsNullOrEmpty(ParentGeoTarget) ? null : gagvr::GeoTargetConstantName.Parse(ParentGeoTarget, allowUnparsed: true);
set => ParentGeoTarget = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::GeoTargetConstantName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal GeoTargetConstantName GeoTargetConstantName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::GeoTargetConstantName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class DungeonCreator : MonoBehaviour
{
public GameObject[] dungeonParts;
private int minimumDungeonSize;
public GameObject wall;
private float difficulty;
public GameObject goalPrefab;
public GameObject[] trapPrefabs;
public GameObject playerPrefab;
private List<MountPoint> opens = new List<MountPoint>();
private int roomIndex = 2;
private List<GameObject> rooms;
private List<GameObject> trapPlaces;
private List<GameObject> goalPlaces;
private List<GameObject> startPlaces;
public void Generate()
{
difficulty = Application.difficulty;
minimumDungeonSize = Application.size * 10;
trapPlaces = new List<GameObject>();
goalPlaces = new List<GameObject>();
startPlaces = new List<GameObject>();
rooms = new List<GameObject>();
opens = new List<MountPoint>();
createFirstDungeonPart();
int missingParts = minimumDungeonSize;
int i = 1;
while (missingParts > 0 )
{
MountPoint currentMountPoint = getRandomOpen();
int dungeonPartIndex = getRandomIndex();
if (opens.Count <= 1 && missingParts > 1)
{
int[] filter = new int[1];
filter[0] = roomIndex;
dungeonPartIndex = getRandomIndexWithFilter(filter);
}
GameObject dungeonPart = Instantiate(dungeonParts[dungeonPartIndex]) as GameObject;
dungeonPart.name = String.Format("part-{0}", i);
dungeonPart.transform.parent = transform;
int index = getRandomIndex(dungeonPart.GetComponent<DungeonPart>().mountPoints);
Transform mpTransform = dungeonPart.GetComponent<DungeonPart>().mountPoints[index];
MountPoint mp = mpTransform.GetComponent<MountPoint>();
TranslateAndRotation tr = getTranslateAndRotation(currentMountPoint.direction, mp.direction);
dungeonPart.transform.Rotate(tr.rotation);
updateMountPointDirections(dungeonPart.GetComponent<DungeonPart>(), tr.rotation);
mpTransform = dungeonPart.GetComponent<DungeonPart>().mountPoints[index];
mp = mpTransform.GetComponent<MountPoint>();
dungeonPart.transform.position = currentMountPoint.transform.position + new Vector3(tr.translationScale.x * Math.Abs(mp.translation.x), tr.translationScale.y * mp.translation.y, tr.translationScale.z * Math.Abs(mp.translation.z));
if (collideWithOtherRoom(dungeonPart.GetComponent<BoxCollider>().bounds))
{
DestroyImmediate(dungeonPart);
dungeonPart = Instantiate(wall) as GameObject;
dungeonPart.name = String.Format("part-{0}", i);
dungeonPart.transform.parent = transform;
index = getRandomIndex(dungeonPart.GetComponent<DungeonPart>().mountPoints);
mpTransform = dungeonPart.GetComponent<DungeonPart>().mountPoints[index];
mp = mpTransform.GetComponent<MountPoint>();
tr = getTranslateAndRotation(currentMountPoint.direction, mp.direction);
dungeonPart.transform.Rotate(tr.rotation);
updateMountPointDirections(dungeonPart.GetComponent<DungeonPart>(), tr.rotation);
mpTransform = dungeonPart.GetComponent<DungeonPart>().mountPoints[index];
mp = mpTransform.GetComponent<MountPoint>();
dungeonPart.transform.position = currentMountPoint.transform.position + new Vector3(tr.translationScale.x * Math.Abs(mp.translation.x), tr.translationScale.y * mp.translation.y, tr.translationScale.z * Math.Abs(mp.translation.z));
}
else
{
missingParts--;
}
addToOpensExept(dungeonPart.GetComponent<DungeonPart>().mountPoints, index);
rooms.Add(dungeonPart);
collectTrapsAndGoals(dungeonPart);
i++;
}
while (opens.Count > 0)
{
MountPoint currentMountPoint = getRandomOpen();
// Completo con habitaciones, si no entran pongo una pared.
GameObject dungeonPart = Instantiate(dungeonParts[roomIndex]) as GameObject;
// GameObject dungeonPart = Instantiate(wall) as GameObject;
dungeonPart.name = String.Format("part-{0}", i);
dungeonPart.transform.parent = transform;
int index = getRandomIndex(dungeonPart.GetComponent<DungeonPart>().mountPoints);
addToOpensExept(dungeonPart.GetComponent<DungeonPart>().mountPoints, index);
Transform mpTransform = dungeonPart.GetComponent<DungeonPart>().mountPoints[index];
MountPoint mp = mpTransform.GetComponent<MountPoint>();
TranslateAndRotation tr = getTranslateAndRotation(currentMountPoint.direction, mp.direction);
dungeonPart.transform.Rotate(tr.rotation);
updateMountPointDirections(dungeonPart.GetComponent<DungeonPart>(), tr.rotation);
mpTransform = dungeonPart.GetComponent<DungeonPart>().mountPoints[index];
mp = mpTransform.GetComponent<MountPoint>();
dungeonPart.transform.position = currentMountPoint.transform.position + new Vector3(tr.translationScale.x * Math.Abs(mp.translation.x), tr.translationScale.y * mp.translation.y, tr.translationScale.z * Math.Abs(mp.translation.z));
Bounds bounds = dungeonPart.GetComponent<BoxCollider>().bounds;
if (collideWithOtherRoom(bounds))
{
DestroyImmediate(dungeonPart);
dungeonPart = Instantiate(wall);
dungeonPart.name = String.Format("part-{0}", i);
dungeonPart.transform.parent = transform;
index = getRandomIndex(dungeonPart.GetComponent<DungeonPart>().mountPoints);
addToOpensExept(dungeonPart.GetComponent<DungeonPart>().mountPoints, index);
mpTransform = dungeonPart.GetComponent<DungeonPart>().mountPoints[index];
mp = mpTransform.GetComponent<MountPoint>();
tr = getTranslateAndRotation(currentMountPoint.direction, mp.direction);
dungeonPart.transform.Rotate(tr.rotation);
updateMountPointDirections(dungeonPart.GetComponent<DungeonPart>(), tr.rotation);
mpTransform = dungeonPart.GetComponent<DungeonPart>().mountPoints[index];
mp = mpTransform.GetComponent<MountPoint>();
dungeonPart.transform.position = currentMountPoint.transform.position + new Vector3(tr.translationScale.x * Math.Abs(mp.translation.x), tr.translationScale.y * mp.translation.y, tr.translationScale.z * Math.Abs(mp.translation.z));
}
rooms.Add(dungeonPart);
collectTrapsAndGoals(dungeonPart);
i++;
}
setGoal();
setTraps();
setPlayer();
}
private void setPlayer()
{
int index = UnityEngine.Random.Range(0, startPlaces.Count - 1);
GameObject startPlace = startPlaces[index];
(Instantiate(playerPrefab, startPlace.transform.position + new Vector3(0, 0.25f, 0), playerPrefab.transform.rotation) as GameObject).transform.parent = startPlace.transform;
}
private void setGoal()
{
int index = UnityEngine.Random.Range(0, goalPlaces.Count - 1);
GameObject goalPlace = goalPlaces[index];
(Instantiate(goalPrefab, goalPlace.transform.position + new Vector3(0, 0.25f, 0), goalPrefab.transform.rotation) as GameObject).transform.parent = goalPlace.transform;
}
private void setTraps()
{
int trapsAmount = (int) Math.Floor(difficulty * trapPlaces.Count);
for (int i = 0; i < trapsAmount; i++)
{
int index = UnityEngine.Random.Range(0, trapPlaces.Count - 1);
GameObject trapPlace = trapPlaces[index];
int trap = UnityEngine.Random.Range(0, trapPrefabs.Length);
GameObject trapPrefab = trapPrefabs[trap];
(Instantiate(trapPrefab, trapPlace.transform.position + new Vector3(0, 0.25f, 0), trapPrefab.transform.rotation) as GameObject).transform.parent = trapPlace.transform;
trapPlaces.RemoveAt(index);
}
}
public void RemoveAll()
{
DungeonPart[] rc = gameObject.GetComponentsInChildren<DungeonPart>();
for (int i=0; i<rc.Length; i++)
{
DestroyImmediate(rc[i].gameObject);
}
}
private bool collideWithOtherRoom(Bounds bounds)
{
foreach (GameObject room in rooms)
{
if (bounds.Intersects(room.GetComponent<BoxCollider>().bounds))
return true;
}
return false;
}
private MountPoint getRandomOpen()
{
int index = UnityEngine.Random.Range(0, opens.Count - 1);
MountPoint mp = opens[index];
opens.Remove(mp);
return mp;
}
private void createFirstDungeonPart()
{
GameObject firstGO = Instantiate(dungeonParts[getRandomIndex()]) as GameObject;
firstGO.name = "part-0";
firstGO.transform.parent = transform;
firstGO.transform.position = new Vector3(0, 0, 0);
foreach (Transform t in firstGO.GetComponent<DungeonPart>().mountPoints)
{
opens.Add(t.GetComponent<MountPoint>());
}
rooms.Add(firstGO);
collectTrapsAndGoals(firstGO);
}
private int getRandomIndex()
{
return UnityEngine.Random.Range(0, dungeonParts.Length);
}
private int getRandomIndexWithFilter(int[] indexesToFilter)
{
int index = UnityEngine.Random.Range(0, dungeonParts.Length);
while (contains(indexesToFilter, index))
{
index = UnityEngine.Random.Range(0, dungeonParts.Length);
}
return index;
}
private bool contains(int [] list, int value)
{
foreach (int elem in list)
{
if (elem == value)
return true;
}
return false;
}
private int getRandomIndex(Transform[] mps)
{
return UnityEngine.Random.Range(0, mps.Length);
}
private void addToOpensExept(Transform[] mps, int index)
{
for (int i = 0; i < mps.Length; i++)
{
if (i == index)
continue;
opens.Add(mps[i].GetComponent<MountPoint>());
}
}
private bool isNorth(Vector3 direction)
{
if (direction.x == -1 && direction.y == 0 && direction.z == 0)
return true;
return false;
}
private bool isSouth(Vector3 direction)
{
if (direction.x == 1 && direction.y == 0 && direction.z == 0)
return true;
return false;
}
private bool isWest(Vector3 direction)
{
if (direction.x == 0 && direction.y == 0 && direction.z == -1)
return true;
return false;
}
private bool isEast(Vector3 direction)
{
if (direction.x == 0 && direction.y == 0 && direction.z == 1)
return true;
return false;
}
private TranslateAndRotation getTranslateAndRotation(Vector3 direction1, Vector3 direction2)
{
if (isNorth(direction1))
{
if (isNorth(direction2))
return new TranslateAndRotation(new Vector3(-1, -1, 0), new Vector3(0, 180, 0));
if (isSouth(direction2))
return new TranslateAndRotation(new Vector3(-1, -1, 0), new Vector3(0, 0, 0));
if (isEast(direction2))
return new TranslateAndRotation(new Vector3(-1, -1, 0), new Vector3(0, 90, 0));
if (isWest(direction2))
return new TranslateAndRotation(new Vector3(-1, -1, 0), new Vector3(0, -90, 0));
}
if (isSouth(direction1))
{
if (isNorth(direction2))
return new TranslateAndRotation(new Vector3(1, -1, 0), new Vector3(0, 0, 0));
if (isSouth(direction2))
return new TranslateAndRotation(new Vector3(1, -1, 0), new Vector3(0, 180, 0));
if (isEast(direction2))
return new TranslateAndRotation(new Vector3(1, -1, 0), new Vector3(0, -90, 0));
if (isWest(direction2))
return new TranslateAndRotation(new Vector3(1, -1, 0), new Vector3(0, 90, 0));
}
if (isEast(direction1))
{
if (isNorth(direction2))
return new TranslateAndRotation(new Vector3(0, -1, 1), new Vector3(0, -90, 0));
if (isSouth(direction2))
return new TranslateAndRotation(new Vector3(0, -1, 1), new Vector3(0, 90, 0));
if (isEast(direction2))
return new TranslateAndRotation(new Vector3(0, -1, 1), new Vector3(0, 180, 0));
if (isWest(direction2))
return new TranslateAndRotation(new Vector3(0, -1, 1), new Vector3(0, 0, 0));
}
if (isWest(direction1))
{
if (isNorth(direction2))
return new TranslateAndRotation(new Vector3(0, -1, -1), new Vector3(0, 90, 0));
if (isSouth(direction2))
return new TranslateAndRotation(new Vector3(0, -1, -1), new Vector3(0, -90, 0));
if (isEast(direction2))
return new TranslateAndRotation(new Vector3(0, -1, -1), new Vector3(0, 0, 0));
if (isWest(direction2))
return new TranslateAndRotation(new Vector3(0, -1, -1), new Vector3(0, 180, 0));
}
Debug.Log("This should never happend (getTranslateAndRotation)");
return new TranslateAndRotation(new Vector3(1, 1, 1), new Vector3(0, 0, 0));
}
private void updateMountPointDirections(DungeonPart dp, Vector3 rotation)
{
if (Math.Abs(rotation.y) <= 0.001)
return;
if (Math.Abs(rotation.y - 90) <= 0.001)
{
foreach (Transform mp in dp.mountPoints)
{
Vector3 direction = mp.GetComponent<MountPoint>().direction;
mp.GetComponent<MountPoint>().direction = new Vector3(direction.z, 0, -1 * direction.x);
Vector3 translation = mp.GetComponent<MountPoint>().translation;
mp.GetComponent<MountPoint>().translation = new Vector3(translation.z, translation.y, -1 * translation.x);
}
return;
}
if (Math.Abs(rotation.y + 90) <= 0.001)
{
foreach (Transform mp in dp.mountPoints)
{
Vector3 direction = mp.GetComponent<MountPoint>().direction;
mp.GetComponent<MountPoint>().direction = new Vector3(-1 * direction.z, 0, direction.x);
Vector3 translation = mp.GetComponent<MountPoint>().translation;
mp.GetComponent<MountPoint>().translation = new Vector3(-1 * translation.z, translation.y, translation.x);
}
return;
}
if (Math.Abs(rotation.y - 180) <= 0.001)
{
foreach (Transform mp in dp.mountPoints)
{
Vector3 direction = mp.GetComponent<MountPoint>().direction;
mp.GetComponent<MountPoint>().direction = new Vector3(-1 * direction.x, 0, -1 * direction.z);
Vector3 translation = mp.GetComponent<MountPoint>().translation;
mp.GetComponent<MountPoint>().translation = new Vector3(-1 * translation.x, translation.y, -1 * translation.z);
}
return;
}
Debug.Log("This should never happend (updateMountPointDirections): " + rotation.y);
}
public class TranslateAndRotation
{
public Vector3 translationScale;
public Vector3 rotation;
public TranslateAndRotation(Vector3 translationScale, Vector3 rotation)
{
this.translationScale = translationScale;
this.rotation = rotation;
}
}
private void collectTrapsAndGoals(GameObject go)
{
foreach (Transform child in go.transform)
{
if (child.CompareTag("TrapPlace"))
{
trapPlaces.Add(child.gameObject);
}
else if (child.CompareTag("GoalPlace"))
{
goalPlaces.Add(child.gameObject);
}
else if (child.CompareTag("StartPlace"))
{
startPlaces.Add(child.gameObject);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Text
{
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System;
using System.Diagnostics.Contracts;
// A Decoder is used to decode a sequence of blocks of bytes into a
// sequence of blocks of characters. Following instantiation of a decoder,
// sequential blocks of bytes are converted into blocks of characters through
// calls to the GetChars method. The decoder maintains state between the
// conversions, allowing it to correctly decode byte sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Decoder abstract base
// class are typically obtained through calls to the GetDecoder method
// of Encoding objects.
//
[Serializable]
internal class DecoderNLS : Decoder, ISerializable
{
// Remember our encoding
protected Encoding m_encoding;
[NonSerialized] protected bool m_mustFlush;
[NonSerialized] internal bool m_throwOnOverflow;
[NonSerialized] internal int m_bytesUsed;
#region Serialization
// Constructor called by serialization. called during deserialization.
internal DecoderNLS(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(
String.Format(
System.Globalization.CultureInfo.CurrentCulture,
Environment.GetResourceString("NotSupported_TypeCannotDeserialized"), this.GetType()));
}
// ISerializable implementation. called during serialization.
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
SerializeDecoder(info);
info.AddValue("encoding", this.m_encoding);
info.SetType(typeof(Encoding.DefaultDecoder));
}
#endregion Serialization
internal DecoderNLS( Encoding encoding )
{
this.m_encoding = encoding;
this.m_fallback = this.m_encoding.DecoderFallback;
this.Reset();
}
// This is used by our child deserializers
internal DecoderNLS( )
{
this.m_encoding = null;
this.Reset();
}
public override void Reset()
{
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
return GetCharCount(bytes, index, count, false);
}
public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException(nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(bytes),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// Avoid null fixed problem
if (bytes.Length == 0)
bytes = new byte[1];
// Just call pointer version
fixed (byte* pBytes = &bytes[0])
return GetCharCount(pBytes + index, count, flush);
}
public unsafe override int GetCharCount(byte* bytes, int count, bool flush)
{
// Validate parameters
if (bytes == null)
throw new ArgumentNullException(nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Remember the flush
this.m_mustFlush = flush;
this.m_throwOnOverflow = true;
// By default just call the encoding version, no flush by default
return m_encoding.GetCharCount(bytes, count, this);
}
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false);
}
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, bool flush)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if ( bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException(nameof(charIndex),
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
// Avoid empty input fixed problem
if (bytes.Length == 0)
bytes = new byte[1];
int charCount = chars.Length - charIndex;
if (chars.Length == 0)
chars = new char[1];
// Just call pointer version
fixed (byte* pBytes = &bytes[0])
fixed (char* pChars = &chars[0])
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount,
pChars + charIndex, charCount, flush);
}
public unsafe override int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Remember our flush
m_mustFlush = flush;
m_throwOnOverflow = true;
// By default just call the encoding's version
return m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
}
// This method is used when the output buffer might not be big enough.
// Just call the pointer version. (This gets chars)
public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate parameters
if (bytes == null || chars == null)
throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// Avoid empty input problem
if (bytes.Length == 0)
bytes = new byte[1];
if (chars.Length == 0)
chars = new char[1];
// Just call the pointer version (public overrides can't do this)
fixed (byte* pBytes = &bytes[0])
{
fixed (char* pChars = &chars[0])
{
Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush,
out bytesUsed, out charsUsed, out completed);
}
}
}
// This is the version that used pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting chars
public unsafe override void Convert(byte* bytes, int byteCount,
char* chars, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate input parameters
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// We don't want to throw
this.m_mustFlush = flush;
this.m_throwOnOverflow = false;
this.m_bytesUsed = 0;
// Do conversion
charsUsed = this.m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
bytesUsed = this.m_bytesUsed;
// Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed
completed = (bytesUsed == byteCount) && (!flush || !this.HasState) &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
// Our data thingys are now full, we can return
}
public bool MustFlush
{
get
{
return m_mustFlush;
}
}
// Anything left in our decoder?
internal virtual bool HasState
{
get
{
return false;
}
}
// Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow)
internal void ClearMustFlush()
{
m_mustFlush = false;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// HashAlgorithm.cs
//
namespace System.Security.Cryptography {
using System.IO;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class HashAlgorithm : IDisposable, ICryptoTransform {
protected int HashSizeValue;
protected internal byte[] HashValue;
protected int State = 0;
private bool m_bDisposed = false;
protected HashAlgorithm() {}
//
// public properties
//
public virtual int HashSize {
get { return HashSizeValue; }
}
public virtual byte[] Hash {
get {
if (m_bDisposed)
throw new ObjectDisposedException(null);
if (State != 0)
throw new CryptographicUnexpectedOperationException(Environment.GetResourceString("Cryptography_HashNotYetFinalized"));
return (byte[]) HashValue.Clone();
}
}
//
// public methods
//
static public HashAlgorithm Create() {
return Create("System.Security.Cryptography.HashAlgorithm");
}
static public HashAlgorithm Create(String hashName) {
return (HashAlgorithm) CryptoConfig.CreateFromName(hashName);
}
public byte[] ComputeHash(Stream inputStream) {
if (m_bDisposed)
throw new ObjectDisposedException(null);
// Default the buffer size to 4K.
byte[] buffer = new byte[4096];
int bytesRead;
do {
bytesRead = inputStream.Read(buffer, 0, 4096);
if (bytesRead > 0) {
HashCore(buffer, 0, bytesRead);
}
} while (bytesRead > 0);
HashValue = HashFinal();
byte[] Tmp = (byte[]) HashValue.Clone();
Initialize();
return(Tmp);
}
public byte[] ComputeHash(byte[] buffer) {
if (m_bDisposed)
throw new ObjectDisposedException(null);
// Do some validation
if (buffer == null) throw new ArgumentNullException("buffer");
HashCore(buffer, 0, buffer.Length);
HashValue = HashFinal();
byte[] Tmp = (byte[]) HashValue.Clone();
Initialize();
return(Tmp);
}
public byte[] ComputeHash(byte[] buffer, int offset, int count) {
// Do some validation
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0 || (count > buffer.Length))
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"));
if ((buffer.Length - count) < offset)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (m_bDisposed)
throw new ObjectDisposedException(null);
HashCore(buffer, offset, count);
HashValue = HashFinal();
byte[] Tmp = (byte[]) HashValue.Clone();
Initialize();
return(Tmp);
}
// ICryptoTransform methods
// we assume any HashAlgorithm can take input a byte at a time
public virtual int InputBlockSize {
get { return(1); }
}
public virtual int OutputBlockSize {
get { return(1); }
}
public virtual bool CanTransformMultipleBlocks {
get { return(true); }
}
public virtual bool CanReuseTransform {
get { return(true); }
}
// We implement TransformBlock and TransformFinalBlock here
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) {
// Do some validation, we let BlockCopy do the destination array validation
if (inputBuffer == null)
throw new ArgumentNullException("inputBuffer");
if (inputOffset < 0)
throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (inputCount < 0 || (inputCount > inputBuffer.Length))
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"));
if ((inputBuffer.Length - inputCount) < inputOffset)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (m_bDisposed)
throw new ObjectDisposedException(null);
// Change the State value
State = 1;
HashCore(inputBuffer, inputOffset, inputCount);
if ((outputBuffer != null) && ((inputBuffer != outputBuffer) || (inputOffset != outputOffset)))
Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount);
return inputCount;
}
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) {
// Do some validation
if (inputBuffer == null)
throw new ArgumentNullException("inputBuffer");
if (inputOffset < 0)
throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (inputCount < 0 || (inputCount > inputBuffer.Length))
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"));
if ((inputBuffer.Length - inputCount) < inputOffset)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (m_bDisposed)
throw new ObjectDisposedException(null);
HashCore(inputBuffer, inputOffset, inputCount);
HashValue = HashFinal();
byte[] outputBytes;
if (inputCount != 0)
{
outputBytes = new byte[inputCount];
Buffer.InternalBlockCopy(inputBuffer, inputOffset, outputBytes, 0, inputCount);
}
else
{
outputBytes = EmptyArray<Byte>.Value;
}
// reset the State value
State = 0;
return outputBytes;
}
// IDisposable methods
// To keep mscorlib compatibility with Orcas, CoreCLR's HashAlgorithm has an explicit IDisposable
// implementation. Post-Orcas the desktop has an implicit IDispoable implementation.
#if FEATURE_CORECLR
void IDisposable.Dispose()
#else
public void Dispose()
#endif // FEATURE_CORECLR
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Clear() {
(this as IDisposable).Dispose();
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
if (HashValue != null)
Array.Clear(HashValue, 0, HashValue.Length);
HashValue = null;
m_bDisposed = true;
}
}
//
// abstract public methods
//
public abstract void Initialize();
protected abstract void HashCore(byte[] array, int ibStart, int cbSize);
protected abstract byte[] HashFinal();
}
}
| |
// Copyright 2021 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 gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="AdGroupCriterionServiceClient"/> instances.</summary>
public sealed partial class AdGroupCriterionServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AdGroupCriterionServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AdGroupCriterionServiceSettings"/>.</returns>
public static AdGroupCriterionServiceSettings GetDefault() => new AdGroupCriterionServiceSettings();
/// <summary>
/// Constructs a new <see cref="AdGroupCriterionServiceSettings"/> object with default settings.
/// </summary>
public AdGroupCriterionServiceSettings()
{
}
private AdGroupCriterionServiceSettings(AdGroupCriterionServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetAdGroupCriterionSettings = existing.GetAdGroupCriterionSettings;
MutateAdGroupCriteriaSettings = existing.MutateAdGroupCriteriaSettings;
OnCopy(existing);
}
partial void OnCopy(AdGroupCriterionServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupCriterionServiceClient.GetAdGroupCriterion</c> and
/// <c>AdGroupCriterionServiceClient.GetAdGroupCriterionAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetAdGroupCriterionSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupCriterionServiceClient.MutateAdGroupCriteria</c> and
/// <c>AdGroupCriterionServiceClient.MutateAdGroupCriteriaAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateAdGroupCriteriaSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AdGroupCriterionServiceSettings"/> object.</returns>
public AdGroupCriterionServiceSettings Clone() => new AdGroupCriterionServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AdGroupCriterionServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class AdGroupCriterionServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupCriterionServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AdGroupCriterionServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AdGroupCriterionServiceClientBuilder()
{
UseJwtAccessWithScopes = AdGroupCriterionServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AdGroupCriterionServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupCriterionServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AdGroupCriterionServiceClient Build()
{
AdGroupCriterionServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AdGroupCriterionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AdGroupCriterionServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AdGroupCriterionServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AdGroupCriterionServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AdGroupCriterionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AdGroupCriterionServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AdGroupCriterionServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupCriterionServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupCriterionServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AdGroupCriterionService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage ad group criteria.
/// </remarks>
public abstract partial class AdGroupCriterionServiceClient
{
/// <summary>
/// The default endpoint for the AdGroupCriterionService service, which is a host of "googleads.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default AdGroupCriterionService scopes.</summary>
/// <remarks>
/// The default AdGroupCriterionService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AdGroupCriterionServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupCriterionServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AdGroupCriterionServiceClient"/>.</returns>
public static stt::Task<AdGroupCriterionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AdGroupCriterionServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AdGroupCriterionServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupCriterionServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AdGroupCriterionServiceClient"/>.</returns>
public static AdGroupCriterionServiceClient Create() => new AdGroupCriterionServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AdGroupCriterionServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AdGroupCriterionServiceSettings"/>.</param>
/// <returns>The created <see cref="AdGroupCriterionServiceClient"/>.</returns>
internal static AdGroupCriterionServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupCriterionServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AdGroupCriterionService.AdGroupCriterionServiceClient grpcClient = new AdGroupCriterionService.AdGroupCriterionServiceClient(callInvoker);
return new AdGroupCriterionServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AdGroupCriterionService client</summary>
public virtual AdGroupCriterionService.AdGroupCriterionServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupCriterion GetAdGroupCriterion(GetAdGroupCriterionRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterion> GetAdGroupCriterionAsync(GetAdGroupCriterionRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterion> GetAdGroupCriterionAsync(GetAdGroupCriterionRequest request, st::CancellationToken cancellationToken) =>
GetAdGroupCriterionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupCriterion GetAdGroupCriterion(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupCriterion(new GetAdGroupCriterionRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterion> GetAdGroupCriterionAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupCriterionAsync(new GetAdGroupCriterionRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterion> GetAdGroupCriterionAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupCriterionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupCriterion GetAdGroupCriterion(gagvr::AdGroupCriterionName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupCriterion(new GetAdGroupCriterionRequest
{
ResourceNameAsAdGroupCriterionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterion> GetAdGroupCriterionAsync(gagvr::AdGroupCriterionName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupCriterionAsync(new GetAdGroupCriterionRequest
{
ResourceNameAsAdGroupCriterionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterion> GetAdGroupCriterionAsync(gagvr::AdGroupCriterionName resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupCriterionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupCriteriaResponse MutateAdGroupCriteria(MutateAdGroupCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(MutateAdGroupCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(MutateAdGroupCriteriaRequest request, st::CancellationToken cancellationToken) =>
MutateAdGroupCriteriaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupCriteriaResponse MutateAdGroupCriteria(string customerId, scg::IEnumerable<AdGroupCriterionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupCriteria(new MutateAdGroupCriteriaRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(string customerId, scg::IEnumerable<AdGroupCriterionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupCriteriaAsync(new MutateAdGroupCriteriaRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(string customerId, scg::IEnumerable<AdGroupCriterionOperation> operations, st::CancellationToken cancellationToken) =>
MutateAdGroupCriteriaAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AdGroupCriterionService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage ad group criteria.
/// </remarks>
public sealed partial class AdGroupCriterionServiceClientImpl : AdGroupCriterionServiceClient
{
private readonly gaxgrpc::ApiCall<GetAdGroupCriterionRequest, gagvr::AdGroupCriterion> _callGetAdGroupCriterion;
private readonly gaxgrpc::ApiCall<MutateAdGroupCriteriaRequest, MutateAdGroupCriteriaResponse> _callMutateAdGroupCriteria;
/// <summary>
/// Constructs a client wrapper for the AdGroupCriterionService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="AdGroupCriterionServiceSettings"/> used within this client.
/// </param>
public AdGroupCriterionServiceClientImpl(AdGroupCriterionService.AdGroupCriterionServiceClient grpcClient, AdGroupCriterionServiceSettings settings)
{
GrpcClient = grpcClient;
AdGroupCriterionServiceSettings effectiveSettings = settings ?? AdGroupCriterionServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetAdGroupCriterion = clientHelper.BuildApiCall<GetAdGroupCriterionRequest, gagvr::AdGroupCriterion>(grpcClient.GetAdGroupCriterionAsync, grpcClient.GetAdGroupCriterion, effectiveSettings.GetAdGroupCriterionSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetAdGroupCriterion);
Modify_GetAdGroupCriterionApiCall(ref _callGetAdGroupCriterion);
_callMutateAdGroupCriteria = clientHelper.BuildApiCall<MutateAdGroupCriteriaRequest, MutateAdGroupCriteriaResponse>(grpcClient.MutateAdGroupCriteriaAsync, grpcClient.MutateAdGroupCriteria, effectiveSettings.MutateAdGroupCriteriaSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateAdGroupCriteria);
Modify_MutateAdGroupCriteriaApiCall(ref _callMutateAdGroupCriteria);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetAdGroupCriterionApiCall(ref gaxgrpc::ApiCall<GetAdGroupCriterionRequest, gagvr::AdGroupCriterion> call);
partial void Modify_MutateAdGroupCriteriaApiCall(ref gaxgrpc::ApiCall<MutateAdGroupCriteriaRequest, MutateAdGroupCriteriaResponse> call);
partial void OnConstruction(AdGroupCriterionService.AdGroupCriterionServiceClient grpcClient, AdGroupCriterionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AdGroupCriterionService client</summary>
public override AdGroupCriterionService.AdGroupCriterionServiceClient GrpcClient { get; }
partial void Modify_GetAdGroupCriterionRequest(ref GetAdGroupCriterionRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateAdGroupCriteriaRequest(ref MutateAdGroupCriteriaRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::AdGroupCriterion GetAdGroupCriterion(GetAdGroupCriterionRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupCriterionRequest(ref request, ref callSettings);
return _callGetAdGroupCriterion.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::AdGroupCriterion> GetAdGroupCriterionAsync(GetAdGroupCriterionRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupCriterionRequest(ref request, ref callSettings);
return _callGetAdGroupCriterion.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateAdGroupCriteriaResponse MutateAdGroupCriteria(MutateAdGroupCriteriaRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupCriteriaRequest(ref request, ref callSettings);
return _callMutateAdGroupCriteria.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(MutateAdGroupCriteriaRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupCriteriaRequest(ref request, ref callSettings);
return _callMutateAdGroupCriteria.Async(request, callSettings);
}
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using Markdig.Helpers;
using Markdig.Parsers.Inlines;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
namespace Markdig.Parsers
{
/// <summary>
/// A delegate called at inline processing stage.
/// </summary>
/// <param name="processor">The processor.</param>
/// <param name="inline">The inline being processed.</param>
public delegate void ProcessInlineDelegate(InlineProcessor processor, Inline inline);
/// <summary>
/// The inline parser state used by all <see cref="InlineParser"/>.
/// </summary>
public class InlineProcessor
{
private readonly List<StringLineGroup.LineOffset> lineOffsets;
private int previousSliceOffset;
private int previousLineIndexForSliceOffset;
/// <summary>
/// Initializes a new instance of the <see cref="InlineProcessor" /> class.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="parsers">The parsers.</param>
/// <param name="preciseSourcelocation">A value indicating whether to provide precise source location.</param>
/// <param name="context">A parser context used for the parsing.</param>
/// <exception cref="ArgumentNullException">
/// </exception>
public InlineProcessor(MarkdownDocument document, InlineParserList parsers, bool preciseSourcelocation, MarkdownParserContext context)
{
if (document == null) ThrowHelper.ArgumentNullException(nameof(document));
if (parsers == null) ThrowHelper.ArgumentNullException(nameof(parsers));
Document = document;
Parsers = parsers;
Context = context;
PreciseSourceLocation = preciseSourcelocation;
lineOffsets = new List<StringLineGroup.LineOffset>();
ParserStates = new object[Parsers.Count];
LiteralInlineParser = new LiteralInlineParser();
}
/// <summary>
/// Gets the current block being processed.
/// </summary>
public LeafBlock Block { get; private set; }
/// <summary>
/// Gets a value indicating whether to provide precise source location.
/// </summary>
public bool PreciseSourceLocation { get; }
/// <summary>
/// Gets or sets the new block to replace the block being processed.
/// </summary>
public Block BlockNew { get; set; }
/// <summary>
/// Gets or sets the current inline. Used by <see cref="InlineParser"/> to return a new inline if match was successfull
/// </summary>
public Inline Inline { get; set; }
/// <summary>
/// Gets the root container of the current <see cref="Block"/>.
/// </summary>
public ContainerInline Root { get; internal set; }
/// <summary>
/// Gets the list of inline parsers.
/// </summary>
public InlineParserList Parsers { get; }
/// <summary>
/// Gets the parser context or <c>null</c> if none is available.
/// </summary>
public MarkdownParserContext Context { get; }
/// <summary>
/// Gets the root document.
/// </summary>
public MarkdownDocument Document { get; }
/// <summary>
/// Gets or sets the index of the line from the begining of the document being processed.
/// </summary>
public int LineIndex { get; private set; }
/// <summary>
/// Gets the parser states that can be used by <see cref="InlineParser"/> using their <see cref="ParserBase{Inline}.Index"/> property.
/// </summary>
public object[] ParserStates { get; }
/// <summary>
/// Gets or sets the debug log writer. No log if null.
/// </summary>
public TextWriter DebugLog { get; set; }
/// <summary>
/// Gets the literal inline parser.
/// </summary>
public LiteralInlineParser LiteralInlineParser { get; }
public int GetSourcePosition(int sliceOffset)
{
return GetSourcePosition(sliceOffset, out int lineIndex, out int column);
}
public SourceSpan GetSourcePositionFromLocalSpan(SourceSpan span)
{
if (span.IsEmpty)
{
return SourceSpan.Empty;
}
return new SourceSpan(GetSourcePosition(span.Start, out int lineIndex, out int column), GetSourcePosition(span.End, out lineIndex, out column));
}
/// <summary>
/// Gets the source position for the specified offset within the current slice.
/// </summary>
/// <param name="sliceOffset">The slice offset.</param>
/// <param name="lineIndex">The line index.</param>
/// <param name="column">The column.</param>
/// <returns>The source position</returns>
public int GetSourcePosition(int sliceOffset, out int lineIndex, out int column)
{
column = 0;
lineIndex = sliceOffset >= previousSliceOffset ? previousLineIndexForSliceOffset : 0;
int position = 0;
if (PreciseSourceLocation)
{
for (; lineIndex < lineOffsets.Count; lineIndex++)
{
var lineOffset = lineOffsets[lineIndex];
if (sliceOffset <= lineOffset.End)
{
// Use the beginning of the line as a previous slice offset
// (since it is on the same line)
previousSliceOffset = lineOffsets[lineIndex].Start;
var delta = sliceOffset - previousSliceOffset;
column = lineOffsets[lineIndex].Column + delta;
position = lineOffset.LinePosition + delta + lineOffsets[lineIndex].Offset;
previousLineIndexForSliceOffset = lineIndex;
// Return an absolute line index
lineIndex = lineIndex + LineIndex;
break;
}
}
}
return position;
}
/// <summary>
/// Processes the inline of the specified <see cref="LeafBlock"/>.
/// </summary>
/// <param name="leafBlock">The leaf block.</param>
public void ProcessInlineLeaf(LeafBlock leafBlock)
{
if (leafBlock == null) ThrowHelper.ArgumentNullException_leafBlock();
// clear parser states
Array.Clear(ParserStates, 0, ParserStates.Length);
Root = new ContainerInline() { IsClosed = false };
leafBlock.Inline = Root;
Inline = null;
Block = leafBlock;
BlockNew = null;
LineIndex = leafBlock.Line;
previousSliceOffset = 0;
previousLineIndexForSliceOffset = 0;
lineOffsets.Clear();
var text = leafBlock.Lines.ToSlice(lineOffsets);
leafBlock.Lines.Release();
int previousStart = -1;
while (!text.IsEmpty)
{
// Security check so that the parser can't go into a crazy infinite loop if one extension is messing
if (previousStart == text.Start)
{
ThrowHelper.InvalidOperationException($"The parser is in an invalid infinite loop while trying to parse inlines for block [{leafBlock.GetType().Name}] at position ({leafBlock.ToPositionText()}");
}
previousStart = text.Start;
var c = text.CurrentChar;
var textSaved = text;
var parsers = Parsers.GetParsersForOpeningCharacter(c);
if (parsers != null)
{
for (int i = 0; i < parsers.Length; i++)
{
text = textSaved;
if (parsers[i].Match(this, ref text))
{
goto done;
}
}
}
parsers = Parsers.GlobalParsers;
if (parsers != null)
{
for (int i = 0; i < parsers.Length; i++)
{
text = textSaved;
if (parsers[i].Match(this, ref text))
{
goto done;
}
}
}
text = textSaved;
// Else match using the default literal inline parser
LiteralInlineParser.Match(this, ref text);
done:
var nextInline = Inline;
if (nextInline != null)
{
if (nextInline.Parent == null)
{
// Get deepest container
var container = FindLastContainer();
if (!ReferenceEquals(container, nextInline))
{
container.AppendChild(nextInline);
}
if (container == Root)
{
if (container.Span.IsEmpty)
{
container.Span = nextInline.Span;
}
container.Span.End = nextInline.Span.End;
}
}
}
else
{
// Get deepest container
var container = FindLastContainer();
Inline = container.LastChild is LeafInline ? container.LastChild : container;
if (Inline == Root)
{
Inline = null;
}
}
//if (DebugLog != null)
//{
// DebugLog.WriteLine($"** Dump: char '{c}");
// leafBlock.Inline.DumpTo(DebugLog);
//}
}
Inline = null;
//if (DebugLog != null)
//{
// DebugLog.WriteLine("** Dump before Emphasis:");
// leafBlock.Inline.DumpTo(DebugLog);
//}
// PostProcess all inlines
PostProcessInlines(0, Root, null, true);
//TransformDelimitersToLiterals();
//if (DebugLog != null)
//{
// DebugLog.WriteLine();
// DebugLog.WriteLine("** Dump after Emphasis:");
// leafBlock.Inline.DumpTo(DebugLog);
//}
}
public void PostProcessInlines(int startingIndex, Inline root, Inline lastChild, bool isFinalProcessing)
{
for (int i = startingIndex; i < Parsers.PostInlineProcessors.Length; i++)
{
var postInlineProcessor = Parsers.PostInlineProcessors[i];
if (!postInlineProcessor.PostProcess(this, root, lastChild, i, isFinalProcessing))
{
break;
}
}
}
private ContainerInline FindLastContainer()
{
var container = Block.Inline;
while (true)
{
if (container.LastChild is ContainerInline nextContainer && !nextContainer.IsClosed)
{
container = nextContainer;
}
else
{
break;
}
}
return container;
}
}
}
| |
//
// ServiceStack.OrmLite: Light-weight POCO ORM for .NET and Mono
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2013 ServiceStack, Inc. All Rights Reserved.
//
// Licensed under the same terms of ServiceStack.
//
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using ServiceStack.DataAnnotations;
using ServiceStack.Logging;
using ServiceStack.OrmLite.Converters;
using ServiceStack.Text;
using ServiceStack.Script;
namespace ServiceStack.OrmLite
{
public abstract class OrmLiteDialectProviderBase<TDialect>
: IOrmLiteDialectProvider
where TDialect : IOrmLiteDialectProvider
{
protected static readonly ILog Log = LogManager.GetLogger(typeof(IOrmLiteDialectProvider));
protected OrmLiteDialectProviderBase()
{
Variables = new Dictionary<string, string>();
StringSerializer = new JsvStringSerializer();
}
#region ADO.NET supported types
/* ADO.NET UNDERSTOOD DATA TYPES:
COUNTER DbType.Int64
AUTOINCREMENT DbType.Int64
IDENTITY DbType.Int64
LONG DbType.Int64
TINYINT DbType.Byte
INTEGER DbType.Int64
INT DbType.Int32
VARCHAR DbType.String
NVARCHAR DbType.String
CHAR DbType.String
NCHAR DbType.String
TEXT DbType.String
NTEXT DbType.String
STRING DbType.String
DOUBLE DbType.Double
FLOAT DbType.Double
REAL DbType.Single
BIT DbType.Boolean
YESNO DbType.Boolean
LOGICAL DbType.Boolean
BOOL DbType.Boolean
NUMERIC DbType.Decimal
DECIMAL DbType.Decimal
MONEY DbType.Decimal
CURRENCY DbType.Decimal
TIME DbType.DateTime
DATE DbType.DateTime
TIMESTAMP DbType.DateTime
DATETIME DbType.DateTime
BLOB DbType.Binary
BINARY DbType.Binary
VARBINARY DbType.Binary
IMAGE DbType.Binary
GENERAL DbType.Binary
OLEOBJECT DbType.Binary
GUID DbType.Guid
UNIQUEIDENTIFIER DbType.Guid
MEMO DbType.String
NOTE DbType.String
LONGTEXT DbType.String
LONGCHAR DbType.String
SMALLINT DbType.Int16
BIGINT DbType.Int64
LONGVARCHAR DbType.String
SMALLDATE DbType.DateTime
SMALLDATETIME DbType.DateTime
*/
#endregion
protected void InitColumnTypeMap()
{
EnumConverter = new EnumConverter();
RowVersionConverter = new RowVersionConverter();
ReferenceTypeConverter = new ReferenceTypeConverter();
ValueTypeConverter = new ValueTypeConverter();
RegisterConverter<string>(new StringConverter());
RegisterConverter<char>(new CharConverter());
RegisterConverter<char[]>(new CharArrayConverter());
RegisterConverter<byte[]>(new ByteArrayConverter());
RegisterConverter<byte>(new ByteConverter());
RegisterConverter<sbyte>(new SByteConverter());
RegisterConverter<short>(new Int16Converter());
RegisterConverter<ushort>(new UInt16Converter());
RegisterConverter<int>(new Int32Converter());
RegisterConverter<uint>(new UInt32Converter());
RegisterConverter<long>(new Int64Converter());
RegisterConverter<ulong>(new UInt64Converter());
RegisterConverter<ulong>(new UInt64Converter());
RegisterConverter<float>(new FloatConverter());
RegisterConverter<double>(new DoubleConverter());
RegisterConverter<decimal>(new DecimalConverter());
RegisterConverter<Guid>(new GuidConverter());
RegisterConverter<TimeSpan>(new TimeSpanAsIntConverter());
RegisterConverter<DateTime>(new DateTimeConverter());
RegisterConverter<DateTimeOffset>(new DateTimeOffsetConverter());
}
public string GetColumnTypeDefinition(Type columnType, int? fieldLength, int? scale)
{
var converter = GetConverter(columnType);
if (converter != null)
{
if (converter is IHasColumnDefinitionPrecision customPrecisionConverter)
return customPrecisionConverter.GetColumnDefinition(fieldLength, scale);
if (converter is IHasColumnDefinitionLength customLengthConverter)
return customLengthConverter.GetColumnDefinition(fieldLength);
if (string.IsNullOrEmpty(converter.ColumnDefinition))
throw new ArgumentException($"{converter.GetType().Name} requires a ColumnDefinition");
return converter.ColumnDefinition;
}
var stringConverter = columnType.IsRefType()
? ReferenceTypeConverter
: columnType.IsEnum
? EnumConverter
: (IHasColumnDefinitionLength)ValueTypeConverter;
return stringConverter.GetColumnDefinition(fieldLength);
}
public virtual void InitDbParam(IDbDataParameter dbParam, Type columnType)
{
var converter = GetConverterBestMatch(columnType);
converter.InitDbParam(dbParam, columnType);
}
public abstract IDbDataParameter CreateParam();
public Dictionary<string, string> Variables { get; set; }
public IOrmLiteExecFilter ExecFilter { get; set; }
public Dictionary<Type, IOrmLiteConverter> Converters = new Dictionary<Type, IOrmLiteConverter>();
public string AutoIncrementDefinition = "AUTOINCREMENT"; //SqlServer express limit
public DecimalConverter DecimalConverter => (DecimalConverter)Converters[typeof(decimal)];
public StringConverter StringConverter => (StringConverter)Converters[typeof(string)];
public Action<IDbConnection> OnOpenConnection { get; set; }
public string ParamString { get; set; } = "@";
public INamingStrategy NamingStrategy { get; set; } = new OrmLiteNamingStrategyBase();
public IStringSerializer StringSerializer { get; set; }
private Func<string, string> paramNameFilter;
public Func<string, string> ParamNameFilter
{
get => paramNameFilter ?? OrmLiteConfig.ParamNameFilter;
set => paramNameFilter = value;
}
public string DefaultValueFormat = " DEFAULT ({0})";
private EnumConverter enumConverter;
public EnumConverter EnumConverter
{
get => enumConverter;
set
{
value.DialectProvider = this;
enumConverter = value;
}
}
private RowVersionConverter rowVersionConverter;
public RowVersionConverter RowVersionConverter
{
get => rowVersionConverter;
set
{
value.DialectProvider = this;
rowVersionConverter = value;
}
}
private ReferenceTypeConverter referenceTypeConverter;
public ReferenceTypeConverter ReferenceTypeConverter
{
get => referenceTypeConverter;
set
{
value.DialectProvider = this;
referenceTypeConverter = value;
}
}
private ValueTypeConverter valueTypeConverter;
public ValueTypeConverter ValueTypeConverter
{
get => valueTypeConverter;
set
{
value.DialectProvider = this;
valueTypeConverter = value;
}
}
public void RemoveConverter<T>()
{
if (Converters.TryRemove(typeof(T), out var converter))
converter.DialectProvider = null;
}
public void RegisterConverter<T>(IOrmLiteConverter converter)
{
if (converter == null)
throw new ArgumentNullException(nameof(converter));
converter.DialectProvider = this;
Converters[typeof(T)] = converter;
}
public IOrmLiteConverter GetConverter(Type type)
{
type = Nullable.GetUnderlyingType(type) ?? type;
return Converters.TryGetValue(type, out IOrmLiteConverter converter)
? converter
: null;
}
public virtual bool ShouldQuoteValue(Type fieldType)
{
var converter = GetConverter(fieldType);
return converter == null || converter is NativeValueOrmLiteConverter;
}
public virtual object FromDbRowVersion(Type fieldType, object value)
{
return RowVersionConverter.FromDbValue(fieldType, value);
}
public IOrmLiteConverter GetConverterBestMatch(Type type)
{
if (type == typeof(RowVersionConverter))
return RowVersionConverter;
var converter = GetConverter(type);
if (converter != null)
return converter;
if (type.IsEnum)
return EnumConverter;
return type.IsRefType()
? (IOrmLiteConverter)ReferenceTypeConverter
: ValueTypeConverter;
}
public virtual IOrmLiteConverter GetConverterBestMatch(FieldDefinition fieldDef)
{
var fieldType = Nullable.GetUnderlyingType(fieldDef.FieldType) ?? fieldDef.FieldType;
if (fieldDef.IsRowVersion)
return RowVersionConverter;
if (Converters.TryGetValue(fieldType, out var converter))
return converter;
if (fieldType.IsEnum)
return EnumConverter;
return fieldType.IsRefType()
? (IOrmLiteConverter)ReferenceTypeConverter
: ValueTypeConverter;
}
public virtual object ToDbValue(object value, Type type)
{
if (value == null || value is DBNull)
return null;
var converter = GetConverterBestMatch(type);
try
{
return converter.ToDbValue(type, value);
}
catch (Exception ex)
{
Log.Error($"Error in {converter.GetType().Name}.ToDbValue() value '{value.GetType().Name}' and Type '{type.Name}'", ex);
throw;
}
}
public virtual object FromDbValue(object value, Type type)
{
if (value == null || value is DBNull)
return null;
var converter = GetConverterBestMatch(type);
try
{
return converter.FromDbValue(type, value);
}
catch (Exception ex)
{
Log.Error($"Error in {converter.GetType().Name}.FromDbValue() value '{value.GetType().Name}' and Type '{type.Name}'", ex);
throw;
}
}
public object GetValue(IDataReader reader, int columnIndex, Type type)
{
if (Converters.TryGetValue(type, out var converter))
return converter.GetValue(reader, columnIndex, null);
return reader.GetValue(columnIndex);
}
public virtual int GetValues(IDataReader reader, object[] values)
{
return reader.GetValues(values);
}
public abstract IDbConnection CreateConnection(string filePath, Dictionary<string, string> options);
public virtual string GetQuotedValue(string paramValue)
{
return "'" + paramValue.Replace("'", "''") + "'";
}
public virtual string GetSchemaName(string schema)
{
return NamingStrategy.GetSchemaName(schema);
}
public virtual string GetTableName(ModelDefinition modelDef) =>
GetTableName(modelDef.ModelName, modelDef.Schema, useStrategy:true);
public virtual string GetTableName(ModelDefinition modelDef, bool useStrategy) =>
GetTableName(modelDef.ModelName, modelDef.Schema, useStrategy);
public virtual string GetTableName(string table, string schema = null) =>
GetTableName(table, schema, useStrategy: true);
public virtual string GetTableName(string table, string schema, bool useStrategy)
{
if (useStrategy)
{
return schema != null
? $"{QuoteIfRequired(NamingStrategy.GetSchemaName(schema))}.{QuoteIfRequired(NamingStrategy.GetTableName(table))}"
: QuoteIfRequired(NamingStrategy.GetTableName(table));
}
return schema != null
? $"{QuoteIfRequired(schema)}.{QuoteIfRequired(table)}"
: QuoteIfRequired(table);
}
public virtual string GetQuotedTableName(ModelDefinition modelDef)
{
return GetQuotedTableName(modelDef.ModelName, modelDef.Schema);
}
public virtual string GetQuotedTableName(string tableName, string schema = null)
{
if (schema == null)
return GetQuotedName(NamingStrategy.GetTableName(tableName));
var escapedSchema = NamingStrategy.GetSchemaName(schema)
.Replace(".", "\".\"");
return $"{GetQuotedName(escapedSchema)}.{GetQuotedName(NamingStrategy.GetTableName(tableName))}";
}
public virtual string GetQuotedTableName(string tableName, string schema, bool useStrategy) =>
GetQuotedName(GetTableName(tableName, schema, useStrategy));
public virtual string GetQuotedColumnName(string columnName)
{
return GetQuotedName(NamingStrategy.GetColumnName(columnName));
}
public virtual bool ShouldQuote(string name) => !string.IsNullOrEmpty(name) &&
(name.IndexOf(' ') >= 0 || name.IndexOf('.') >= 0);
public virtual string QuoteIfRequired(string name)
{
return ShouldQuote(name)
? GetQuotedName(name)
: name;
}
public virtual string GetQuotedName(string name) => name == null ? null : name.FirstCharEquals('"')
? name : '"' + name + '"';
public virtual string GetQuotedName(string name, string schema)
{
return schema != null
? $"{GetQuotedName(schema)}.{GetQuotedName(name)}"
: GetQuotedName(name);
}
public virtual string SanitizeFieldNameForParamName(string fieldName)
{
return OrmLiteConfig.SanitizeFieldNameForParamNameFn(fieldName);
}
public virtual string GetColumnDefinition(FieldDefinition fieldDef)
{
var fieldDefinition = ResolveFragment(fieldDef.CustomFieldDefinition) ??
GetColumnTypeDefinition(fieldDef.ColumnType, fieldDef.FieldLength, fieldDef.Scale);
var sql = StringBuilderCache.Allocate();
sql.Append($"{GetQuotedColumnName(fieldDef.FieldName)} {fieldDefinition}");
if (fieldDef.IsPrimaryKey)
{
sql.Append(" PRIMARY KEY");
if (fieldDef.AutoIncrement)
{
sql.Append(" ").Append(AutoIncrementDefinition);
}
}
else
{
sql.Append(fieldDef.IsNullable ? " NULL" : " NOT NULL");
}
if (fieldDef.IsUniqueConstraint)
{
sql.Append(" UNIQUE");
}
var defaultValue = GetDefaultValue(fieldDef);
if (!string.IsNullOrEmpty(defaultValue))
{
sql.AppendFormat(DefaultValueFormat, defaultValue);
}
return StringBuilderCache.ReturnAndFree(sql);
}
public virtual string SelectIdentitySql { get; set; }
public virtual long GetLastInsertId(IDbCommand dbCmd)
{
if (SelectIdentitySql == null)
throw new NotImplementedException("Returning last inserted identity is not implemented on this DB Provider.");
dbCmd.CommandText = SelectIdentitySql;
return dbCmd.ExecLongScalar();
}
public virtual string GetLastInsertIdSqlSuffix<T>()
{
if (SelectIdentitySql == null)
throw new NotImplementedException("Returning last inserted identity is not implemented on this DB Provider.");
return "; " + SelectIdentitySql;
}
public virtual bool IsFullSelectStatement(string sql) => !string.IsNullOrEmpty(sql)
&& sql.TrimStart().StartsWith("SELECT", StringComparison.OrdinalIgnoreCase);
// Fmt
public virtual string ToSelectStatement(Type tableType, string sqlFilter, params object[] filterParams)
{
if (IsFullSelectStatement(sqlFilter))
return sqlFilter.SqlFmt(this, filterParams);
var modelDef = tableType.GetModelDefinition();
var sql = StringBuilderCache.Allocate();
sql.Append($"SELECT {GetColumnNames(modelDef)} FROM {GetQuotedTableName(modelDef)}");
if (string.IsNullOrEmpty(sqlFilter))
return StringBuilderCache.ReturnAndFree(sql);
sqlFilter = sqlFilter.SqlFmt(this, filterParams);
if (!sqlFilter.StartsWith("ORDER ", StringComparison.OrdinalIgnoreCase)
&& !sqlFilter.StartsWith("LIMIT ", StringComparison.OrdinalIgnoreCase))
{
sql.Append(" WHERE ");
}
sql.Append(sqlFilter);
return StringBuilderCache.ReturnAndFree(sql);
}
public virtual string ToSelectStatement(ModelDefinition modelDef,
string selectExpression,
string bodyExpression,
string orderByExpression = null,
int? offset = null,
int? rows = null)
{
var sb = StringBuilderCache.Allocate();
sb.Append(selectExpression);
sb.Append(bodyExpression);
if (orderByExpression != null)
{
sb.Append(orderByExpression);
}
if (offset != null || rows != null)
{
sb.Append("\n");
sb.Append(SqlLimit(offset, rows));
}
return StringBuilderCache.ReturnAndFree(sb);
}
public virtual SelectItem GetRowVersionSelectColumn(FieldDefinition field, string tablePrefix = null)
{
return new SelectItemColumn(this, field.FieldName, null, tablePrefix);
}
public virtual string GetRowVersionColumn(FieldDefinition field, string tablePrefix = null)
{
return GetRowVersionSelectColumn(field, tablePrefix).ToString();
}
public virtual string GetColumnNames(ModelDefinition modelDef)
{
return GetColumnNames(modelDef, null).ToSelectString();
}
public virtual SelectItem[] GetColumnNames(ModelDefinition modelDef, string tablePrefix)
{
var quotedPrefix = tablePrefix != null
? GetQuotedTableName(tablePrefix, modelDef.Schema)
: "";
var sqlColumns = new SelectItem[modelDef.FieldDefinitions.Count];
for (var i = 0; i < sqlColumns.Length; ++i)
{
var field = modelDef.FieldDefinitions[i];
if (field.CustomSelect != null)
{
sqlColumns[i] = new SelectItemExpression(this, field.CustomSelect, field.FieldName);
}
else if (field.IsRowVersion)
{
sqlColumns[i] = GetRowVersionSelectColumn(field, quotedPrefix);
}
else
{
sqlColumns[i] = new SelectItemColumn(this, field.FieldName, null, quotedPrefix);
}
}
return sqlColumns;
}
protected virtual bool ShouldSkipInsert(FieldDefinition fieldDef) =>
fieldDef.ShouldSkipInsert();
public virtual FieldDefinition[] GetInsertFieldDefinitions(ModelDefinition modelDef, ICollection<string> insertFields)
{
return insertFields != null
? NamingStrategy.GetType() == typeof(OrmLiteNamingStrategyBase)
? modelDef.GetOrderedFieldDefinitions(insertFields)
: modelDef.GetOrderedFieldDefinitions(insertFields, name => NamingStrategy.GetColumnName(name))
: modelDef.FieldDefinitionsArray;
}
public virtual string ToInsertRowStatement(IDbCommand cmd, object objWithProperties, ICollection<string> insertFields = null)
{
var sbColumnNames = StringBuilderCache.Allocate();
var sbColumnValues = StringBuilderCacheAlt.Allocate();
var modelDef = objWithProperties.GetType().GetModelDefinition();
var fieldDefs = GetInsertFieldDefinitions(modelDef, insertFields);
foreach (var fieldDef in fieldDefs)
{
if (ShouldSkipInsert(fieldDef) && !fieldDef.AutoId)
continue;
if (sbColumnNames.Length > 0)
sbColumnNames.Append(",");
if (sbColumnValues.Length > 0)
sbColumnValues.Append(",");
try
{
sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));
sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));
var p = AddParameter(cmd, fieldDef);
p.Value = GetFieldValue(fieldDef, fieldDef.GetValue(objWithProperties)) ?? DBNull.Value;
}
catch (Exception ex)
{
Log.Error("ERROR in ToInsertRowStatement(): " + ex.Message, ex);
throw;
}
}
var sql = $"INSERT INTO {GetQuotedTableName(modelDef)} ({StringBuilderCache.ReturnAndFree(sbColumnNames)}) " +
$"VALUES ({StringBuilderCacheAlt.ReturnAndFree(sbColumnValues)})";
return sql;
}
public virtual string ToInsertStatement<T>(IDbCommand dbCmd, T item, ICollection<string> insertFields = null)
{
dbCmd.Parameters.Clear();
var dialectProvider = dbCmd.GetDialectProvider();
dialectProvider.PrepareParameterizedInsertStatement<T>(dbCmd, insertFields);
if (string.IsNullOrEmpty(dbCmd.CommandText))
return null;
dialectProvider.SetParameterValues<T>(dbCmd, item);
return MergeParamsIntoSql(dbCmd.CommandText, ToArray(dbCmd.Parameters));
}
protected virtual object GetInsertDefaultValue(FieldDefinition fieldDef)
{
if (!fieldDef.AutoId)
return null;
if (fieldDef.FieldType == typeof(Guid))
return Guid.NewGuid();
return null;
}
public virtual void PrepareParameterizedInsertStatement<T>(IDbCommand cmd, ICollection<string> insertFields = null)
{
var sbColumnNames = StringBuilderCache.Allocate();
var sbColumnValues = StringBuilderCacheAlt.Allocate();
var modelDef = typeof(T).GetModelDefinition();
cmd.Parameters.Clear();
var fieldDefs = GetInsertFieldDefinitions(modelDef, insertFields);
foreach (var fieldDef in fieldDefs)
{
if (fieldDef.ShouldSkipInsert())
continue;
if (sbColumnNames.Length > 0)
sbColumnNames.Append(",");
if (sbColumnValues.Length > 0)
sbColumnValues.Append(",");
try
{
sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));
sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));
var p = AddParameter(cmd, fieldDef);
if (fieldDef.AutoId)
{
p.Value = GetInsertDefaultValue(fieldDef);
}
}
catch (Exception ex)
{
Log.Error("ERROR in PrepareParameterizedInsertStatement(): " + ex.Message, ex);
throw;
}
}
cmd.CommandText = $"INSERT INTO {GetQuotedTableName(modelDef)} ({StringBuilderCache.ReturnAndFree(sbColumnNames)}) " +
$"VALUES ({StringBuilderCacheAlt.ReturnAndFree(sbColumnValues)})";
}
public virtual void PrepareInsertRowStatement<T>(IDbCommand dbCmd, Dictionary<string, object> args)
{
var sbColumnNames = StringBuilderCache.Allocate();
var sbColumnValues = StringBuilderCacheAlt.Allocate();
var modelDef = typeof(T).GetModelDefinition();
dbCmd.Parameters.Clear();
foreach (var entry in args)
{
var fieldDef = modelDef.GetFieldDefinition(entry.Key);
if (fieldDef.ShouldSkipInsert())
continue;
var value = entry.Value;
if (sbColumnNames.Length > 0)
sbColumnNames.Append(",");
if (sbColumnValues.Length > 0)
sbColumnValues.Append(",");
try
{
sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));
sbColumnValues.Append(this.AddUpdateParam(dbCmd, value, fieldDef).ParameterName);
}
catch (Exception ex)
{
Log.Error("ERROR in PrepareInsertRowStatement(): " + ex.Message, ex);
throw;
}
}
dbCmd.CommandText = $"INSERT INTO {GetQuotedTableName(modelDef)} ({StringBuilderCache.ReturnAndFree(sbColumnNames)}) " +
$"VALUES ({StringBuilderCacheAlt.ReturnAndFree(sbColumnValues)})";
}
public virtual string ToUpdateStatement<T>(IDbCommand dbCmd, T item, ICollection<string> updateFields = null)
{
dbCmd.Parameters.Clear();
var dialectProvider = dbCmd.GetDialectProvider();
dialectProvider.PrepareParameterizedUpdateStatement<T>(dbCmd);
if (string.IsNullOrEmpty(dbCmd.CommandText))
return null;
dialectProvider.SetParameterValues<T>(dbCmd, item);
return MergeParamsIntoSql(dbCmd.CommandText, ToArray(dbCmd.Parameters));
}
IDbDataParameter[] ToArray(IDataParameterCollection dbParams)
{
var to = new IDbDataParameter[dbParams.Count];
for (int i = 0; i < dbParams.Count; i++)
{
to[i] = (IDbDataParameter)dbParams[i];
}
return to;
}
public virtual string MergeParamsIntoSql(string sql, IEnumerable<IDbDataParameter> dbParams)
{
foreach (var dbParam in dbParams)
{
var quotedValue = dbParam.Value != null
? GetQuotedValue(dbParam.Value, dbParam.Value.GetType())
: "null";
var pattern = dbParam.ParameterName + @"(,|\s|\)|$)";
var replacement = quotedValue.Replace("$", "$$") + "$1";
sql = Regex.Replace(sql, pattern, replacement);
}
return sql;
}
public virtual bool PrepareParameterizedUpdateStatement<T>(IDbCommand cmd, ICollection<string> updateFields = null)
{
var sql = StringBuilderCache.Allocate();
var sqlFilter = StringBuilderCacheAlt.Allocate();
var modelDef = typeof(T).GetModelDefinition();
var hadRowVersion = false;
var updateAllFields = updateFields == null || updateFields.Count == 0;
cmd.Parameters.Clear();
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if (fieldDef.ShouldSkipUpdate())
continue;
try
{
if ((fieldDef.IsPrimaryKey || fieldDef.IsRowVersion) && updateAllFields)
{
if (sqlFilter.Length > 0)
sqlFilter.Append(" AND ");
AppendFieldCondition(sqlFilter, fieldDef, cmd);
if (fieldDef.IsRowVersion)
hadRowVersion = true;
continue;
}
if (!updateAllFields && !updateFields.Contains(fieldDef.Name, StringComparer.OrdinalIgnoreCase))
continue;
if (sql.Length > 0)
sql.Append(", ");
sql
.Append(GetQuotedColumnName(fieldDef.FieldName))
.Append("=")
.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));
AddParameter(cmd, fieldDef);
}
catch (Exception ex)
{
OrmLiteUtils.HandleException(ex, "ERROR in PrepareParameterizedUpdateStatement(): " + ex.Message);
}
}
if (sql.Length > 0)
{
var strFilter = StringBuilderCacheAlt.ReturnAndFree(sqlFilter);
cmd.CommandText = $"UPDATE {GetQuotedTableName(modelDef)} " +
$"SET {StringBuilderCache.ReturnAndFree(sql)} {(strFilter.Length > 0 ? "WHERE " + strFilter : "")}";
}
else
{
cmd.CommandText = "";
}
return hadRowVersion;
}
public virtual void AppendNullFieldCondition(StringBuilder sqlFilter, FieldDefinition fieldDef)
{
sqlFilter
.Append(GetQuotedColumnName(fieldDef.FieldName))
.Append(" IS NULL");
}
public virtual void AppendFieldCondition(StringBuilder sqlFilter, FieldDefinition fieldDef, IDbCommand cmd)
{
sqlFilter
.Append(GetQuotedColumnName(fieldDef.FieldName))
.Append("=")
.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));
AddParameter(cmd, fieldDef);
}
public virtual bool PrepareParameterizedDeleteStatement<T>(IDbCommand cmd, IDictionary<string, object> deleteFieldValues)
{
if (deleteFieldValues == null || deleteFieldValues.Count == 0)
throw new ArgumentException("DELETE's must have at least 1 criteria");
var sqlFilter = StringBuilderCache.Allocate();
var modelDef = typeof(T).GetModelDefinition();
var hadRowVersion = false;
cmd.Parameters.Clear();
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if (fieldDef.ShouldSkipDelete())
continue;
if (!deleteFieldValues.TryGetValue(fieldDef.Name, out var fieldValue))
continue;
if (fieldDef.IsRowVersion)
hadRowVersion = true;
try
{
if (sqlFilter.Length > 0)
sqlFilter.Append(" AND ");
if (fieldValue != null)
{
AppendFieldCondition(sqlFilter, fieldDef, cmd);
}
else
{
AppendNullFieldCondition(sqlFilter, fieldDef);
}
}
catch (Exception ex)
{
OrmLiteUtils.HandleException(ex, "ERROR in PrepareParameterizedDeleteStatement(): " + ex.Message);
}
}
cmd.CommandText = $"DELETE FROM {GetQuotedTableName(modelDef)} WHERE {StringBuilderCache.ReturnAndFree(sqlFilter)}";
return hadRowVersion;
}
public virtual void PrepareStoredProcedureStatement<T>(IDbCommand cmd, T obj)
{
cmd.CommandText = ToExecuteProcedureStatement(obj);
cmd.CommandType = CommandType.StoredProcedure;
}
/// <summary>
/// Used for adding updated DB params in INSERT and UPDATE statements
/// </summary>
protected IDbDataParameter AddParameter(IDbCommand cmd, FieldDefinition fieldDef)
{
var p = cmd.CreateParameter();
SetParameter(fieldDef, p);
InitUpdateParam(p);
cmd.Parameters.Add(p);
return p;
}
public virtual void SetParameter(FieldDefinition fieldDef, IDbDataParameter p)
{
p.ParameterName = this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName));
InitDbParam(p, fieldDef.ColumnType);
}
public virtual void SetParameterValues<T>(IDbCommand dbCmd, object obj)
{
var modelDef = GetModel(typeof(T));
var fieldMap = GetFieldDefinitionMap(modelDef);
foreach (IDataParameter p in dbCmd.Parameters)
{
var fieldName = this.ToFieldName(p.ParameterName);
fieldMap.TryGetValue(fieldName, out var fieldDef);
if (fieldDef == null)
{
if (ParamNameFilter != null)
{
fieldDef = modelDef.GetFieldDefinition(name =>
string.Equals(ParamNameFilter(name), fieldName, StringComparison.OrdinalIgnoreCase));
}
if (fieldDef == null)
throw new ArgumentException($"Field Definition '{fieldName}' was not found");
}
if (fieldDef.AutoId && p.Value != null)
{
var existingId = fieldDef.GetValueFn(obj);
if (existingId is Guid existingGuid && existingGuid != default(Guid))
{
p.Value = existingGuid; // Use existing value if not default
}
fieldDef.SetValueFn(obj, p.Value); //Auto populate default values
continue;
}
SetParameterValue<T>(fieldDef, p, obj);
}
}
public Dictionary<string, FieldDefinition> GetFieldDefinitionMap(ModelDefinition modelDef)
{
return modelDef.GetFieldDefinitionMap(SanitizeFieldNameForParamName);
}
public virtual void SetParameterValue<T>(FieldDefinition fieldDef, IDataParameter p, object obj)
{
var value = GetValueOrDbNull<T>(fieldDef, obj);
p.Value = value;
if (p.Value is string s && p is IDbDataParameter dataParam && dataParam.Size > 0 && s.Length > dataParam.Size)
{
// db param Size set in StringConverter
dataParam.Size = s.Length;
}
}
protected virtual object GetValue<T>(FieldDefinition fieldDef, object obj)
{
var value = obj is T
? fieldDef.GetValue(obj)
: GetAnonValue(fieldDef, obj);
return GetFieldValue(fieldDef, value);
}
public object GetFieldValue(FieldDefinition fieldDef, object value)
{
if (value == null)
return null;
var converter = GetConverterBestMatch(fieldDef);
try
{
return converter.ToDbValue(fieldDef.FieldType, value);
}
catch (Exception ex)
{
Log.Error($"Error in {converter.GetType().Name}.ToDbValue() for field '{fieldDef.Name}' of Type '{fieldDef.FieldType}' with value '{value.GetType().Name}'", ex);
throw;
}
}
public object GetFieldValue(Type fieldType, object value)
{
if (value == null)
return null;
var converter = GetConverterBestMatch(fieldType);
try
{
return converter.ToDbValue(fieldType, value);
}
catch (Exception ex)
{
Log.Error($"Error in {converter.GetType().Name}.ToDbValue() for field of Type '{fieldType}' with value '{value.GetType().Name}'", ex);
throw;
}
}
protected virtual object GetValueOrDbNull<T>(FieldDefinition fieldDef, object obj)
{
var value = GetValue<T>(fieldDef, obj);
if (value == null)
return DBNull.Value;
return value;
}
protected virtual object GetQuotedValueOrDbNull<T>(FieldDefinition fieldDef, object obj)
{
var value = obj is T
? fieldDef.GetValue(obj)
: GetAnonValue(fieldDef, obj);
if (value == null)
return DBNull.Value;
var unquotedVal = GetQuotedValue(value, fieldDef.FieldType)
.TrimStart('\'').TrimEnd('\''); ;
if (string.IsNullOrEmpty(unquotedVal))
return DBNull.Value;
return unquotedVal;
}
static readonly ConcurrentDictionary<string, GetMemberDelegate> anonValueFnMap =
new ConcurrentDictionary<string, GetMemberDelegate>();
protected virtual object GetAnonValue(FieldDefinition fieldDef, object obj)
{
var anonType = obj.GetType();
var key = anonType.Name + "." + fieldDef.Name;
var factoryFn = (Func<string, GetMemberDelegate>)(_ =>
anonType.GetProperty(fieldDef.Name).CreateGetter());
var getterFn = anonValueFnMap.GetOrAdd(key, factoryFn);
return getterFn(obj);
}
public virtual void PrepareUpdateRowStatement(IDbCommand dbCmd, object objWithProperties, ICollection<string> updateFields = null)
{
var sql = StringBuilderCache.Allocate();
var sqlFilter = StringBuilderCacheAlt.Allocate();
var modelDef = objWithProperties.GetType().GetModelDefinition();
var updateAllFields = updateFields == null || updateFields.Count == 0;
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if (fieldDef.ShouldSkipUpdate())
continue;
try
{
if (fieldDef.IsPrimaryKey && updateAllFields)
{
if (sqlFilter.Length > 0)
sqlFilter.Append(" AND ");
sqlFilter
.Append(GetQuotedColumnName(fieldDef.FieldName))
.Append("=")
.Append(this.AddQueryParam(dbCmd, fieldDef.GetValue(objWithProperties), fieldDef).ParameterName);
continue;
}
if (!updateAllFields && !updateFields.Contains(fieldDef.Name, StringComparer.OrdinalIgnoreCase) || fieldDef.AutoIncrement)
continue;
if (sql.Length > 0)
sql.Append(", ");
sql
.Append(GetQuotedColumnName(fieldDef.FieldName))
.Append("=")
.Append(this.AddUpdateParam(dbCmd, fieldDef.GetValue(objWithProperties), fieldDef).ParameterName);
}
catch (Exception ex)
{
OrmLiteUtils.HandleException(ex, "ERROR in ToUpdateRowStatement(): " + ex.Message);
}
}
var strFilter = StringBuilderCacheAlt.ReturnAndFree(sqlFilter);
dbCmd.CommandText = $"UPDATE {GetQuotedTableName(modelDef)} " +
$"SET {StringBuilderCache.ReturnAndFree(sql)}{(strFilter.Length > 0 ? " WHERE " + strFilter : "")}";
if (sql.Length == 0)
throw new Exception("No valid update properties provided (e.g. p => p.FirstName): " + dbCmd.CommandText);
}
public virtual void PrepareUpdateRowStatement<T>(IDbCommand dbCmd, Dictionary<string, object> args, string sqlFilter)
{
var sql = StringBuilderCache.Allocate();
var modelDef = typeof(T).GetModelDefinition();
foreach (var entry in args)
{
var fieldDef = modelDef.GetFieldDefinition(entry.Key);
if (fieldDef.ShouldSkipUpdate() || fieldDef.IsPrimaryKey || fieldDef.AutoIncrement)
continue;
var value = entry.Value;
try
{
if (sql.Length > 0)
sql.Append(", ");
sql
.Append(GetQuotedColumnName(fieldDef.FieldName))
.Append("=")
.Append(this.AddUpdateParam(dbCmd, value, fieldDef).ParameterName);
}
catch (Exception ex)
{
OrmLiteUtils.HandleException(ex, "ERROR in PrepareUpdateRowStatement(cmd,args): " + ex.Message);
}
}
dbCmd.CommandText = $"UPDATE {GetQuotedTableName(modelDef)} " +
$"SET {StringBuilderCache.ReturnAndFree(sql)}{(string.IsNullOrEmpty(sqlFilter) ? "" : " ")}{sqlFilter}";
if (sql.Length == 0)
throw new Exception("No valid update properties provided (e.g. () => new Person { Age = 27 }): " + dbCmd.CommandText);
}
public virtual void PrepareUpdateRowAddStatement<T>(IDbCommand dbCmd, Dictionary<string, object> args, string sqlFilter)
{
var sql = StringBuilderCache.Allocate();
var modelDef = typeof(T).GetModelDefinition();
foreach (var entry in args)
{
var fieldDef = modelDef.GetFieldDefinition(entry.Key);
if (fieldDef.ShouldSkipUpdate() || fieldDef.AutoIncrement || fieldDef.IsPrimaryKey ||
fieldDef.IsRowVersion || fieldDef.Name == OrmLiteConfig.IdField)
continue;
var value = entry.Value;
try
{
if (sql.Length > 0)
sql.Append(", ");
var quotedFieldName = GetQuotedColumnName(fieldDef.FieldName);
if (fieldDef.FieldType.IsNumericType())
{
sql
.Append(quotedFieldName)
.Append("=")
.Append(quotedFieldName)
.Append("+")
.Append(this.AddUpdateParam(dbCmd, value, fieldDef).ParameterName);
}
else
{
sql
.Append(quotedFieldName)
.Append("=")
.Append(this.AddUpdateParam(dbCmd, value, fieldDef).ParameterName);
}
}
catch (Exception ex)
{
OrmLiteUtils.HandleException(ex, "ERROR in PrepareUpdateRowAddStatement(): " + ex.Message);
}
}
dbCmd.CommandText = $"UPDATE {GetQuotedTableName(modelDef)} " +
$"SET {StringBuilderCache.ReturnAndFree(sql)}{(string.IsNullOrEmpty(sqlFilter) ? "" : " ")}{sqlFilter}";
if (sql.Length == 0)
throw new Exception("No valid update properties provided (e.g. () => new Person { Age = 27 }): " + dbCmd.CommandText);
}
public virtual string ToDeleteStatement(Type tableType, string sqlFilter, params object[] filterParams)
{
var sql = StringBuilderCache.Allocate();
const string deleteStatement = "DELETE ";
var isFullDeleteStatement =
!string.IsNullOrEmpty(sqlFilter)
&& sqlFilter.Length > deleteStatement.Length
&& sqlFilter.Substring(0, deleteStatement.Length).ToUpper().Equals(deleteStatement);
if (isFullDeleteStatement)
return sqlFilter.SqlFmt(this, filterParams);
var modelDef = tableType.GetModelDefinition();
sql.Append($"DELETE FROM {GetQuotedTableName(modelDef)}");
if (string.IsNullOrEmpty(sqlFilter))
return StringBuilderCache.ReturnAndFree(sql);
sqlFilter = sqlFilter.SqlFmt(this, filterParams);
sql.Append(" WHERE ");
sql.Append(sqlFilter);
return StringBuilderCache.ReturnAndFree(sql);
}
public virtual bool HasInsertReturnValues(ModelDefinition modelDef) =>
modelDef.FieldDefinitions.Any(x => x.ReturnOnInsert);
public string GetDefaultValue(Type tableType, string fieldName)
{
var modelDef = tableType.GetModelDefinition();
var fieldDef = modelDef.GetFieldDefinition(fieldName);
return GetDefaultValue(fieldDef);
}
public virtual string GetDefaultValue(FieldDefinition fieldDef)
{
var defaultValue = fieldDef.DefaultValue;
if (string.IsNullOrEmpty(defaultValue))
{
return fieldDef.AutoId
? GetAutoIdDefaultValue(fieldDef)
: null;
}
return ResolveFragment(defaultValue);
}
public virtual string ResolveFragment(string sql)
{
if (string.IsNullOrEmpty(sql))
return null;
if (!sql.StartsWith("{"))
return sql;
return Variables.TryGetValue(sql, out var variable)
? variable
: null;
}
public virtual string GetAutoIdDefaultValue(FieldDefinition fieldDef) => null;
public Func<ModelDefinition, List<FieldDefinition>> CreateTableFieldsStrategy { get; set; } = GetFieldDefinitions;
public static List<FieldDefinition> GetFieldDefinitions(ModelDefinition modelDef) => modelDef.FieldDefinitions;
public abstract string ToCreateSchemaStatement(string schemaName);
public abstract bool DoesSchemaExist(IDbCommand dbCmd, string schemaName);
public virtual string ToCreateTableStatement(Type tableType)
{
var sbColumns = StringBuilderCache.Allocate();
var sbConstraints = StringBuilderCacheAlt.Allocate();
var modelDef = tableType.GetModelDefinition();
foreach (var fieldDef in CreateTableFieldsStrategy(modelDef))
{
if (fieldDef.CustomSelect != null)
continue;
var columnDefinition = GetColumnDefinition(fieldDef);
if (columnDefinition == null)
continue;
if (sbColumns.Length != 0)
sbColumns.Append(", \n ");
sbColumns.Append(columnDefinition);
var sqlConstraint = GetCheckConstraint(modelDef, fieldDef);
if (sqlConstraint != null)
{
sbConstraints.Append(",\n" + sqlConstraint);
}
if (fieldDef.ForeignKey == null || OrmLiteConfig.SkipForeignKeys)
continue;
var refModelDef = fieldDef.ForeignKey.ReferenceType.GetModelDefinition();
sbConstraints.Append(
$", \n\n CONSTRAINT {GetQuotedName(fieldDef.ForeignKey.GetForeignKeyName(modelDef, refModelDef, NamingStrategy, fieldDef))} " +
$"FOREIGN KEY ({GetQuotedColumnName(fieldDef.FieldName)}) " +
$"REFERENCES {GetQuotedTableName(refModelDef)} ({GetQuotedColumnName(refModelDef.PrimaryKey.FieldName)})");
sbConstraints.Append(GetForeignKeyOnDeleteClause(fieldDef.ForeignKey));
sbConstraints.Append(GetForeignKeyOnUpdateClause(fieldDef.ForeignKey));
}
var uniqueConstraints = GetUniqueConstraints(modelDef);
if (uniqueConstraints != null)
{
sbConstraints.Append(",\n" + uniqueConstraints);
}
var sql = $"CREATE TABLE {GetQuotedTableName(modelDef)} " +
$"\n(\n {StringBuilderCache.ReturnAndFree(sbColumns)}{StringBuilderCacheAlt.ReturnAndFree(sbConstraints)} \n); \n";
return sql;
}
public virtual string GetUniqueConstraints(ModelDefinition modelDef)
{
var constraints = modelDef.UniqueConstraints.Map(x =>
$"CONSTRAINT {GetUniqueConstraintName(x, GetTableName(modelDef).StripDbQuotes())} UNIQUE ({x.FieldNames.Map(f => modelDef.GetQuotedName(f,this)).Join(",")})" );
return constraints.Count > 0
? constraints.Join(",\n")
: null;
}
protected virtual string GetUniqueConstraintName(UniqueConstraintAttribute constraint, string tableName) =>
constraint.Name ?? $"UC_{tableName}_{constraint.FieldNames.Join("_")}";
public virtual string GetCheckConstraint(ModelDefinition modelDef, FieldDefinition fieldDef)
{
if (fieldDef.CheckConstraint == null)
return null;
return $"CONSTRAINT CHK_{modelDef.Schema}_{modelDef.ModelName}_{fieldDef.FieldName} CHECK ({fieldDef.CheckConstraint})";
}
public virtual string ToPostCreateTableStatement(ModelDefinition modelDef)
{
return null;
}
public virtual string ToPostDropTableStatement(ModelDefinition modelDef)
{
return null;
}
public virtual string GetForeignKeyOnDeleteClause(ForeignKeyConstraint foreignKey)
{
return !string.IsNullOrEmpty(foreignKey.OnDelete) ? " ON DELETE " + foreignKey.OnDelete : "";
}
public virtual string GetForeignKeyOnUpdateClause(ForeignKeyConstraint foreignKey)
{
return !string.IsNullOrEmpty(foreignKey.OnUpdate) ? " ON UPDATE " + foreignKey.OnUpdate : "";
}
public virtual List<string> ToCreateIndexStatements(Type tableType)
{
var sqlIndexes = new List<string>();
var modelDef = tableType.GetModelDefinition();
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if (!fieldDef.IsIndexed) continue;
var indexName = fieldDef.IndexName
?? GetIndexName(fieldDef.IsUniqueIndex, modelDef.ModelName.SafeVarName(), fieldDef.FieldName);
sqlIndexes.Add(
ToCreateIndexStatement(fieldDef.IsUniqueIndex, indexName, modelDef, fieldDef.FieldName, isCombined: false, fieldDef: fieldDef));
}
foreach (var compositeIndex in modelDef.CompositeIndexes)
{
var indexName = GetCompositeIndexName(compositeIndex, modelDef);
var sb = StringBuilderCache.Allocate();
foreach (var fieldName in compositeIndex.FieldNames)
{
if (sb.Length > 0)
sb.Append(", ");
var parts = fieldName.SplitOnLast(' ');
if (parts.Length == 2 && (parts[1].ToLower().StartsWith("desc") || parts[1].ToLower().StartsWith("asc")))
{
sb.Append(GetQuotedColumnName(parts[0]))
.Append(' ')
.Append(parts[1]);
}
else
{
sb.Append(GetQuotedColumnName(fieldName));
}
}
sqlIndexes.Add(
ToCreateIndexStatement(compositeIndex.Unique, indexName, modelDef,
StringBuilderCache.ReturnAndFree(sb),
isCombined: true));
}
return sqlIndexes;
}
public virtual bool DoesTableExist(IDbConnection db, string tableName, string schema = null)
{
return db.Exec(dbCmd => DoesTableExist(dbCmd, tableName, schema));
}
public virtual bool DoesTableExist(IDbCommand dbCmd, string tableName, string schema = null)
{
throw new NotImplementedException();
}
public virtual bool DoesColumnExist(IDbConnection db, string columnName, string tableName, string schema = null)
{
throw new NotImplementedException();
}
public virtual bool DoesSequenceExist(IDbCommand dbCmd, string sequenceName)
{
throw new NotImplementedException();
}
protected virtual string GetIndexName(bool isUnique, string modelName, string fieldName)
{
return $"{(isUnique ? "u" : "")}idx_{modelName}_{fieldName}".ToLower();
}
protected virtual string GetCompositeIndexName(CompositeIndexAttribute compositeIndex, ModelDefinition modelDef)
{
return compositeIndex.Name ?? GetIndexName(compositeIndex.Unique, modelDef.ModelName.SafeVarName(),
string.Join("_", compositeIndex.FieldNames.Map(x => x.LeftPart(' ')).ToArray()));
}
protected virtual string GetCompositeIndexNameWithSchema(CompositeIndexAttribute compositeIndex, ModelDefinition modelDef)
{
return compositeIndex.Name ?? GetIndexName(compositeIndex.Unique,
(modelDef.IsInSchema
? modelDef.Schema + "_" + GetQuotedTableName(modelDef)
: GetQuotedTableName(modelDef)).SafeVarName(),
string.Join("_", compositeIndex.FieldNames.ToArray()));
}
protected virtual string ToCreateIndexStatement(bool isUnique, string indexName, ModelDefinition modelDef, string fieldName,
bool isCombined = false, FieldDefinition fieldDef = null)
{
return $"CREATE {(isUnique ? "UNIQUE" : "")}" +
(fieldDef?.IsClustered == true ? " CLUSTERED" : "") +
(fieldDef?.IsNonClustered == true ? " NONCLUSTERED" : "") +
$" INDEX {indexName} ON {GetQuotedTableName(modelDef)} " +
$"({(isCombined ? fieldName : GetQuotedColumnName(fieldName))}); \n";
}
public virtual List<string> ToCreateSequenceStatements(Type tableType)
{
return new List<string>();
}
public virtual string ToCreateSequenceStatement(Type tableType, string sequenceName)
{
return "";
}
public virtual List<string> SequenceList(Type tableType)
{
return new List<string>();
}
// TODO : make abstract ??
public virtual string ToExistStatement(Type fromTableType,
object objWithProperties,
string sqlFilter,
params object[] filterParams)
{
throw new NotImplementedException();
}
// TODO : make abstract ??
public virtual string ToSelectFromProcedureStatement(
object fromObjWithProperties,
Type outputModelType,
string sqlFilter,
params object[] filterParams)
{
throw new NotImplementedException();
}
// TODO : make abstract ??
public virtual string ToExecuteProcedureStatement(object objWithProperties)
{
return null;
}
protected static ModelDefinition GetModel(Type modelType)
{
return modelType.GetModelDefinition();
}
public virtual SqlExpression<T> SqlExpression<T>()
{
throw new NotImplementedException();
}
public IDbCommand CreateParameterizedDeleteStatement(IDbConnection connection, object objWithProperties)
{
throw new NotImplementedException();
}
public virtual string GetDropForeignKeyConstraints(ModelDefinition modelDef)
{
return null;
}
public virtual string ToAddColumnStatement(Type modelType, FieldDefinition fieldDef)
{
var column = GetColumnDefinition(fieldDef);
return $"ALTER TABLE {GetQuotedTableName(modelType.GetModelDefinition())} ADD COLUMN {column};";
}
public virtual string ToAlterColumnStatement(Type modelType, FieldDefinition fieldDef)
{
var column = GetColumnDefinition(fieldDef);
return $"ALTER TABLE {GetQuotedTableName(modelType.GetModelDefinition())} MODIFY COLUMN {column};";
}
public virtual string ToChangeColumnNameStatement(Type modelType, FieldDefinition fieldDef, string oldColumnName)
{
var column = GetColumnDefinition(fieldDef);
return $"ALTER TABLE {GetQuotedTableName(modelType.GetModelDefinition())} CHANGE COLUMN {GetQuotedColumnName(oldColumnName)} {column};";
}
public virtual string ToAddForeignKeyStatement<T, TForeign>(Expression<Func<T, object>> field,
Expression<Func<TForeign, object>> foreignField,
OnFkOption onUpdate,
OnFkOption onDelete,
string foreignKeyName = null)
{
var sourceMD = ModelDefinition<T>.Definition;
var fieldName = sourceMD.GetFieldDefinition(field).FieldName;
var referenceMD = ModelDefinition<TForeign>.Definition;
var referenceFieldName = referenceMD.GetFieldDefinition(foreignField).FieldName;
string name = GetQuotedName(foreignKeyName.IsNullOrEmpty() ?
"fk_" + sourceMD.ModelName + "_" + fieldName + "_" + referenceFieldName :
foreignKeyName);
return $"ALTER TABLE {GetQuotedTableName(sourceMD)} " +
$"ADD CONSTRAINT {name} FOREIGN KEY ({GetQuotedColumnName(fieldName)}) " +
$"REFERENCES {GetQuotedTableName(referenceMD)} " +
$"({GetQuotedColumnName(referenceFieldName)})" +
$"{GetForeignKeyOnDeleteClause(new ForeignKeyConstraint(typeof(T), onDelete: FkOptionToString(onDelete)))}" +
$"{GetForeignKeyOnUpdateClause(new ForeignKeyConstraint(typeof(T), onUpdate: FkOptionToString(onUpdate)))};";
}
public virtual string ToCreateIndexStatement<T>(Expression<Func<T, object>> field, string indexName = null, bool unique = false)
{
var sourceDef = ModelDefinition<T>.Definition;
var fieldName = sourceDef.GetFieldDefinition(field).FieldName;
string name = GetQuotedName(indexName.IsNullOrEmpty() ?
(unique ? "uidx" : "idx") + "_" + sourceDef.ModelName + "_" + fieldName :
indexName);
string command = $"CREATE {(unique ? "UNIQUE" : "")} " +
$"INDEX {name} ON {GetQuotedTableName(sourceDef)}" +
$"({GetQuotedColumnName(fieldName)});";
return command;
}
protected virtual string FkOptionToString(OnFkOption option)
{
switch (option)
{
case OnFkOption.Cascade: return "CASCADE";
case OnFkOption.NoAction: return "NO ACTION";
case OnFkOption.SetNull: return "SET NULL";
case OnFkOption.SetDefault: return "SET DEFAULT";
case OnFkOption.Restrict:
default: return "RESTRICT";
}
}
public virtual string GetQuotedValue(object value, Type fieldType)
{
if (value == null) return "NULL";
var converter = value.GetType().IsEnum
? EnumConverter
: GetConverterBestMatch(fieldType);
try
{
return converter.ToQuotedString(fieldType, value);
}
catch (Exception ex)
{
Log.Error($"Error in {converter.GetType().Name}.ToQuotedString() value '{converter.GetType().Name}' and Type '{value.GetType().Name}'", ex);
throw;
}
}
public virtual object GetParamValue(object value, Type fieldType)
{
return ToDbValue(value, fieldType);
}
public virtual void InitQueryParam(IDbDataParameter param) {}
public virtual void InitUpdateParam(IDbDataParameter param) {}
public virtual string EscapeWildcards(string value)
{
return value?.Replace("^", @"^^")
.Replace(@"\", @"^\")
.Replace("_", @"^_")
.Replace("%", @"^%");
}
public virtual string GetLoadChildrenSubSelect<From>(SqlExpression<From> expr)
{
var modelDef = expr.ModelDef;
expr.UnsafeSelect(this.GetQuotedColumnName(modelDef, modelDef.PrimaryKey));
var subSql = expr.ToSelectStatement();
return subSql;
}
public virtual string ToRowCountStatement(string innerSql)
{
return $"SELECT COUNT(*) FROM ({innerSql}) AS COUNT";
}
public virtual void DropColumn(IDbConnection db, Type modelType, string columnName)
{
var provider = db.GetDialectProvider();
var command = ToDropColumnStatement(modelType, columnName, provider);
db.ExecuteSql(command);
}
protected virtual string ToDropColumnStatement(Type modelType, string columnName, IOrmLiteDialectProvider provider)
{
return $"ALTER TABLE {provider.GetQuotedTableName(modelType.GetModelDefinition())} " +
$"DROP COLUMN {provider.GetQuotedColumnName(columnName)};";
}
public virtual string ToTableNamesStatement(string schema) => throw new NotSupportedException();
public virtual string ToTableNamesWithRowCountsStatement(bool live, string schema) => null; //returning null Fallsback to slow UNION N+1 COUNT(*) op
public virtual string SqlConflict(string sql, string conflictResolution) => sql; //NOOP
public virtual string SqlConcat(IEnumerable<object> args) => $"CONCAT({string.Join(", ", args)})";
public virtual string SqlCurrency(string fieldOrValue) => SqlCurrency(fieldOrValue, "$");
public virtual string SqlCurrency(string fieldOrValue, string currencySymbol) => SqlConcat(new List<string> { currencySymbol, fieldOrValue });
public virtual string SqlBool(bool value) => value ? "true" : "false";
public virtual string SqlLimit(int? offset = null, int? rows = null) => rows == null && offset == null
? ""
: offset == null
? "LIMIT " + rows
: "LIMIT " + rows.GetValueOrDefault(int.MaxValue) + " OFFSET " + offset;
public virtual string SqlCast(object fieldOrValue, string castAs) => $"CAST({fieldOrValue} AS {castAs})";
//Async API's, should be overrided by Dialect Providers to use .ConfigureAwait(false)
//Default impl below uses TaskAwaiter shim in async.cs
public virtual Task OpenAsync(IDbConnection db, CancellationToken token = default(CancellationToken))
{
db.Open();
return TaskResult.Finished;
}
public virtual Task<IDataReader> ExecuteReaderAsync(IDbCommand cmd, CancellationToken token = default(CancellationToken))
{
return cmd.ExecuteReader().InTask();
}
public virtual Task<int> ExecuteNonQueryAsync(IDbCommand cmd, CancellationToken token = default(CancellationToken))
{
return cmd.ExecuteNonQuery().InTask();
}
public virtual Task<object> ExecuteScalarAsync(IDbCommand cmd, CancellationToken token = default(CancellationToken))
{
return cmd.ExecuteScalar().InTask();
}
public virtual Task<bool> ReadAsync(IDataReader reader, CancellationToken token = default(CancellationToken))
{
return reader.Read().InTask();
}
#if ASYNC
public virtual async Task<List<T>> ReaderEach<T>(IDataReader reader, Func<T> fn, CancellationToken token = default(CancellationToken))
{
try
{
var to = new List<T>();
while (await ReadAsync(reader, token))
{
var row = fn();
to.Add(row);
}
return to;
}
finally
{
reader.Dispose();
}
}
public virtual async Task<Return> ReaderEach<Return>(IDataReader reader, Action fn, Return source, CancellationToken token = default(CancellationToken))
{
try
{
while (await ReadAsync(reader, token))
{
fn();
}
return source;
}
finally
{
reader.Dispose();
}
}
public virtual async Task<T> ReaderRead<T>(IDataReader reader, Func<T> fn, CancellationToken token = default(CancellationToken))
{
try
{
if (await ReadAsync(reader, token))
return fn();
return default(T);
}
finally
{
reader.Dispose();
}
}
public virtual Task<long> InsertAndGetLastInsertIdAsync<T>(IDbCommand dbCmd, CancellationToken token)
{
if (SelectIdentitySql == null)
return new NotImplementedException("Returning last inserted identity is not implemented on this DB Provider.")
.InTask<long>();
dbCmd.CommandText += "; " + SelectIdentitySql;
return dbCmd.ExecLongScalarAsync(null, token);
}
#else
public Task<List<T>> ReaderEach<T>(IDataReader reader, Func<T> fn, CancellationToken token = new CancellationToken())
{
throw new NotImplementedException(OrmLiteUtils.AsyncRequiresNet45Error);
}
public Task<Return> ReaderEach<Return>(IDataReader reader, Action fn, Return source, CancellationToken token = new CancellationToken())
{
throw new NotImplementedException(OrmLiteUtils.AsyncRequiresNet45Error);
}
public Task<T> ReaderRead<T>(IDataReader reader, Func<T> fn, CancellationToken token = new CancellationToken())
{
throw new NotImplementedException(OrmLiteUtils.AsyncRequiresNet45Error);
}
public Task<long> InsertAndGetLastInsertIdAsync<T>(IDbCommand dbCmd, CancellationToken token)
{
throw new NotImplementedException(OrmLiteUtils.AsyncRequiresNet45Error);
}
#endif
}
}
| |
//
// Button.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Xwt.Drawing;
using System.ComponentModel;
namespace Xwt
{
[BackendType (typeof(IButtonBackend))]
public class Button: Widget
{
EventHandler clicked;
ButtonStyle style = ButtonStyle.Normal;
ButtonType type = ButtonType.Normal;
Image image;
string label;
bool useMnemonic = true;
ContentPosition imagePosition = ContentPosition.Left;
protected new class WidgetBackendHost: Widget.WidgetBackendHost, IButtonEventSink
{
protected override void OnBackendCreated ()
{
base.OnBackendCreated ();
((IButtonBackend)Backend).SetButtonStyle (((Button)Parent).style);
}
public void OnClicked ()
{
((Button)Parent).OnClicked (EventArgs.Empty);
}
}
static Button ()
{
MapEvent (ButtonEvent.Clicked, typeof(Button), "OnClicked");
}
public Button ()
{
}
public Button (string label)
{
VerifyConstructorCall (this);
Label = label;
}
public Button (Image img, string label)
{
VerifyConstructorCall (this);
Label = label;
Image = img;
}
public Button (Image img)
{
VerifyConstructorCall (this);
Image = img;
}
protected override BackendHost CreateBackendHost ()
{
return new WidgetBackendHost ();
}
IButtonBackend Backend {
get { return (IButtonBackend) BackendHost.Backend; }
}
[DefaultValue ("")]
public string Label {
get { return label ?? ""; }
set {
label = value ?? string.Empty;
Backend.SetContent (value, UseMnemonic, image != null ? image.GetImageDescription (BackendHost.ToolkitEngine) : ImageDescription.Null, imagePosition);
OnPreferredSizeChanged ();
}
}
string markup;
/// <summary>
/// Gets or sets the text with markup to display.
/// </summary>
/// <remarks>
/// <see cref="Xwt.FormattedText"/> for supported formatting options.</remarks>
[DefaultValue("")]
public string Markup {
get { return markup; }
set {
markup = value;
var t = FormattedText.FromMarkup (markup);
Backend.SetFormattedText (t);
OnPreferredSizeChanged ();
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Xwt.Button"/> uses a mnemonic.
/// </summary>
/// <value><c>true</c> if it uses a mnemonic; otherwise, <c>false</c>.</value>
/// <remarks>
/// When set to true, the character after the first underscore character in the Label property value is
/// interpreted as the mnemonic for that Label.
/// </remarks>
[DefaultValue(true)]
public bool UseMnemonic {
get { return useMnemonic; }
set
{
if (useMnemonic == value)
return;
Backend.SetContent (label, value, image != null ? image.GetImageDescription (BackendHost.ToolkitEngine) : ImageDescription.Null, imagePosition);
useMnemonic = value;
}
}
[DefaultValue (null)]
public Image Image {
get { return image; }
set {
image = value;
Backend.SetContent (label, UseMnemonic, image != null ? image.GetImageDescription (BackendHost.ToolkitEngine) : ImageDescription.Null, imagePosition);
OnPreferredSizeChanged ();
}
}
[DefaultValue (ContentPosition.Left)]
public ContentPosition ImagePosition {
get { return imagePosition; }
set {
imagePosition = value;
Backend.SetContent (label, UseMnemonic, image != null ? image.GetImageDescription (BackendHost.ToolkitEngine) : ImageDescription.Null, imagePosition);
OnPreferredSizeChanged ();
}
}
[DefaultValue (ButtonStyle.Normal)]
public ButtonStyle Style {
get { return style; }
set {
style = value;
Backend.SetButtonStyle (style);
OnPreferredSizeChanged ();
}
}
[DefaultValue (ButtonType.Normal)]
public ButtonType Type {
get { return type; }
set {
type = value;
Backend.SetButtonType (type);
OnPreferredSizeChanged ();
}
}
public Color LabelColor {
get { return Backend.LabelColor; }
set { Backend.LabelColor = value; }
}
public bool IsDefault {
get { return Backend.IsDefault; }
set { Backend.IsDefault = value; }
}
protected virtual void OnClicked (EventArgs e)
{
if (clicked != null)
clicked (this, e);
}
public event EventHandler Clicked {
add {
BackendHost.OnBeforeEventAdd (ButtonEvent.Clicked, clicked);
clicked += value;
}
remove {
clicked -= value;
BackendHost.OnAfterEventRemove (ButtonEvent.Clicked, clicked);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
{
// This abstract class represents a calendar. A calendar reckons time in
// divisions such as weeks, months and years. The number, length and start of
// the divisions vary in each calendar.
//
// Any instant in time can be represented as an n-tuple of numeric values using
// a particular calendar. For example, the next vernal equinox occurs at (0.0, 0
// , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of
// Calendar can map any DateTime value to such an n-tuple and vice versa. The
// DateTimeFormat class can map between such n-tuples and a textual
// representation such as "8:46 AM March 20th 1999 AD".
//
// Most calendars identify a year which begins the current era. There may be any
// number of previous eras. The Calendar class identifies the eras as enumerated
// integers where the current era (CurrentEra) has the value zero.
//
// For consistency, the first unit in each interval, e.g. the first month, is
// assigned the value one.
// The calculation of hour/minute/second is moved to Calendar from GregorianCalendar,
// since most of the calendars (or all?) have the same way of calcuating hour/minute/second.
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract partial class Calendar : ICloneable
{
// Number of 100ns (10E-7 second) ticks per time unit
internal const long TicksPerMillisecond = 10000;
internal const long TicksPerSecond = TicksPerMillisecond * 1000;
internal const long TicksPerMinute = TicksPerSecond * 60;
internal const long TicksPerHour = TicksPerMinute * 60;
internal const long TicksPerDay = TicksPerHour * 24;
// Number of milliseconds per time unit
internal const int MillisPerSecond = 1000;
internal const int MillisPerMinute = MillisPerSecond * 60;
internal const int MillisPerHour = MillisPerMinute * 60;
internal const int MillisPerDay = MillisPerHour * 24;
// Number of days in a non-leap year
internal const int DaysPerYear = 365;
// Number of days in 4 years
internal const int DaysPer4Years = DaysPerYear * 4 + 1;
// Number of days in 100 years
internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
// Number of days in 400 years
internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
// Number of days from 1/1/0001 to 1/1/10000
internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
private int _currentEraValue = -1;
[OptionalField(VersionAdded = 2)]
private bool _isReadOnly = false;
#if INSIDE_CLR
internal const CalendarId CAL_HEBREW = CalendarId.HEBREW;
internal const CalendarId CAL_HIJRI = CalendarId.HIJRI;
internal const CalendarId CAL_JAPAN = CalendarId.JAPAN;
internal const CalendarId CAL_JULIAN = CalendarId.JULIAN;
internal const CalendarId CAL_TAIWAN = CalendarId.TAIWAN;
internal const CalendarId CAL_UMALQURA = CalendarId.UMALQURA;
internal const CalendarId CAL_PERSIAN = CalendarId.PERSIAN;
#endif
// The minimum supported DateTime range for the calendar.
[System.Runtime.InteropServices.ComVisible(false)]
public virtual DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
// The maximum supported DateTime range for the calendar.
[System.Runtime.InteropServices.ComVisible(false)]
public virtual DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public virtual CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.Unknown;
}
}
protected Calendar()
{
//Do-nothing constructor.
}
///
// This can not be abstract, otherwise no one can create a subclass of Calendar.
//
internal virtual CalendarId ID
{
get
{
return CalendarId.UNINITIALIZED_VALUE;
}
}
///
// Return the Base calendar ID for calendars that didn't have defined data in calendarData
//
internal virtual CalendarId BaseCalendarID
{
get { return ID; }
}
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
//
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public bool IsReadOnly
{
get { return (_isReadOnly); }
}
////////////////////////////////////////////////////////////////////////
//
// Clone
//
// Is the implementation of ICloneable.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public virtual object Clone()
{
object o = MemberwiseClone();
((Calendar)o).SetReadOnlyState(false);
return (o);
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public static Calendar ReadOnly(Calendar calendar)
{
if (calendar == null) { throw new ArgumentNullException("calendar"); }
Contract.EndContractBlock();
if (calendar.IsReadOnly) { return (calendar); }
Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone());
clonedCalendar.SetReadOnlyState(true);
return (clonedCalendar);
}
internal void VerifyWritable()
{
if (_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
internal void SetReadOnlyState(bool readOnly)
{
_isReadOnly = readOnly;
}
/*=================================CurrentEraValue==========================
**Action: This is used to convert CurretEra(0) to an appropriate era value.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** The value is from calendar.nlp.
============================================================================*/
internal virtual int CurrentEraValue
{
get
{
// The following code assumes that the current era value can not be -1.
if (_currentEraValue == -1)
{
Contract.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
return (_currentEraValue);
}
}
// The current era for a calendar.
public const int CurrentEra = 0;
internal int twoDigitYearMax = -1;
internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue)
{
if (ticks < minValue.Ticks || ticks > maxValue.Ticks)
{
throw new ArgumentException(
String.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange,
minValue, maxValue)));
}
Contract.EndContractBlock();
}
internal DateTime Add(DateTime time, double value, int scale)
{
// From ECMA CLI spec, Partition III, section 3.27:
//
// If overflow occurs converting a floating-point type to an integer, or if the floating-point value
// being converted to an integer is a NaN, the value returned is unspecified.
//
// Based upon this, this method should be performing the comparison against the double
// before attempting a cast. Otherwise, the result is undefined.
double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5));
if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis)))
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_AddValue);
}
long millis = (long)tempMillis;
long ticks = time.Ticks + millis * TicksPerMillisecond;
CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// milliseconds to the specified DateTime. The result is computed by rounding
// the number of milliseconds given by value to the nearest integer,
// and adding that interval to the specified DateTime. The value
// argument is permitted to be negative.
//
public virtual DateTime AddMilliseconds(DateTime time, double milliseconds)
{
return (Add(time, milliseconds, 1));
}
// Returns the DateTime resulting from adding a fractional number of
// days to the specified DateTime. The result is computed by rounding the
// fractional number of days given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddDays(DateTime time, int days)
{
return (Add(time, days, MillisPerDay));
}
// Returns the DateTime resulting from adding a fractional number of
// hours to the specified DateTime. The result is computed by rounding the
// fractional number of hours given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddHours(DateTime time, int hours)
{
return (Add(time, hours, MillisPerHour));
}
// Returns the DateTime resulting from adding a fractional number of
// minutes to the specified DateTime. The result is computed by rounding the
// fractional number of minutes given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddMinutes(DateTime time, int minutes)
{
return (Add(time, minutes, MillisPerMinute));
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public abstract DateTime AddMonths(DateTime time, int months);
// Returns the DateTime resulting from adding a number of
// seconds to the specified DateTime. The result is computed by rounding the
// fractional number of seconds given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddSeconds(DateTime time, int seconds)
{
return Add(time, seconds, MillisPerSecond);
}
// Returns the DateTime resulting from adding a number of
// weeks to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddWeeks(DateTime time, int weeks)
{
return (AddDays(time, weeks * 7));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public abstract DateTime AddYears(DateTime time, int years);
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public abstract int GetDayOfMonth(DateTime time);
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public abstract DayOfWeek GetDayOfWeek(DateTime time);
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public abstract int GetDayOfYear(DateTime time);
// Returns the number of days in the month given by the year and
// month arguments.
//
public virtual int GetDaysInMonth(int year, int month)
{
return (GetDaysInMonth(year, month, CurrentEra));
}
// Returns the number of days in the month given by the year and
// month arguments for the specified era.
//
public abstract int GetDaysInMonth(int year, int month, int era);
// Returns the number of days in the year given by the year argument for the current era.
//
public virtual int GetDaysInYear(int year)
{
return (GetDaysInYear(year, CurrentEra));
}
// Returns the number of days in the year given by the year argument for the current era.
//
public abstract int GetDaysInYear(int year, int era);
// Returns the era for the specified DateTime value.
public abstract int GetEra(DateTime time);
/*=================================Eras==========================
**Action: Get the list of era values.
**Returns: The int array of the era names supported in this calendar.
** null if era is not used.
**Arguments: None.
**Exceptions: None.
============================================================================*/
public abstract int[] Eras
{
get;
}
// Returns the hour part of the specified DateTime. The returned value is an
// integer between 0 and 23.
//
public virtual int GetHour(DateTime time)
{
return ((int)((time.Ticks / TicksPerHour) % 24));
}
// Returns the millisecond part of the specified DateTime. The returned value
// is an integer between 0 and 999.
//
public virtual double GetMilliseconds(DateTime time)
{
return (double)((time.Ticks / TicksPerMillisecond) % 1000);
}
// Returns the minute part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetMinute(DateTime time)
{
return ((int)((time.Ticks / TicksPerMinute) % 60));
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public abstract int GetMonth(DateTime time);
// Returns the number of months in the specified year in the current era.
public virtual int GetMonthsInYear(int year)
{
return (GetMonthsInYear(year, CurrentEra));
}
// Returns the number of months in the specified year and era.
public abstract int GetMonthsInYear(int year, int era);
// Returns the second part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetSecond(DateTime time)
{
return ((int)((time.Ticks / TicksPerSecond) % 60));
}
/*=================================GetFirstDayWeekOfYear==========================
**Action: Get the week of year using the FirstDay rule.
**Returns: the week of year.
**Arguments:
** time
** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday)
**Notes:
** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year.
** Assume f is the specifed firstDayOfWeek,
** and n is the day of week for January 1 of the specified year.
** Assign offset = n - f;
** Case 1: offset = 0
** E.g.
** f=1
** weekday 0 1 2 3 4 5 6 0 1
** date 1/1
** week# 1 2
** then week of year = (GetDayOfYear(time) - 1) / 7 + 1
**
** Case 2: offset < 0
** e.g.
** n=1 f=3
** weekday 0 1 2 3 4 5 6 0
** date 1/1
** week# 1 2
** This means that the first week actually starts 5 days before 1/1.
** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1
** Case 3: offset > 0
** e.g.
** f=0 n=2
** weekday 0 1 2 3 4 5 6 0 1 2
** date 1/1
** week# 1 2
** This means that the first week actually starts 2 days before 1/1.
** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1
============================================================================*/
internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek)
{
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
// Calculate the day of week for the first day of the year.
// dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that
// this value can be less than 0. It's fine since we are making it positive again in calculating offset.
int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
return ((dayOfYear + offset) / 7 + 1);
}
private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays)
{
int dayForJan1;
int offset;
int day;
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
//
// Calculate the number of days between the first day of year (1/1) and the first day of the week.
// This value will be a positive value from 0 ~ 6. We call this value as "offset".
//
// If offset is 0, it means that the 1/1 is the start of the first week.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 12/31 1/1 1/2 1/3 1/4 1/5 1/6
// +--> First week starts here.
//
// If offset is 1, it means that the first day of the week is 1 day ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7
// +--> First week starts here.
//
// If offset is 2, it means that the first day of the week is 2 days ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sat Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8
// +--> First week starts here.
// Day of week is 0-based.
// Get the day of week for 1/1. This can be derived from the day of week of the target day.
// Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset.
dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
// Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value.
offset = (firstDayOfWeek - dayForJan1 + 14) % 7;
if (offset != 0 && offset >= fullDays)
{
//
// If the offset is greater than the value of fullDays, it means that
// the first week of the year starts on the week where Jan/1 falls on.
//
offset -= 7;
}
//
// Calculate the day of year for specified time by taking offset into account.
//
day = dayOfYear - offset;
if (day >= 0)
{
//
// If the day of year value is greater than zero, get the week of year.
//
return (day / 7 + 1);
}
//
// Otherwise, the specified time falls on the week of previous year.
// Call this method again by passing the last day of previous year.
//
// the last day of the previous year may "underflow" to no longer be a valid date time for
// this calendar if we just subtract so we need the subclass to provide us with
// that information
if (time <= MinSupportedDateTime.AddDays(dayOfYear))
{
return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays);
}
return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays));
}
private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek)
{
int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7;
// Calculate the offset (how many days from the start of the year to the start of the week)
int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7;
if (offset == 0 || offset >= minimumDaysInFirstWeek)
{
// First of year falls in the first week of the year
return 1;
}
int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7);
// starting from first day of the year, how many days do you have to go forward
// before getting to the first day of the week?
int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7;
int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek;
if (daysInInitialPartialWeek >= minimumDaysInFirstWeek)
{
// If the offset is greater than the minimum Days in the first week, it means that
// First of year is part of the first week of the year even though it is only a partial week
// add another week
day += 7;
}
return (day / 7 + 1);
}
// it would be nice to make this abstract but we can't since that would break previous implementations
protected virtual int DaysInYearBeforeMinSupportedYear
{
get
{
return 365;
}
}
// Returns the week of year for the specified DateTime. The returned value is an
// integer between 1 and 53.
//
public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6)
{
throw new ArgumentOutOfRangeException(
"firstDayOfWeek", SR.Format(SR.ArgumentOutOfRange_Range,
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
Contract.EndContractBlock();
switch (rule)
{
case CalendarWeekRule.FirstDay:
return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek));
case CalendarWeekRule.FirstFullWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7));
case CalendarWeekRule.FirstFourDayWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4));
}
throw new ArgumentOutOfRangeException(
"rule", SR.Format(SR.ArgumentOutOfRange_Range,
CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public abstract int GetYear(DateTime time);
// Checks whether a given day in the current era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public virtual bool IsLeapDay(int year, int month, int day)
{
return (IsLeapDay(year, month, day, CurrentEra));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public abstract bool IsLeapDay(int year, int month, int day, int era);
// Checks whether a given month in the current era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public virtual bool IsLeapMonth(int year, int month)
{
return (IsLeapMonth(year, month, CurrentEra));
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public abstract bool IsLeapMonth(int year, int month, int era);
// Returns the leap month in a calendar year of the current era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetLeapMonth(int year)
{
return (GetLeapMonth(year, CurrentEra));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetLeapMonth(int year, int era)
{
if (!IsLeapYear(year, era))
return 0;
int monthsCount = GetMonthsInYear(year, era);
for (int month = 1; month <= monthsCount; month++)
{
if (IsLeapMonth(year, month, era))
return month;
}
return 0;
}
// Checks whether a given year in the current era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public virtual bool IsLeapYear(int year)
{
return (IsLeapYear(year, CurrentEra));
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public abstract bool IsLeapYear(int year, int era);
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era);
internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result)
{
result = DateTime.MinValue;
try
{
result = ToDateTime(year, month, day, hour, minute, second, millisecond, era);
return true;
}
catch (ArgumentException)
{
return false;
}
}
internal virtual bool IsValidYear(int year, int era)
{
return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime));
}
internal virtual bool IsValidMonth(int year, int month, int era)
{
return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era));
}
internal virtual bool IsValidDay(int year, int month, int day, int era)
{
return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era));
}
// Returns and assigns the maximum value to represent a two digit year. This
// value is the upper boundary of a 100 year range that allows a two digit year
// to be properly translated to a four digit year. For example, if 2029 is the
// upper boundary, then a two digit value of 30 should be interpreted as 1930
// while a two digit value of 29 should be interpreted as 2029. In this example
// , the 100 year range would be from 1930-2029. See ToFourDigitYear().
public virtual int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
twoDigitYearMax = value;
}
}
// Converts the year value to the appropriate century by using the
// TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029,
// then a two digit value of 30 will get converted to 1930 while a two digit
// value of 29 will get converted to 2029.
public virtual int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException("year",
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year < 100)
{
return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year);
}
// If the year value is above 100, just return the year value. Don't have to do
// the TwoDigitYearMax comparison.
return (year);
}
// Return the tick count corresponding to the given hour, minute, second.
// Will check the if the parameters are valid.
internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
{
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
"millisecond",
String.Format(
CultureInfo.InvariantCulture,
SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)));
}
return InternalGloablizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond;
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
internal static int GetSystemTwoDigitYearSetting(CalendarId CalID, int defaultYearValue)
{
// Call nativeGetTwoDigitYearMax
int twoDigitYearMax = CalendarData.GetTwoDigitYearMax(CalID);
if (twoDigitYearMax < 0)
{
twoDigitYearMax = defaultYearValue;
}
return (twoDigitYearMax);
}
}
}
| |
/*
* Copyright (c) 2006-2014, openmetaverse.org
* 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.
* - Neither the name of the openmetaverse.org 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;
namespace OpenMetaverse
{
/// <summary>
/// Wrapper around a byte array that allows bit to be packed and unpacked
/// one at a time or by a variable amount. Useful for very tightly packed
/// data like LayerData packets
/// </summary>
public class BitPack
{
/// <summary></summary>
public byte[] Data;
/// <summary></summary>
public int BytePos
{
get
{
if (bytePos != 0 && bitPos == 0)
return bytePos - 1;
else
return bytePos;
}
}
/// <summary></summary>
public int BitPos { get { return bitPos; } }
private const int MAX_BITS = 8;
private static readonly byte[] ON = new byte[] { 1 };
private static readonly byte[] OFF = new byte[] { 0 };
private int bytePos;
private int bitPos;
private bool weAreBigEndian = !BitConverter.IsLittleEndian;
/// <summary>
/// Default constructor, initialize the bit packer / bit unpacker
/// with a byte array and starting position
/// </summary>
/// <param name="data">Byte array to pack bits in to or unpack from</param>
/// <param name="pos">Starting position in the byte array</param>
public BitPack(byte[] data, int pos)
{
Data = data;
bytePos = pos;
}
/// <summary>
/// Pack a floating point value in to the data
/// </summary>
/// <param name="data">Floating point value to pack</param>
public void PackFloat(float data)
{
byte[] input = BitConverter.GetBytes(data);
if (weAreBigEndian) Array.Reverse(input);
PackBitArray(input, 32);
}
/// <summary>
/// Pack part or all of an integer in to the data
/// </summary>
/// <param name="data">Integer containing the data to pack</param>
/// <param name="totalCount">Number of bits of the integer to pack</param>
public void PackBits(int data, int totalCount)
{
byte[] input = BitConverter.GetBytes(data);
if (weAreBigEndian) Array.Reverse(input);
PackBitArray(input, totalCount);
}
/// <summary>
/// Pack part or all of an unsigned integer in to the data
/// </summary>
/// <param name="data">Unsigned integer containing the data to pack</param>
/// <param name="totalCount">Number of bits of the integer to pack</param>
public void PackBits(uint data, int totalCount)
{
byte[] input = BitConverter.GetBytes(data);
if (weAreBigEndian) Array.Reverse(input);
PackBitArray(input, totalCount);
}
/// <summary>
/// Pack a single bit in to the data
/// </summary>
/// <param name="bit">Bit to pack</param>
public void PackBit(bool bit)
{
if (bit)
PackBitArray(ON, 1);
else
PackBitArray(OFF, 1);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="isSigned"></param>
/// <param name="intBits"></param>
/// <param name="fracBits"></param>
public void PackFixed(float data, bool isSigned, int intBits, int fracBits)
{
int unsignedBits = intBits + fracBits;
int totalBits = unsignedBits;
int min, max;
if (isSigned)
{
totalBits++;
min = 1 << intBits;
min *= -1;
}
else
{
min = 0;
}
max = 1 << intBits;
float fixedVal = Utils.Clamp(data, (float)min, (float)max);
if (isSigned) fixedVal += max;
fixedVal *= 1 << fracBits;
if (totalBits <= 8)
PackBits((uint)fixedVal, 8);
else if (totalBits <= 16)
PackBits((uint)fixedVal, 16);
else if (totalBits <= 31)
PackBits((uint)fixedVal, 32);
else
throw new Exception("Can't use fixed point packing for " + totalBits);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
public void PackUUID(UUID data)
{
byte[] bytes = data.GetBytes();
// Not sure if our PackBitArray function can handle 128-bit byte
//arrays, so using this for now
for (int i = 0; i < 16; i++)
PackBits(bytes[i], 8);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
public void PackColor(Color4 data)
{
byte[] bytes = data.GetBytes();
PackBitArray(bytes, 32);
}
/// <summary>
/// Unpacking a floating point value from the data
/// </summary>
/// <returns>Unpacked floating point value</returns>
public float UnpackFloat()
{
byte[] output = UnpackBitsArray(32);
if (weAreBigEndian) Array.Reverse(output);
return BitConverter.ToSingle(output, 0);
}
/// <summary>
/// Unpack a variable number of bits from the data in to integer format
/// </summary>
/// <param name="totalCount">Number of bits to unpack</param>
/// <returns>An integer containing the unpacked bits</returns>
/// <remarks>This function is only useful up to 32 bits</remarks>
public int UnpackBits(int totalCount)
{
byte[] output = UnpackBitsArray(totalCount);
if (weAreBigEndian) Array.Reverse(output);
return BitConverter.ToInt32(output, 0);
}
/// <summary>
/// Unpack a variable number of bits from the data in to unsigned
/// integer format
/// </summary>
/// <param name="totalCount">Number of bits to unpack</param>
/// <returns>An unsigned integer containing the unpacked bits</returns>
/// <remarks>This function is only useful up to 32 bits</remarks>
public uint UnpackUBits(int totalCount)
{
byte[] output = UnpackBitsArray(totalCount);
if (weAreBigEndian) Array.Reverse(output);
return BitConverter.ToUInt32(output, 0);
}
/// <summary>
/// Unpack a 16-bit signed integer
/// </summary>
/// <returns>16-bit signed integer</returns>
public short UnpackShort()
{
return (short)UnpackBits(16);
}
/// <summary>
/// Unpack a 16-bit unsigned integer
/// </summary>
/// <returns>16-bit unsigned integer</returns>
public ushort UnpackUShort()
{
return (ushort)UnpackUBits(16);
}
/// <summary>
/// Unpack a 32-bit signed integer
/// </summary>
/// <returns>32-bit signed integer</returns>
public int UnpackInt()
{
return UnpackBits(32);
}
/// <summary>
/// Unpack a 32-bit unsigned integer
/// </summary>
/// <returns>32-bit unsigned integer</returns>
public uint UnpackUInt()
{
return UnpackUBits(32);
}
public byte UnpackByte()
{
byte[] output = UnpackBitsArray(8);
return output[0];
}
public float UnpackFixed(bool signed, int intBits, int fracBits)
{
int minVal;
int maxVal;
int unsignedBits = intBits + fracBits;
int totalBits = unsignedBits;
float fixedVal;
if (signed)
{
totalBits++;
minVal = 1 << intBits;
minVal *= -1;
}
maxVal = 1 << intBits;
if (totalBits <= 8)
fixedVal = (float)UnpackByte();
else if (totalBits <= 16)
fixedVal = (float)UnpackUBits(16);
else if (totalBits <= 31)
fixedVal = (float)UnpackUBits(32);
else
return 0.0f;
fixedVal /= (float)(1 << fracBits);
if (signed) fixedVal -= (float)maxVal;
return fixedVal;
}
public string UnpackString(int size)
{
if (bitPos != 0 || bytePos + size > Data.Length) throw new IndexOutOfRangeException();
string str = System.Text.UTF8Encoding.UTF8.GetString(Data, bytePos, size);
bytePos += size;
return str;
}
public UUID UnpackUUID()
{
if (bitPos != 0) throw new IndexOutOfRangeException();
UUID val = new UUID(Data, bytePos);
bytePos += 16;
return val;
}
private void PackBitArray(byte[] data, int totalCount)
{
int count = 0;
int curBytePos = 0;
int curBitPos = 0;
while (totalCount > 0)
{
if (totalCount > MAX_BITS)
{
count = MAX_BITS;
totalCount -= MAX_BITS;
}
else
{
count = totalCount;
totalCount = 0;
}
while (count > 0)
{
byte curBit = (byte)(0x80 >> bitPos);
if ((data[curBytePos] & (0x01 << (count - 1))) != 0)
Data[bytePos] |= curBit;
else
Data[bytePos] &= (byte)~curBit;
--count;
++bitPos;
++curBitPos;
if (bitPos >= MAX_BITS)
{
bitPos = 0;
++bytePos;
}
if (curBitPos >= MAX_BITS)
{
curBitPos = 0;
++curBytePos;
}
}
}
}
private byte[] UnpackBitsArray(int totalCount)
{
int count = 0;
byte[] output = new byte[4];
int curBytePos = 0;
int curBitPos = 0;
while (totalCount > 0)
{
if (totalCount > MAX_BITS)
{
count = MAX_BITS;
totalCount -= MAX_BITS;
}
else
{
count = totalCount;
totalCount = 0;
}
while (count > 0)
{
// Shift the previous bits
output[curBytePos] <<= 1;
// Grab one bit
if ((Data[bytePos] & (0x80 >> bitPos++)) != 0)
++output[curBytePos];
--count;
++curBitPos;
if (bitPos >= MAX_BITS)
{
bitPos = 0;
++bytePos;
}
if (curBitPos >= MAX_BITS)
{
curBitPos = 0;
++curBytePos;
}
}
}
return output;
}
}
}
| |
namespace ChooseAndCopy
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage_BOP = new System.Windows.Forms.TabPage();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.checkBox2 = new System.Windows.Forms.CheckBox();
this.comboBox2 = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.open_bop_config_folder_cbx = new System.Windows.Forms.CheckBox();
this.copy_bop_config_btn = new System.Windows.Forms.Button();
this.includesAll_btn = new System.Windows.Forms.RadioButton();
this.deselectBtn = new System.Windows.Forms.Button();
this.lb1 = new System.Windows.Forms.ListBox();
this.label5 = new System.Windows.Forms.Label();
this.onlySelected_btn = new System.Windows.Forms.RadioButton();
this.TargetFolder_Bin_btn = new System.Windows.Forms.Button();
this.excludeSelected_btn = new System.Windows.Forms.RadioButton();
this.selectBtn = new System.Windows.Forms.Button();
this.bop_config_target_folder_label = new System.Windows.Forms.Label();
this.SourceFolder_Bin_btn = new System.Windows.Forms.Button();
this.sourceBinFolder_lable = new System.Windows.Forms.Label();
this.lb2 = new System.Windows.Forms.ListBox();
this.tabPage_etc = new System.Windows.Forms.TabPage();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.checkBox3 = new System.Windows.Forms.CheckBox();
this.comboBox3 = new System.Windows.Forms.ComboBox();
this.label6 = new System.Windows.Forms.Label();
this.filter_out_sys_altsys_files_ckb = new System.Windows.Forms.CheckBox();
this.open_etc_folder_cbx = new System.Windows.Forms.CheckBox();
this.copy_etc_btn = new System.Windows.Forms.Button();
this.includesAll_btn_b = new System.Windows.Forms.RadioButton();
this.deselectBtn_b = new System.Windows.Forms.Button();
this.lb3 = new System.Windows.Forms.ListBox();
this.label1 = new System.Windows.Forms.Label();
this.onlySelected_btn_b = new System.Windows.Forms.RadioButton();
this.TargetFolder_etc_btn = new System.Windows.Forms.Button();
this.excludeSelected_btn_b = new System.Windows.Forms.RadioButton();
this.selectBtn_b = new System.Windows.Forms.Button();
this.etc_target_folder_label = new System.Windows.Forms.Label();
this.SourceFolder_etc_btn = new System.Windows.Forms.Button();
this.sourceEtcFolder_lable = new System.Windows.Forms.Label();
this.lb4 = new System.Windows.Forms.ListBox();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.linkLabel2 = new System.Windows.Forms.LinkLabel();
this.label8 = new System.Windows.Forms.Label();
this.linkLabel1 = new System.Windows.Forms.LinkLabel();
this.label7 = new System.Windows.Forms.Label();
this.sysinitFileFath = new System.Windows.Forms.Label();
this.altsysinitFilePath = new System.Windows.Forms.Label();
this.sysinitFilePath_TZ_btn = new System.Windows.Forms.Button();
this.altsysinitFilePath_TZ_btn = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.BOP_sysinitFileName = new System.Windows.Forms.Label();
this.TargetFileBtn = new System.Windows.Forms.Button();
this.SourceFileBtn = new System.Windows.Forms.Button();
this.ReplaceInfoBtn = new System.Windows.Forms.Button();
this.SourceFileName = new System.Windows.Forms.Label();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.openFilesCHKBOX = new System.Windows.Forms.CheckBox();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.tabControl1.SuspendLayout();
this.tabPage_BOP.SuspendLayout();
this.groupBox1.SuspendLayout();
this.tabPage_etc.SuspendLayout();
this.groupBox2.SuspendLayout();
this.tabPage3.SuspendLayout();
this.groupBox5.SuspendLayout();
this.groupBox3.SuspendLayout();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage_BOP);
this.tabControl1.Controls.Add(this.tabPage_etc);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.tabControl1.Location = new System.Drawing.Point(3, 3);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(929, 421);
this.tabControl1.TabIndex = 0;
//
// tabPage_BOP
//
this.tabPage_BOP.Controls.Add(this.groupBox1);
this.tabPage_BOP.Location = new System.Drawing.Point(4, 22);
this.tabPage_BOP.Name = "tabPage_BOP";
this.tabPage_BOP.Padding = new System.Windows.Forms.Padding(3);
this.tabPage_BOP.Size = new System.Drawing.Size(921, 395);
this.tabPage_BOP.TabIndex = 0;
this.tabPage_BOP.Text = "Copy Folder /bop_config";
this.tabPage_BOP.UseVisualStyleBackColor = true;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.checkBox2);
this.groupBox1.Controls.Add(this.comboBox2);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.open_bop_config_folder_cbx);
this.groupBox1.Controls.Add(this.copy_bop_config_btn);
this.groupBox1.Controls.Add(this.includesAll_btn);
this.groupBox1.Controls.Add(this.deselectBtn);
this.groupBox1.Controls.Add(this.lb1);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.onlySelected_btn);
this.groupBox1.Controls.Add(this.TargetFolder_Bin_btn);
this.groupBox1.Controls.Add(this.excludeSelected_btn);
this.groupBox1.Controls.Add(this.selectBtn);
this.groupBox1.Controls.Add(this.bop_config_target_folder_label);
this.groupBox1.Controls.Add(this.SourceFolder_Bin_btn);
this.groupBox1.Controls.Add(this.sourceBinFolder_lable);
this.groupBox1.Controls.Add(this.lb2);
this.groupBox1.Location = new System.Drawing.Point(9, 9);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(908, 378);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Copy source files under /bin (or /bop_config) to target folder /bin/bop_config";
//
// checkBox2
//
this.checkBox2.AutoSize = true;
this.checkBox2.Location = new System.Drawing.Point(13, 291);
this.checkBox2.Name = "checkBox2";
this.checkBox2.Size = new System.Drawing.Size(220, 17);
this.checkBox2.TabIndex = 25;
this.checkBox2.Text = "Apply the same procedure to other nodes";
this.checkBox2.UseVisualStyleBackColor = true;
this.checkBox2.CheckedChanged += new System.EventHandler(this.checkBox_bop_CheckedChanged);
//
// comboBox2
//
this.comboBox2.Enabled = false;
this.comboBox2.FormattingEnabled = true;
this.comboBox2.Location = new System.Drawing.Point(158, 308);
this.comboBox2.Name = "comboBox2";
this.comboBox2.Size = new System.Drawing.Size(43, 21);
this.comboBox2.TabIndex = 26;
this.comboBox2.SelectedValueChanged += new System.EventHandler(this.comboBox_bop_SelectedValueChanged);
this.comboBox2.DropDown += new System.EventHandler(this.comboBox_bop_DropDown);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(29, 311);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(121, 13);
this.label4.TabIndex = 27;
this.label4.Text = "Amount of nodes in total";
//
// open_bop_config_folder_cbx
//
this.open_bop_config_folder_cbx.AutoSize = true;
this.open_bop_config_folder_cbx.Checked = true;
this.open_bop_config_folder_cbx.CheckState = System.Windows.Forms.CheckState.Checked;
this.open_bop_config_folder_cbx.Location = new System.Drawing.Point(438, 291);
this.open_bop_config_folder_cbx.Name = "open_bop_config_folder_cbx";
this.open_bop_config_folder_cbx.Size = new System.Drawing.Size(161, 17);
this.open_bop_config_folder_cbx.TabIndex = 20;
this.open_bop_config_folder_cbx.Text = "Open target folder after copy";
this.open_bop_config_folder_cbx.UseVisualStyleBackColor = true;
//
// copy_bop_config_btn
//
this.copy_bop_config_btn.Location = new System.Drawing.Point(12, 341);
this.copy_bop_config_btn.Name = "copy_bop_config_btn";
this.copy_bop_config_btn.Size = new System.Drawing.Size(58, 23);
this.copy_bop_config_btn.TabIndex = 19;
this.copy_bop_config_btn.Text = "Copy";
this.copy_bop_config_btn.UseVisualStyleBackColor = true;
this.copy_bop_config_btn.Click += new System.EventHandler(this.copy_bop_config_btn_Click);
//
// includesAll_btn
//
this.includesAll_btn.AutoSize = true;
this.includesAll_btn.Location = new System.Drawing.Point(12, 213);
this.includesAll_btn.Name = "includesAll_btn";
this.includesAll_btn.Size = new System.Drawing.Size(222, 17);
this.includesAll_btn.TabIndex = 18;
this.includesAll_btn.Text = "Include all subfolders/files in source folder";
this.includesAll_btn.UseVisualStyleBackColor = true;
this.includesAll_btn.CheckedChanged += new System.EventHandler(this.includesAll_btn_CheckedChanged);
//
// deselectBtn
//
this.deselectBtn.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("deselectBtn.BackgroundImage")));
this.deselectBtn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.deselectBtn.Location = new System.Drawing.Point(438, 154);
this.deselectBtn.Name = "deselectBtn";
this.deselectBtn.Size = new System.Drawing.Size(33, 33);
this.deselectBtn.TabIndex = 17;
this.deselectBtn.Text = ".";
this.deselectBtn.UseVisualStyleBackColor = true;
this.deselectBtn.Click += new System.EventHandler(this.deselectBtn_Click);
//
// lb1
//
this.lb1.FormattingEnabled = true;
this.lb1.Location = new System.Drawing.Point(13, 66);
this.lb1.Name = "lb1";
this.lb1.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.lb1.Size = new System.Drawing.Size(420, 147);
this.lb1.TabIndex = 5;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(474, 50);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(126, 13);
this.label5.TabIndex = 13;
this.label5.Text = "Selected subfolders/files:";
//
// onlySelected_btn
//
this.onlySelected_btn.AutoSize = true;
this.onlySelected_btn.Location = new System.Drawing.Point(477, 234);
this.onlySelected_btn.Name = "onlySelected_btn";
this.onlySelected_btn.Size = new System.Drawing.Size(305, 17);
this.onlySelected_btn.TabIndex = 10;
this.onlySelected_btn.Text = "Only include selected subfolders/files from the source folder";
this.onlySelected_btn.UseVisualStyleBackColor = true;
//
// TargetFolder_Bin_btn
//
this.TargetFolder_Bin_btn.Location = new System.Drawing.Point(12, 262);
this.TargetFolder_Bin_btn.Name = "TargetFolder_Bin_btn";
this.TargetFolder_Bin_btn.Size = new System.Drawing.Size(123, 23);
this.TargetFolder_Bin_btn.TabIndex = 2;
this.TargetFolder_Bin_btn.Text = "Choose target folder";
this.TargetFolder_Bin_btn.UseVisualStyleBackColor = true;
this.TargetFolder_Bin_btn.Click += new System.EventHandler(this.TargetFolder_Bin_btn_Click);
//
// excludeSelected_btn
//
this.excludeSelected_btn.AutoSize = true;
this.excludeSelected_btn.Checked = true;
this.excludeSelected_btn.Location = new System.Drawing.Point(477, 213);
this.excludeSelected_btn.Name = "excludeSelected_btn";
this.excludeSelected_btn.Size = new System.Drawing.Size(285, 17);
this.excludeSelected_btn.TabIndex = 9;
this.excludeSelected_btn.TabStop = true;
this.excludeSelected_btn.Text = "Exclude selected subfolders/files from the source folder";
this.excludeSelected_btn.UseVisualStyleBackColor = true;
//
// selectBtn
//
this.selectBtn.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("selectBtn.BackgroundImage")));
this.selectBtn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.selectBtn.Location = new System.Drawing.Point(438, 91);
this.selectBtn.Name = "selectBtn";
this.selectBtn.Size = new System.Drawing.Size(33, 33);
this.selectBtn.TabIndex = 16;
this.selectBtn.TabStop = false;
this.selectBtn.Text = ".";
this.selectBtn.UseVisualStyleBackColor = true;
this.selectBtn.Click += new System.EventHandler(this.selectBtn_Click);
//
// bop_config_target_folder_label
//
this.bop_config_target_folder_label.AutoSize = true;
this.bop_config_target_folder_label.Location = new System.Drawing.Point(135, 266);
this.bop_config_target_folder_label.Name = "bop_config_target_folder_label";
this.bop_config_target_folder_label.Size = new System.Drawing.Size(16, 13);
this.bop_config_target_folder_label.TabIndex = 14;
this.bop_config_target_folder_label.Text = "...";
//
// SourceFolder_Bin_btn
//
this.SourceFolder_Bin_btn.Location = new System.Drawing.Point(14, 25);
this.SourceFolder_Bin_btn.Name = "SourceFolder_Bin_btn";
this.SourceFolder_Bin_btn.Size = new System.Drawing.Size(123, 23);
this.SourceFolder_Bin_btn.TabIndex = 0;
this.SourceFolder_Bin_btn.Text = "Choose source folder";
this.SourceFolder_Bin_btn.UseVisualStyleBackColor = true;
this.SourceFolder_Bin_btn.Click += new System.EventHandler(this.SourceFolder_Bin_btn_Click);
//
// sourceBinFolder_lable
//
this.sourceBinFolder_lable.AutoSize = true;
this.sourceBinFolder_lable.Location = new System.Drawing.Point(135, 30);
this.sourceBinFolder_lable.Name = "sourceBinFolder_lable";
this.sourceBinFolder_lable.Size = new System.Drawing.Size(16, 13);
this.sourceBinFolder_lable.TabIndex = 12;
this.sourceBinFolder_lable.Text = "...";
//
// lb2
//
this.lb2.FormattingEnabled = true;
this.lb2.Location = new System.Drawing.Point(477, 66);
this.lb2.Name = "lb2";
this.lb2.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.lb2.Size = new System.Drawing.Size(420, 147);
this.lb2.TabIndex = 6;
//
// tabPage_etc
//
this.tabPage_etc.Controls.Add(this.groupBox2);
this.tabPage_etc.Location = new System.Drawing.Point(4, 22);
this.tabPage_etc.Name = "tabPage_etc";
this.tabPage_etc.Padding = new System.Windows.Forms.Padding(3);
this.tabPage_etc.Size = new System.Drawing.Size(921, 395);
this.tabPage_etc.TabIndex = 1;
this.tabPage_etc.Text = "Copy Folder /etc";
this.tabPage_etc.UseVisualStyleBackColor = true;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.checkBox3);
this.groupBox2.Controls.Add(this.comboBox3);
this.groupBox2.Controls.Add(this.label6);
this.groupBox2.Controls.Add(this.filter_out_sys_altsys_files_ckb);
this.groupBox2.Controls.Add(this.open_etc_folder_cbx);
this.groupBox2.Controls.Add(this.copy_etc_btn);
this.groupBox2.Controls.Add(this.includesAll_btn_b);
this.groupBox2.Controls.Add(this.deselectBtn_b);
this.groupBox2.Controls.Add(this.lb3);
this.groupBox2.Controls.Add(this.label1);
this.groupBox2.Controls.Add(this.onlySelected_btn_b);
this.groupBox2.Controls.Add(this.TargetFolder_etc_btn);
this.groupBox2.Controls.Add(this.excludeSelected_btn_b);
this.groupBox2.Controls.Add(this.selectBtn_b);
this.groupBox2.Controls.Add(this.etc_target_folder_label);
this.groupBox2.Controls.Add(this.SourceFolder_etc_btn);
this.groupBox2.Controls.Add(this.sourceEtcFolder_lable);
this.groupBox2.Controls.Add(this.lb4);
this.groupBox2.Location = new System.Drawing.Point(9, 9);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(908, 378);
this.groupBox2.TabIndex = 2;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Copy source files under /etc to target folder /etc";
//
// checkBox3
//
this.checkBox3.AutoSize = true;
this.checkBox3.Location = new System.Drawing.Point(13, 291);
this.checkBox3.Name = "checkBox3";
this.checkBox3.Size = new System.Drawing.Size(220, 17);
this.checkBox3.TabIndex = 28;
this.checkBox3.Text = "Apply the same procedure to other nodes";
this.checkBox3.UseVisualStyleBackColor = true;
this.checkBox3.CheckedChanged += new System.EventHandler(this.checkBox_etc_CheckedChanged);
//
// comboBox3
//
this.comboBox3.Enabled = false;
this.comboBox3.FormattingEnabled = true;
this.comboBox3.Location = new System.Drawing.Point(158, 308);
this.comboBox3.Name = "comboBox3";
this.comboBox3.Size = new System.Drawing.Size(43, 21);
this.comboBox3.TabIndex = 29;
this.comboBox3.SelectedIndexChanged += new System.EventHandler(this.comboBox_etc_SelectedValueChanged);
this.comboBox3.DropDown += new System.EventHandler(this.comboBox_etc_DropDown);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(29, 311);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(121, 13);
this.label6.TabIndex = 30;
this.label6.Text = "Amount of nodes in total";
//
// filter_out_sys_altsys_files_ckb
//
this.filter_out_sys_altsys_files_ckb.AutoSize = true;
this.filter_out_sys_altsys_files_ckb.Checked = true;
this.filter_out_sys_altsys_files_ckb.CheckState = System.Windows.Forms.CheckState.Checked;
this.filter_out_sys_altsys_files_ckb.Location = new System.Drawing.Point(438, 291);
this.filter_out_sys_altsys_files_ckb.Name = "filter_out_sys_altsys_files_ckb";
this.filter_out_sys_altsys_files_ckb.Size = new System.Drawing.Size(262, 17);
this.filter_out_sys_altsys_files_ckb.TabIndex = 21;
this.filter_out_sys_altsys_files_ckb.Text = "filter out files for file name starting with sys or altsys";
this.filter_out_sys_altsys_files_ckb.UseVisualStyleBackColor = true;
//
// open_etc_folder_cbx
//
this.open_etc_folder_cbx.AutoSize = true;
this.open_etc_folder_cbx.Checked = true;
this.open_etc_folder_cbx.CheckState = System.Windows.Forms.CheckState.Checked;
this.open_etc_folder_cbx.Location = new System.Drawing.Point(438, 312);
this.open_etc_folder_cbx.Name = "open_etc_folder_cbx";
this.open_etc_folder_cbx.Size = new System.Drawing.Size(161, 17);
this.open_etc_folder_cbx.TabIndex = 20;
this.open_etc_folder_cbx.Text = "Open target folder after copy";
this.open_etc_folder_cbx.UseVisualStyleBackColor = true;
//
// copy_etc_btn
//
this.copy_etc_btn.Location = new System.Drawing.Point(12, 341);
this.copy_etc_btn.Name = "copy_etc_btn";
this.copy_etc_btn.Size = new System.Drawing.Size(58, 23);
this.copy_etc_btn.TabIndex = 19;
this.copy_etc_btn.Text = "Copy";
this.copy_etc_btn.UseVisualStyleBackColor = true;
this.copy_etc_btn.Click += new System.EventHandler(this.copy_etc_btn_Click);
//
// includesAll_btn_b
//
this.includesAll_btn_b.AutoSize = true;
this.includesAll_btn_b.Location = new System.Drawing.Point(12, 213);
this.includesAll_btn_b.Name = "includesAll_btn_b";
this.includesAll_btn_b.Size = new System.Drawing.Size(222, 17);
this.includesAll_btn_b.TabIndex = 18;
this.includesAll_btn_b.Text = "Include all subfolders/files in source folder";
this.includesAll_btn_b.UseVisualStyleBackColor = true;
this.includesAll_btn_b.CheckedChanged += new System.EventHandler(this.includesAll_btn_CheckedChanged_b);
//
// deselectBtn_b
//
this.deselectBtn_b.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("deselectBtn_b.BackgroundImage")));
this.deselectBtn_b.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.deselectBtn_b.Location = new System.Drawing.Point(438, 154);
this.deselectBtn_b.Name = "deselectBtn_b";
this.deselectBtn_b.Size = new System.Drawing.Size(33, 33);
this.deselectBtn_b.TabIndex = 17;
this.deselectBtn_b.Text = ".";
this.deselectBtn_b.UseVisualStyleBackColor = true;
this.deselectBtn_b.Click += new System.EventHandler(this.deselectBtn_b_Click);
//
// lb3
//
this.lb3.FormattingEnabled = true;
this.lb3.Location = new System.Drawing.Point(13, 66);
this.lb3.Name = "lb3";
this.lb3.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.lb3.Size = new System.Drawing.Size(420, 147);
this.lb3.TabIndex = 5;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(474, 50);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(126, 13);
this.label1.TabIndex = 13;
this.label1.Text = "Selected subfolders/files:";
//
// onlySelected_btn_b
//
this.onlySelected_btn_b.AutoSize = true;
this.onlySelected_btn_b.Location = new System.Drawing.Point(477, 234);
this.onlySelected_btn_b.Name = "onlySelected_btn_b";
this.onlySelected_btn_b.Size = new System.Drawing.Size(305, 17);
this.onlySelected_btn_b.TabIndex = 10;
this.onlySelected_btn_b.Text = "Only include selected subfolders/files from the source folder";
this.onlySelected_btn_b.UseVisualStyleBackColor = true;
//
// TargetFolder_etc_btn
//
this.TargetFolder_etc_btn.Location = new System.Drawing.Point(12, 262);
this.TargetFolder_etc_btn.Name = "TargetFolder_etc_btn";
this.TargetFolder_etc_btn.Size = new System.Drawing.Size(123, 23);
this.TargetFolder_etc_btn.TabIndex = 2;
this.TargetFolder_etc_btn.Text = "Choose target folder";
this.TargetFolder_etc_btn.UseVisualStyleBackColor = true;
this.TargetFolder_etc_btn.Click += new System.EventHandler(this.TargetFolder_etc_btn_Click);
//
// excludeSelected_btn_b
//
this.excludeSelected_btn_b.AutoSize = true;
this.excludeSelected_btn_b.Checked = true;
this.excludeSelected_btn_b.Location = new System.Drawing.Point(477, 213);
this.excludeSelected_btn_b.Name = "excludeSelected_btn_b";
this.excludeSelected_btn_b.Size = new System.Drawing.Size(285, 17);
this.excludeSelected_btn_b.TabIndex = 9;
this.excludeSelected_btn_b.TabStop = true;
this.excludeSelected_btn_b.Text = "Exclude selected subfolders/files from the source folder";
this.excludeSelected_btn_b.UseVisualStyleBackColor = true;
//
// selectBtn_b
//
this.selectBtn_b.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("selectBtn_b.BackgroundImage")));
this.selectBtn_b.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.selectBtn_b.Location = new System.Drawing.Point(438, 91);
this.selectBtn_b.Name = "selectBtn_b";
this.selectBtn_b.Size = new System.Drawing.Size(33, 33);
this.selectBtn_b.TabIndex = 16;
this.selectBtn_b.TabStop = false;
this.selectBtn_b.Text = ".";
this.selectBtn_b.UseVisualStyleBackColor = true;
this.selectBtn_b.Click += new System.EventHandler(this.selectBtn_b_Click);
//
// etc_target_folder_label
//
this.etc_target_folder_label.AutoSize = true;
this.etc_target_folder_label.Location = new System.Drawing.Point(134, 266);
this.etc_target_folder_label.Name = "etc_target_folder_label";
this.etc_target_folder_label.Size = new System.Drawing.Size(16, 13);
this.etc_target_folder_label.TabIndex = 14;
this.etc_target_folder_label.Text = "...";
//
// SourceFolder_etc_btn
//
this.SourceFolder_etc_btn.Location = new System.Drawing.Point(14, 25);
this.SourceFolder_etc_btn.Name = "SourceFolder_etc_btn";
this.SourceFolder_etc_btn.Size = new System.Drawing.Size(123, 23);
this.SourceFolder_etc_btn.TabIndex = 0;
this.SourceFolder_etc_btn.Text = "Choose source folder";
this.SourceFolder_etc_btn.UseVisualStyleBackColor = true;
this.SourceFolder_etc_btn.Click += new System.EventHandler(this.SourceFolder_etc_btn_Click);
//
// sourceEtcFolder_lable
//
this.sourceEtcFolder_lable.AutoSize = true;
this.sourceEtcFolder_lable.Location = new System.Drawing.Point(135, 30);
this.sourceEtcFolder_lable.Name = "sourceEtcFolder_lable";
this.sourceEtcFolder_lable.Size = new System.Drawing.Size(16, 13);
this.sourceEtcFolder_lable.TabIndex = 12;
this.sourceEtcFolder_lable.Text = "...";
//
// lb4
//
this.lb4.FormattingEnabled = true;
this.lb4.Location = new System.Drawing.Point(477, 66);
this.lb4.Name = "lb4";
this.lb4.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.lb4.Size = new System.Drawing.Size(420, 147);
this.lb4.TabIndex = 6;
//
// tabPage3
//
this.tabPage3.Controls.Add(this.groupBox5);
this.tabPage3.Controls.Add(this.sysinitFileFath);
this.tabPage3.Controls.Add(this.altsysinitFilePath);
this.tabPage3.Controls.Add(this.sysinitFilePath_TZ_btn);
this.tabPage3.Controls.Add(this.altsysinitFilePath_TZ_btn);
this.tabPage3.Controls.Add(this.label2);
this.tabPage3.Controls.Add(this.BOP_sysinitFileName);
this.tabPage3.Controls.Add(this.TargetFileBtn);
this.tabPage3.Controls.Add(this.SourceFileBtn);
this.tabPage3.Controls.Add(this.ReplaceInfoBtn);
this.tabPage3.Controls.Add(this.SourceFileName);
this.tabPage3.Controls.Add(this.groupBox3);
this.tabPage3.Controls.Add(this.groupBox4);
this.tabPage3.Location = new System.Drawing.Point(4, 22);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Padding = new System.Windows.Forms.Padding(3);
this.tabPage3.Size = new System.Drawing.Size(921, 395);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "Replacement";
this.tabPage3.UseVisualStyleBackColor = true;
//
// groupBox5
//
this.groupBox5.Controls.Add(this.linkLabel2);
this.groupBox5.Controls.Add(this.label8);
this.groupBox5.Controls.Add(this.linkLabel1);
this.groupBox5.Controls.Add(this.label7);
this.groupBox5.Location = new System.Drawing.Point(667, 10);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(244, 319);
this.groupBox5.TabIndex = 33;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "USEFUL RESOURCES";
//
// linkLabel2
//
this.linkLabel2.AutoSize = true;
this.linkLabel2.Location = new System.Drawing.Point(105, 74);
this.linkLabel2.Name = "linkLabel2";
this.linkLabel2.Size = new System.Drawing.Size(131, 13);
this.linkLabel2.TabIndex = 4;
this.linkLabel2.TabStop = true;
this.linkLabel2.Text = "winmerge.org/downloads/";
this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked);
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(4, 48);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(232, 39);
this.label8.TabIndex = 3;
this.label8.Text = "If you would like to compare files and/or folders,\nWinMerge is strongly recommend" +
"ed, which can\nbe downloaded from";
//
// linkLabel1
//
this.linkLabel1.AutoSize = true;
this.linkLabel1.Location = new System.Drawing.Point(69, 19);
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.Size = new System.Drawing.Size(164, 13);
this.linkLabel1.TabIndex = 2;
this.linkLabel1.TabStop = true;
this.linkLabel1.Text = "notepad-plus-plus.org/download/";
this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(4, 20);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(69, 13);
this.label7.TabIndex = 1;
this.label7.Text = "Notepad++ : ";
//
// sysinitFileFath
//
this.sysinitFileFath.AutoSize = true;
this.sysinitFileFath.Location = new System.Drawing.Point(23, 211);
this.sysinitFileFath.Name = "sysinitFileFath";
this.sysinitFileFath.Size = new System.Drawing.Size(307, 13);
this.sysinitFileFath.TabIndex = 29;
this.sysinitFileFath.Text = "Press button below to choose sysinit file for updating Time Zone";
//
// altsysinitFilePath
//
this.altsysinitFilePath.AutoSize = true;
this.altsysinitFilePath.Location = new System.Drawing.Point(23, 161);
this.altsysinitFilePath.Name = "altsysinitFilePath";
this.altsysinitFilePath.Size = new System.Drawing.Size(318, 13);
this.altsysinitFilePath.TabIndex = 28;
this.altsysinitFilePath.Text = "Press button below to choose altsysinit file for updating Time Zone";
//
// sysinitFilePath_TZ_btn
//
this.sysinitFilePath_TZ_btn.Location = new System.Drawing.Point(23, 226);
this.sysinitFilePath_TZ_btn.Name = "sysinitFilePath_TZ_btn";
this.sysinitFilePath_TZ_btn.Size = new System.Drawing.Size(98, 23);
this.sysinitFilePath_TZ_btn.TabIndex = 27;
this.sysinitFilePath_TZ_btn.Text = "Choose sysinit";
this.sysinitFilePath_TZ_btn.UseVisualStyleBackColor = true;
this.sysinitFilePath_TZ_btn.Click += new System.EventHandler(this.sysinitFilePath_TZ_btn_Click);
//
// altsysinitFilePath_TZ_btn
//
this.altsysinitFilePath_TZ_btn.Location = new System.Drawing.Point(23, 175);
this.altsysinitFilePath_TZ_btn.Name = "altsysinitFilePath_TZ_btn";
this.altsysinitFilePath_TZ_btn.Size = new System.Drawing.Size(98, 23);
this.altsysinitFilePath_TZ_btn.TabIndex = 26;
this.altsysinitFilePath_TZ_btn.Text = "Choose altsysinit";
this.altsysinitFilePath_TZ_btn.UseVisualStyleBackColor = true;
this.altsysinitFilePath_TZ_btn.Click += new System.EventHandler(this.altsysinitFilePath_TZ_btn_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(23, 342);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(342, 13);
this.label2.TabIndex = 25;
this.label2.Text = "Press button below to replace fields of target file with ones in source file";
//
// BOP_sysinitFileName
//
this.BOP_sysinitFileName.AutoSize = true;
this.BOP_sysinitFileName.Location = new System.Drawing.Point(23, 113);
this.BOP_sysinitFileName.Name = "BOP_sysinitFileName";
this.BOP_sysinitFileName.Size = new System.Drawing.Size(284, 13);
this.BOP_sysinitFileName.TabIndex = 21;
this.BOP_sysinitFileName.Text = "Press button below to choose BOP_sysinit file in folder /bin";
//
// TargetFileBtn
//
this.TargetFileBtn.Location = new System.Drawing.Point(23, 127);
this.TargetFileBtn.Name = "TargetFileBtn";
this.TargetFileBtn.Size = new System.Drawing.Size(151, 23);
this.TargetFileBtn.TabIndex = 20;
this.TargetFileBtn.Text = "Choose Target BOP_sysinit";
this.TargetFileBtn.UseVisualStyleBackColor = true;
this.TargetFileBtn.Click += new System.EventHandler(this.TargetFileBtn_Click);
//
// SourceFileBtn
//
this.SourceFileBtn.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.SourceFileBtn.Location = new System.Drawing.Point(23, 44);
this.SourceFileBtn.Name = "SourceFileBtn";
this.SourceFileBtn.Size = new System.Drawing.Size(151, 23);
this.SourceFileBtn.TabIndex = 19;
this.SourceFileBtn.Text = "Choose Source Sysinit File";
this.SourceFileBtn.UseVisualStyleBackColor = true;
this.SourceFileBtn.Click += new System.EventHandler(this.SourceFileBtn_Click);
//
// ReplaceInfoBtn
//
this.ReplaceInfoBtn.Location = new System.Drawing.Point(23, 357);
this.ReplaceInfoBtn.Name = "ReplaceInfoBtn";
this.ReplaceInfoBtn.Size = new System.Drawing.Size(62, 23);
this.ReplaceInfoBtn.TabIndex = 18;
this.ReplaceInfoBtn.Text = "Replace";
this.ReplaceInfoBtn.UseVisualStyleBackColor = true;
this.ReplaceInfoBtn.Click += new System.EventHandler(this.ReplaceInfoBtn_Click);
//
// SourceFileName
//
this.SourceFileName.AutoSize = true;
this.SourceFileName.Location = new System.Drawing.Point(23, 29);
this.SourceFileName.Name = "SourceFileName";
this.SourceFileName.Size = new System.Drawing.Size(292, 13);
this.SourceFileName.TabIndex = 17;
this.SourceFileName.Text = "Press button below to choose source sysinit file in folder /etc";
//
// groupBox3
//
this.groupBox3.Controls.Add(this.openFilesCHKBOX);
this.groupBox3.Controls.Add(this.checkBox1);
this.groupBox3.Controls.Add(this.comboBox1);
this.groupBox3.Controls.Add(this.label3);
this.groupBox3.Location = new System.Drawing.Point(12, 89);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(646, 240);
this.groupBox3.TabIndex = 31;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "TARGET";
//
// openFilesCHKBOX
//
this.openFilesCHKBOX.AutoSize = true;
this.openFilesCHKBOX.Location = new System.Drawing.Point(442, 183);
this.openFilesCHKBOX.Name = "openFilesCHKBOX";
this.openFilesCHKBOX.Size = new System.Drawing.Size(194, 17);
this.openFilesCHKBOX.TabIndex = 30;
this.openFilesCHKBOX.Text = "Open updated files with NotePad++";
this.openFilesCHKBOX.UseVisualStyleBackColor = true;
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Location = new System.Drawing.Point(14, 183);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(220, 17);
this.checkBox1.TabIndex = 22;
this.checkBox1.Text = "Apply the same procedure to other nodes";
this.checkBox1.UseVisualStyleBackColor = true;
this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);
//
// comboBox1
//
this.comboBox1.Enabled = false;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(169, 202);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(43, 21);
this.comboBox1.TabIndex = 23;
this.comboBox1.SelectedValueChanged += new System.EventHandler(this.comboBox1_SelectedValueChanged);
this.comboBox1.DropDown += new System.EventHandler(this.comboBox1_DropDown);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(31, 205);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(121, 13);
this.label3.TabIndex = 24;
this.label3.Text = "Amount of nodes in total";
//
// groupBox4
//
this.groupBox4.Location = new System.Drawing.Point(12, 10);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(646, 77);
this.groupBox4.TabIndex = 32;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "SOURCE";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(930, 426);
this.Controls.Add(this.tabControl1);
this.Name = "Form1";
this.Text = "EasyClick";
this.tabControl1.ResumeLayout(false);
this.tabPage_BOP.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.tabPage_etc.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.tabPage3.ResumeLayout(false);
this.tabPage3.PerformLayout();
this.groupBox5.ResumeLayout(false);
this.groupBox5.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage_BOP;
private System.Windows.Forms.TabPage tabPage_etc;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckBox open_bop_config_folder_cbx;
private System.Windows.Forms.Button copy_bop_config_btn;
private System.Windows.Forms.RadioButton includesAll_btn;
private System.Windows.Forms.Button deselectBtn;
private System.Windows.Forms.ListBox lb1;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.RadioButton onlySelected_btn;
private System.Windows.Forms.Button TargetFolder_Bin_btn;
private System.Windows.Forms.RadioButton excludeSelected_btn;
private System.Windows.Forms.Button selectBtn;
private System.Windows.Forms.Label bop_config_target_folder_label;
private System.Windows.Forms.Button SourceFolder_Bin_btn;
private System.Windows.Forms.Label sourceBinFolder_lable;
private System.Windows.Forms.ListBox lb2;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.CheckBox open_etc_folder_cbx;
private System.Windows.Forms.Button copy_etc_btn;
private System.Windows.Forms.RadioButton includesAll_btn_b;
private System.Windows.Forms.Button deselectBtn_b;
private System.Windows.Forms.ListBox lb3;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.RadioButton onlySelected_btn_b;
private System.Windows.Forms.Button TargetFolder_etc_btn;
private System.Windows.Forms.RadioButton excludeSelected_btn_b;
private System.Windows.Forms.Button selectBtn_b;
private System.Windows.Forms.Label etc_target_folder_label;
private System.Windows.Forms.Button SourceFolder_etc_btn;
private System.Windows.Forms.Label sourceEtcFolder_lable;
private System.Windows.Forms.ListBox lb4;
private System.Windows.Forms.CheckBox filter_out_sys_altsys_files_ckb;
private System.Windows.Forms.CheckBox openFilesCHKBOX;
private System.Windows.Forms.Label sysinitFileFath;
private System.Windows.Forms.Label altsysinitFilePath;
private System.Windows.Forms.Button sysinitFilePath_TZ_btn;
private System.Windows.Forms.Button altsysinitFilePath_TZ_btn;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.Label BOP_sysinitFileName;
private System.Windows.Forms.Button TargetFileBtn;
private System.Windows.Forms.Button SourceFileBtn;
private System.Windows.Forms.Button ReplaceInfoBtn;
private System.Windows.Forms.Label SourceFileName;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.CheckBox checkBox2;
private System.Windows.Forms.ComboBox comboBox2;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.CheckBox checkBox3;
private System.Windows.Forms.ComboBox comboBox3;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.LinkLabel linkLabel1;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.LinkLabel linkLabel2;
}
}
| |
using UnityEngine;
using Stratus;
using System;
using System.Collections.Generic;
namespace Stratus.Gameplay
{
/// <summary>
/// The base class that drives the logic for the game's combat system.
/// </summary>
public abstract class StratusCombatSystem : StratusBehaviour
{
//------------------------------------------------------------------------/
// Events
//------------------------------------------------------------------------/
public class ReferenceEvent : StratusEvent { public StratusCombatSystem System; }
/// <summary>
/// Informs that the combat system has finished its initialization routine
/// </summary>
public class InitializedEvent : StratusEvent { }
/// <summary>
/// Informs that combat has been resolved
/// </summary>
public class ResolveEvent : StratusEvent { }
/// <summary>
/// Informs that combat has been won by the player
/// </summary>
public class VictoryEvent : StratusEvent { public StratusCombatEncounter Encounter; }
/// <summary>
/// Informs that the player has been defeated
/// </summary>
public class DefeatEvent : StratusEvent { public StratusCombatEncounter Encounter; }
/// <summary>
// Informs that combat is to be retried/
/// </summary>
public class RetryEvent : StratusEvent { public StratusCombatEncounter Encounter; }
//------------------------------------------------------------------------/
// Properties
//------------------------------------------------------------------------/
public bool debug = false;
/// <summary>
/// Whether combat has been resolved.
/// </summary>
protected bool IsResolved = false;
//------------------------------------------------------------------------/
// Interface
//------------------------------------------------------------------------/
// Combatants
protected abstract void OnConfigureCombatController(StratusCombatController CombatController);
protected abstract void OnCombatControllerSpawn(StratusCombatController controller);
protected abstract void OnCombatControllerDeath(StratusCombatController controller);
// System
protected abstract void OnCombatSystemInitialize();
protected abstract void OnCombatSystemSubscribe();
protected abstract void OnCombatSystemTerminate();
protected abstract void OnCombatSystemUpdate();
// Combat
protected abstract void OnCombatStart();
protected abstract void OnCombatRetry();
//------------------------------------------------------------------------/
// Messages
//------------------------------------------------------------------------/
private void Awake()
{
this.Subscribe();
this.OnCombatSystemSubscribe();
this.OnCombatSystemInitialize();
// Announce that the combat system has finished initializing
StratusScene.Dispatch<InitializedEvent>(new InitializedEvent());
}
/// <summary>
/// Updates the battle system every frame.
/// </summary>
void FixedUpdate()
{
if (IsResolved)
return;
this.OnCombatSystemUpdate();
}
//------------------------------------------------------------------------/
// Methods
//------------------------------------------------------------------------/
/// <summary>
/// Subscribe to events.
/// </summary>
protected virtual void Subscribe()
{
StratusScene.Connect<StratusCombatController.SpawnEvent>(this.OnCombatControllerSpawnEvent);
StratusScene.Connect<StratusCombatController.DeactivateEvent>(this.OnCombatControllerDeathEvent);
StratusScene.Connect<RetryEvent>(this.OnCombatRetryEvent);
}
/// <summary>
/// Registers the CombatControllers depending on their given faction.
/// </summary>
/// <param name="e"></param>
void OnCombatControllerSpawnEvent(StratusCombatController.SpawnEvent e)
{
OnCombatControllerSpawn(e.controller);
}
/// <summary>
/// Received when a combat controller becomes inactive (such as being knocked out)
/// </summary>
/// <param name="e">The controller which has gone inactive. </param>
void OnCombatControllerDeathEvent(StratusCombatController.DeactivateEvent e)
{
OnCombatControllerDeath(e.controller);
}
void OnCombatRetryEvent(RetryEvent e)
{
this.OnCombatRetry();
}
protected void StartCombat()
{
//Gamestate.Change(Gamestate.State.Combat);
StratusScene.Dispatch<StratusCombat.StartedEvent>(new StratusCombat.StartedEvent());
}
protected void EndCombat()
{
//Gamestate.Revert();
StratusScene.Dispatch<StratusCombat.EndedEvent>(new StratusCombat.EndedEvent());
}
}
public enum StratusCombatState
{
Setup,
Started,
Ended
}
public enum StratusCombatResolutionResult
{
Ongoing,
Victory,
Defeat
}
public abstract class StratusCombatResolutionPredicate : IStratusLogger
{
public string label;
public virtual string title => label;
public abstract string description { get; }
private Func<StratusCombatResolutionResult> isResolved { get; set; }
public StratusCombatResolutionPredicate(string label)
{
this.label = label;
this.isResolved = isResolved;
}
public abstract StratusCombatResolutionResult IsResolved(IStratusCombatSystem system);
public override string ToString()
{
return label;
}
}
public abstract class StratusCombatResolutionPredicate<CombatSystem>
: StratusCombatResolutionPredicate
where CombatSystem : class, IStratusCombatSystem
{
public StratusCombatResolutionPredicate(string label) : base(label)
{
}
public override StratusCombatResolutionResult IsResolved(IStratusCombatSystem system)
{
return OnIsResolved(system as CombatSystem);
}
protected abstract StratusCombatResolutionResult OnIsResolved(CombatSystem system);
}
public interface IStratusCombatSystem
{
void StartCombat(StratusCombatResolutionPredicate predicate);
void EndCombat(StratusCombatResolutionResult resolution);
}
public abstract class StratusCombatResults
{
public StratusCombatResolutionResult resolution;
public int unitsSpawned;
public int unitsDefeated;
public int playerUnitsSpawned;
public int playerUnitsDefeated;
public int enemyUnitsSpawned;
public int enemyUnitsDefeated;
}
public abstract class StratusCombatSystem<T, CombatController, CombatResults>
: StratusSingletonBehaviour<T>, IStratusCombatSystem
where T : StratusCombatSystem<T, CombatController, CombatResults>
where CombatController : class, IStratusCombatController
where CombatResults : StratusCombatResults, new()
{
//------------------------------------------------------------------------/
// Declarations
//------------------------------------------------------------------------/
/// <summary>
/// Informs that combat has been resolved
/// </summary>
public class ResolveEvent : StratusEvent
{
}
/// <summary>
/// Combat has started
/// </summary>
public class StartedEvent : StratusEvent
{
public StratusCombatResolutionPredicate predicate;
public StartedEvent(StratusCombatResolutionPredicate predicate)
{
this.predicate = predicate;
}
}
/// <summary>
/// Combat has ended
/// </summary>
public class EndedEvent : ResolveEvent
{
public CombatResults results { get; private set; }
public StratusCombatResolutionResult resolution => results.resolution;
public EndedEvent(CombatResults results)
{
this.results = results;
}
}
//------------------------------------------------------------------------/
// Fields
//------------------------------------------------------------------------/
private List<CombatController> _controllers = new List<CombatController>();
private List<CombatController> _queuedControllers = new List<CombatController>();
//------------------------------------------------------------------------/
// Properties
//------------------------------------------------------------------------/
/// <summary>
/// Whether this system is being debugged currently
/// </summary>
public virtual bool debug => true;
/// <summary>
/// The current combat state
/// </summary>
public StratusCombatState state
{
get => _state;
set
{
if (value != _state)
{
_state = value;
onStateChanged?.Invoke(value);
}
}
}
private StratusCombatState _state;
/// <summary>
/// All active combat controllers
/// </summary>
protected CombatController[] controllers => _controllers.ToArray();
/// <summary>
/// The number of active combat controllers
/// </summary>
public int controllerCount => _controllers.Count;
/// <summary>
/// Decides how combat is resolved
/// </summary>
public StratusCombatResolutionPredicate resolutionPredicate { get; private set; }
/// <summary>
/// When combat starts, collects all relevant combat data
/// </summary>
public CombatResults results { get; private set; }
//------------------------------------------------------------------------/
// Events
//------------------------------------------------------------------------/
public event Action<StratusCombatState> onStateChanged;
public event Action<CombatController> onControllerAdded;
public event Action<CombatController> onControllerRemoved;
//------------------------------------------------------------------------/
// Abstract
//------------------------------------------------------------------------/
protected abstract void OnCombatSystemInitialize();
protected abstract void OnCombatSystemTerminate();
protected abstract void OnStartCombat(CombatController[] controllers);
protected abstract void OnEndCombat();
protected abstract void OnCombatRetry();
protected abstract void OnControllerAdded(CombatController combatController);
protected abstract void OnControllerRemoved(CombatController combatController);
//------------------------------------------------------------------------/
// Messages
//------------------------------------------------------------------------/
protected override void OnAwake()
{
state = StratusCombatState.Setup;
OnCombatSystemInitialize();
StratusScene.Connect<StratusCombatController.SpawnEvent>(OnCombatControllerSpawnEvent);
//Scene.Connect<StratusCombatController.DespawnEvent>(OnCombatControllerDespawnEvent);
StratusScene.Connect<StratusCombatController.ActivateEvent>(OnCombatControllerActivateEvent);
StratusScene.Connect<StratusCombatController.DeactivateEvent>(OnCombatControllerDeactivateEvent);
}
//------------------------------------------------------------------------/
// Methods
//------------------------------------------------------------------------/
public void StartCombat(StratusCombatResolutionPredicate predicate)
{
state = StratusCombatState.Started;
this.results = new CombatResults();
this.resolutionPredicate = predicate;
AddQueuedControllers();
//ActivateControllers();
OnStartCombat(controllers);
this.Log($"Combat started with predicate: {resolutionPredicate}");
StratusScene.Dispatch<StartedEvent>(new StartedEvent(predicate));
}
public void EndCombat(StratusCombatResolutionResult resolution)
{
state = StratusCombatState.Ended;
OnEndCombat();
this.Log($"Combat ended: {resolutionPredicate}");
results.resolution = resolution;
StratusScene.Dispatch<EndedEvent>(new EndedEvent( results));
}
public StratusCombatResolutionResult IsResolved()
{
if (state != StratusCombatState.Started)
{
throw new Exception("Combat not yet started");
}
return resolutionPredicate.IsResolved(this);
}
//------------------------------------------------------------------------/
// Events
//------------------------------------------------------------------------/
/// <summary>
/// When a controller is initialized, we add it or queue it to be added
/// when combat starts
/// </summary>
/// <param name="e"></param>
private void OnCombatControllerSpawnEvent(StratusCombatController.SpawnEvent e)
{
CombatController controller = e.controller as CombatController;
if (controller != null)
{
Add(controller);
}
}
//private void OnCombatControllerDespawnEvent(StratusCombatController.DespawnEvent e)
//{
// CombatController controller = e.controller as CombatController;
// if (controller != null)
// {
// //Remove(controller);
// }
//}
/// <summary>
/// When a controller requests to be activated, it is valid only when combat has already started
/// </summary>
/// <param name="e"></param>
private void OnCombatControllerActivateEvent(StratusCombatController.ActivateEvent e)
{
CombatController controller = e.controller as CombatController;
if (controller != null)
{
if (state == StratusCombatState.Started)
{
e.valid = true;
}
else
{
this.LogError($"Cannot active {controller} while combat not started");
}
}
}
/// <summary>
/// When a controller requests to be deactivated, it is valid only when combat has already started
/// </summary>
/// <param name="e"></param>
private void OnCombatControllerDeactivateEvent(StratusCombatController.DeactivateEvent e)
{
CombatController controller = e.controller as CombatController;
if (controller != null)
{
if (state == StratusCombatState.Started)
{
e.valid = true;
Remove(controller);
}
else
{
this.LogError($"Cannot deactivate {controller} while combat not started");
}
}
}
//------------------------------------------------------------------------/
// Controllers
//------------------------------------------------------------------------/
public void Add(CombatController controller)
{
if (state == StratusCombatState.Setup)
{
this.Log($"Queuing controller {controller} to be added when combat starts...");
_queuedControllers.Add(controller);
return;
}
_controllers.Add(controller);
OnControllerAdded(controller);
onControllerAdded?.Invoke(controller);
controller.Activate();
results.unitsSpawned++;
}
public void Remove(CombatController controller)
{
_controllers.Remove(controller);
OnControllerRemoved(controller);
onControllerRemoved?.Invoke(controller);
results.unitsDefeated++;
}
private void AddQueuedControllers()
{
foreach(var controller in _queuedControllers)
{
Add(controller);
}
_queuedControllers.Clear();
}
//private void ActivateControllers()
//{
// this.Log("Now activating all controllers");
// foreach (var controller in controllers)
// {
// controller.Activate();
// }
//}
}
}
| |
// 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 Internal.Runtime.Augments;
using System.Diagnostics; // for TraceInformation
using System.Runtime.CompilerServices;
namespace System.Threading
{
public enum LockRecursionPolicy
{
NoRecursion = 0,
SupportsRecursion = 1,
}
//
// ReaderWriterCount tracks how many of each kind of lock is held by each thread.
// We keep a linked list for each thread, attached to a ThreadStatic field.
// These are reused wherever possible, so that a given thread will only
// allocate N of these, where N is the maximum number of locks held simultaneously
// by that thread.
//
internal class ReaderWriterCount
{
// Which lock does this object belong to? This is a numeric ID for two reasons:
// 1) We don't want this field to keep the lock object alive, and a WeakReference would
// be too expensive.
// 2) Setting the value of a long is faster than setting the value of a reference.
// The "hot" paths in ReaderWriterLockSlim are short enough that this actually
// matters.
public long lockID;
// How many reader locks does this thread hold on this ReaderWriterLockSlim instance?
public int readercount;
// Ditto for writer/upgrader counts. These are only used if the lock allows recursion.
// But we have to have the fields on every ReaderWriterCount instance, because
// we reuse it for different locks.
public int writercount;
public int upgradecount;
// Next RWC in this thread's list.
public ReaderWriterCount next;
}
/// <summary>
/// A reader-writer lock implementation that is intended to be simple, yet very
/// efficient. In particular only 1 interlocked operation is taken for any lock
/// operation (we use spin locks to achieve this). The spin lock is never held
/// for more than a few instructions (in particular, we never call event APIs
/// or in fact any non-trivial API while holding the spin lock).
/// </summary>
public class ReaderWriterLockSlim : IDisposable
{
private static readonly int ProcessorCount = Environment.ProcessorCount;
//Specifying if locked can be reacquired recursively.
private readonly bool _fIsReentrant;
// Lock specification for myLock: This lock protects exactly the local fields associated with this
// instance of ReaderWriterLockSlim. It does NOT protect the memory associated with
// the events that hang off this lock (eg writeEvent, readEvent upgradeEvent).
private int _myLock;
//The variables controlling spinning behavior of Mylock(which is a spin-lock)
private const int LockSpinCycles = 20;
private const int LockSpinCount = 10;
private const int LockSleep0Count = 5;
// These variables allow use to avoid Setting events (which is expensive) if we don't have to.
private uint _numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent
private uint _numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent
private uint _numWriteUpgradeWaiters; // maximum number of threads that can be doing a WaitOne on the upgradeEvent (at most 1).
private uint _numUpgradeWaiters;
private WaiterStates _waiterStates;
private int _upgradeLockOwnerId;
private int _writeLockOwnerId;
// conditions we wait on.
private EventWaitHandle _writeEvent; // threads waiting to acquire a write lock go here.
private EventWaitHandle _readEvent; // threads waiting to acquire a read lock go here (will be released in bulk)
private EventWaitHandle _upgradeEvent; // thread waiting to acquire the upgrade lock
private EventWaitHandle _waitUpgradeEvent; // thread waiting to upgrade from the upgrade lock to a write lock go here (at most one)
// Every lock instance has a unique ID, which is used by ReaderWriterCount to associate itself with the lock
// without holding a reference to it.
private static long s_nextLockID;
private long _lockID;
// See comments on ReaderWriterCount.
[ThreadStatic]
private static ReaderWriterCount t_rwc;
private bool _fUpgradeThreadHoldingRead;
private const int MaxSpinCount = 20;
//The uint, that contains info like if the writer lock is held, num of
//readers etc.
private uint _owners;
//Various R/W masks
//Note:
//The Uint is divided as follows:
//
//Writer-Owned Waiting-Writers Waiting Upgraders Num-Readers
// 31 30 29 28.......0
//
//Dividing the uint, allows to vastly simplify logic for checking if a
//reader should go in etc. Setting the writer bit will automatically
//make the value of the uint much larger than the max num of readers
//allowed, thus causing the check for max_readers to fail.
private const uint WRITER_HELD = 0x80000000;
private const uint WAITING_WRITERS = 0x40000000;
private const uint WAITING_UPGRADER = 0x20000000;
//The max readers is actually one less then its theoretical max.
//This is done in order to prevent reader count overflows. If the reader
//count reaches max, other readers will wait.
private const uint MAX_READER = 0x10000000 - 2;
private const uint READER_MASK = 0x10000000 - 1;
private bool _fDisposed;
private void InitializeThreadCounts()
{
_upgradeLockOwnerId = -1;
_writeLockOwnerId = -1;
}
public ReaderWriterLockSlim()
: this(LockRecursionPolicy.NoRecursion)
{
}
public ReaderWriterLockSlim(LockRecursionPolicy recursionPolicy)
{
if (recursionPolicy == LockRecursionPolicy.SupportsRecursion)
{
_fIsReentrant = true;
}
InitializeThreadCounts();
_waiterStates = WaiterStates.NoWaiters;
_lockID = Interlocked.Increment(ref s_nextLockID);
}
private bool HasNoWaiters
{
get
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
return (_waiterStates & WaiterStates.NoWaiters) != WaiterStates.None;
}
set
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
if (value)
{
_waiterStates |= WaiterStates.NoWaiters;
}
else
{
_waiterStates &= ~WaiterStates.NoWaiters;
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsRWEntryEmpty(ReaderWriterCount rwc)
{
if (rwc.lockID == 0)
return true;
else if (rwc.readercount == 0 && rwc.writercount == 0 && rwc.upgradecount == 0)
return true;
else
return false;
}
private bool IsRwHashEntryChanged(ReaderWriterCount lrwc)
{
return lrwc.lockID != _lockID;
}
/// <summary>
/// This routine retrieves/sets the per-thread counts needed to enforce the
/// various rules related to acquiring the lock.
///
/// DontAllocate is set to true if the caller just wants to get an existing
/// entry for this thread, but doesn't want to add one if an existing one
/// could not be found.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ReaderWriterCount GetThreadRWCount(bool dontAllocate)
{
ReaderWriterCount rwc = t_rwc;
ReaderWriterCount empty = null;
while (rwc != null)
{
if (rwc.lockID == _lockID)
return rwc;
if (!dontAllocate && empty == null && IsRWEntryEmpty(rwc))
empty = rwc;
rwc = rwc.next;
}
if (dontAllocate)
return null;
if (empty == null)
{
empty = new ReaderWriterCount();
empty.next = t_rwc;
t_rwc = empty;
}
empty.lockID = _lockID;
return empty;
}
public void EnterReadLock()
{
TryEnterReadLock(-1);
}
//
// Common timeout support
//
private struct TimeoutTracker
{
private int _total;
private int _start;
public TimeoutTracker(TimeSpan timeout)
{
long ltm = (long)timeout.TotalMilliseconds;
if (ltm < -1 || ltm > (long)Int32.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout));
_total = (int)ltm;
if (_total != -1 && _total != 0)
_start = Environment.TickCount;
else
_start = 0;
}
public TimeoutTracker(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
_total = millisecondsTimeout;
if (_total != -1 && _total != 0)
_start = Environment.TickCount;
else
_start = 0;
}
public int RemainingMilliseconds
{
get
{
if (_total == -1 || _total == 0)
return _total;
int elapsed = Environment.TickCount - _start;
// elapsed may be negative if TickCount has overflowed by 2^31 milliseconds.
if (elapsed < 0 || elapsed >= _total)
return 0;
return _total - elapsed;
}
}
public bool IsExpired
{
get
{
return RemainingMilliseconds == 0;
}
}
}
public bool TryEnterReadLock(TimeSpan timeout)
{
return TryEnterReadLock(new TimeoutTracker(timeout));
}
public bool TryEnterReadLock(int millisecondsTimeout)
{
return TryEnterReadLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterReadLock(TimeoutTracker timeout)
{
return TryEnterReadLockCore(timeout);
}
private bool TryEnterReadLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
ReaderWriterCount lrwc = null;
int id = Environment.CurrentManagedThreadId;
if (!_fIsReentrant)
{
if (id == _writeLockOwnerId)
{
//Check for AW->AR
throw new LockRecursionException(SR.LockRecursionException_ReadAfterWriteNotAllowed);
}
EnterMyLock();
lrwc = GetThreadRWCount(false);
//Check if the reader lock is already acquired. Note, we could
//check the presence of a reader by not allocating rwc (But that
//would lead to two lookups in the common case. It's better to keep
//a count in the structure).
if (lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_RecursiveReadNotAllowed);
}
else if (id == _upgradeLockOwnerId)
{
//The upgrade lock is already held.
//Update the global read counts and exit.
lrwc.readercount++;
_owners++;
ExitMyLock();
return true;
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (lrwc.readercount > 0)
{
lrwc.readercount++;
ExitMyLock();
return true;
}
else if (id == _upgradeLockOwnerId)
{
//The upgrade lock is already held.
//Update the global read counts and exit.
lrwc.readercount++;
_owners++;
ExitMyLock();
_fUpgradeThreadHoldingRead = true;
return true;
}
else if (id == _writeLockOwnerId)
{
//The write lock is already held.
//Update global read counts here,
lrwc.readercount++;
_owners++;
ExitMyLock();
return true;
}
}
bool retVal = true;
int spinCount = 0;
for (; ;)
{
// We can enter a read lock if there are only read-locks have been given out
// and a writer is not trying to get in.
if (_owners < MAX_READER)
{
// Good case, there is no contention, we are basically done
_owners++; // Indicate we have another reader
lrwc.readercount++;
break;
}
if (timeout.IsExpired)
{
ExitMyLock();
return false;
}
if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyRead())
{
ExitMyLock();
spinCount++;
SpinWait(spinCount);
EnterMyLock();
//The per-thread structure may have been recycled as the lock is acquired (due to message pumping), load again.
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
continue;
}
// Drat, we need to wait. Mark that we have waiters and wait.
if (_readEvent == null) // Create the needed event
{
LazyCreateEvent(ref _readEvent, false);
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
continue; // since we left the lock, start over.
}
retVal =
WaitOnEvent(
_readEvent,
ref _numReadWaiters,
timeout,
isWriteWaiter: false,
waiterSignaledState: WaiterStates.None);
if (!retVal)
{
return false;
}
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
}
ExitMyLock();
return retVal;
}
public void EnterWriteLock()
{
TryEnterWriteLock(-1);
}
public bool TryEnterWriteLock(TimeSpan timeout)
{
return TryEnterWriteLock(new TimeoutTracker(timeout));
}
public bool TryEnterWriteLock(int millisecondsTimeout)
{
return TryEnterWriteLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterWriteLock(TimeoutTracker timeout)
{
return TryEnterWriteLockCore(timeout);
}
private bool TryEnterWriteLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
int id = Environment.CurrentManagedThreadId;
ReaderWriterCount lrwc;
bool upgradingToWrite = false;
if (!_fIsReentrant)
{
if (id == _writeLockOwnerId)
{
//Check for AW->AW
throw new LockRecursionException(SR.LockRecursionException_RecursiveWriteNotAllowed);
}
else if (id == _upgradeLockOwnerId)
{
//AU->AW case is allowed once.
upgradingToWrite = true;
}
EnterMyLock();
lrwc = GetThreadRWCount(true);
//Can't acquire write lock with reader lock held.
if (lrwc != null && lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (id == _writeLockOwnerId)
{
lrwc.writercount++;
ExitMyLock();
return true;
}
else if (id == _upgradeLockOwnerId)
{
upgradingToWrite = true;
}
else if (lrwc.readercount > 0)
{
//Write locks may not be acquired if only read locks have been
//acquired.
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
}
}
bool retVal = true;
int spinCount = 0;
for (; ;)
{
if (IsWriterAcquired())
{
// Good case, there is no contention, we are basically done
SetWriterAcquired();
break;
}
//Check if there is just one upgrader, and no readers.
//Assumption: Only one thread can have the upgrade lock, so the
//following check will fail for all other threads that may sneak in
//when the upgrading thread is waiting.
if (upgradingToWrite)
{
uint readercount = GetNumReaders();
if (readercount == 1)
{
//Good case again, there is just one upgrader, and no readers.
SetWriterAcquired(); // indicate we have a writer.
break;
}
else if (readercount == 2)
{
if (lrwc != null)
{
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
if (lrwc.readercount > 0)
{
//This check is needed for EU->ER->EW case, as the owner count will be two.
Debug.Assert(_fIsReentrant);
Debug.Assert(_fUpgradeThreadHoldingRead);
//Good case again, there is just one upgrader, and no readers.
SetWriterAcquired(); // indicate we have a writer.
break;
}
}
}
}
if (timeout.IsExpired)
{
ExitMyLock();
return false;
}
if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyWrite(upgradingToWrite))
{
ExitMyLock();
spinCount++;
SpinWait(spinCount);
EnterMyLock();
continue;
}
if (upgradingToWrite)
{
if (_waitUpgradeEvent == null) // Create the needed event
{
LazyCreateEvent(ref _waitUpgradeEvent, true);
continue; // since we left the lock, start over.
}
Debug.Assert(_numWriteUpgradeWaiters == 0, "There can be at most one thread with the upgrade lock held.");
retVal =
WaitOnEvent(
_waitUpgradeEvent,
ref _numWriteUpgradeWaiters,
timeout,
isWriteWaiter: true,
waiterSignaledState: WaiterStates.None);
//The lock is not held in case of failure.
if (!retVal)
return false;
}
else
{
// Drat, we need to wait. Mark that we have waiters and wait.
if (_writeEvent == null) // create the needed event.
{
LazyCreateEvent(ref _writeEvent, true);
continue; // since we left the lock, start over.
}
retVal =
WaitOnEvent(
_writeEvent,
ref _numWriteWaiters,
timeout,
isWriteWaiter: true,
waiterSignaledState: WaiterStates.WriteWaiterSignaled);
//The lock is not held in case of failure.
if (!retVal)
return false;
}
}
Debug.Assert((_owners & WRITER_HELD) > 0);
if (_fIsReentrant)
{
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
lrwc.writercount++;
}
ExitMyLock();
_writeLockOwnerId = id;
return true;
}
public void EnterUpgradeableReadLock()
{
TryEnterUpgradeableReadLock(-1);
}
public bool TryEnterUpgradeableReadLock(TimeSpan timeout)
{
return TryEnterUpgradeableReadLock(new TimeoutTracker(timeout));
}
public bool TryEnterUpgradeableReadLock(int millisecondsTimeout)
{
return TryEnterUpgradeableReadLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterUpgradeableReadLock(TimeoutTracker timeout)
{
return TryEnterUpgradeableReadLockCore(timeout);
}
private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
int id = Environment.CurrentManagedThreadId;
ReaderWriterCount lrwc;
if (!_fIsReentrant)
{
if (id == _upgradeLockOwnerId)
{
//Check for AU->AU
throw new LockRecursionException(SR.LockRecursionException_RecursiveUpgradeNotAllowed);
}
else if (id == _writeLockOwnerId)
{
//Check for AU->AW
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterWriteNotAllowed);
}
EnterMyLock();
lrwc = GetThreadRWCount(true);
//Can't acquire upgrade lock with reader lock held.
if (lrwc != null && lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (id == _upgradeLockOwnerId)
{
lrwc.upgradecount++;
ExitMyLock();
return true;
}
else if (id == _writeLockOwnerId)
{
//Write lock is already held, Just update the global state
//to show presence of upgrader.
Debug.Assert((_owners & WRITER_HELD) > 0);
_owners++;
_upgradeLockOwnerId = id;
lrwc.upgradecount++;
if (lrwc.readercount > 0)
_fUpgradeThreadHoldingRead = true;
ExitMyLock();
return true;
}
else if (lrwc.readercount > 0)
{
//Upgrade locks may not be acquired if only read locks have been
//acquired.
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
}
}
bool retVal = true;
int spinCount = 0;
for (; ;)
{
//Once an upgrade lock is taken, it's like having a reader lock held
//until upgrade or downgrade operations are performed.
if ((_upgradeLockOwnerId == -1) && (_owners < MAX_READER))
{
_owners++;
_upgradeLockOwnerId = id;
break;
}
if (timeout.IsExpired)
{
ExitMyLock();
return false;
}
if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyRead())
{
ExitMyLock();
spinCount++;
SpinWait(spinCount);
EnterMyLock();
continue;
}
// Drat, we need to wait. Mark that we have waiters and wait.
if (_upgradeEvent == null) // Create the needed event
{
LazyCreateEvent(ref _upgradeEvent, true);
continue; // since we left the lock, start over.
}
//Only one thread with the upgrade lock held can proceed.
retVal =
WaitOnEvent(
_upgradeEvent,
ref _numUpgradeWaiters,
timeout,
isWriteWaiter: false,
waiterSignaledState: WaiterStates.UpgradeableReadWaiterSignaled);
if (!retVal)
return false;
}
if (_fIsReentrant)
{
//The lock may have been dropped getting here, so make a quick check to see whether some other
//thread did not grab the entry.
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
lrwc.upgradecount++;
}
ExitMyLock();
return true;
}
public void ExitReadLock()
{
ReaderWriterCount lrwc = null;
EnterMyLock();
lrwc = GetThreadRWCount(true);
if (lrwc == null || lrwc.readercount < 1)
{
//You have to be holding the read lock to make this call.
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedRead);
}
if (_fIsReentrant)
{
if (lrwc.readercount > 1)
{
lrwc.readercount--;
ExitMyLock();
return;
}
if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
{
_fUpgradeThreadHoldingRead = false;
}
}
Debug.Assert(_owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
--_owners;
Debug.Assert(lrwc.readercount == 1);
lrwc.readercount--;
ExitAndWakeUpAppropriateWaiters();
}
public void ExitWriteLock()
{
ReaderWriterCount lrwc;
if (!_fIsReentrant)
{
if (Environment.CurrentManagedThreadId != _writeLockOwnerId)
{
//You have to be holding the write lock to make this call.
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
EnterMyLock();
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (lrwc == null)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
if (lrwc.writercount < 1)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
lrwc.writercount--;
if (lrwc.writercount > 0)
{
ExitMyLock();
return;
}
}
Debug.Assert((_owners & WRITER_HELD) > 0, "Calling ReleaseWriterLock when no write lock is held");
ClearWriterAcquired();
_writeLockOwnerId = -1;
ExitAndWakeUpAppropriateWaiters();
}
public void ExitUpgradeableReadLock()
{
ReaderWriterCount lrwc;
if (!_fIsReentrant)
{
if (Environment.CurrentManagedThreadId != _upgradeLockOwnerId)
{
//You have to be holding the upgrade lock to make this call.
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
EnterMyLock();
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(true);
if (lrwc == null)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
if (lrwc.upgradecount < 1)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
lrwc.upgradecount--;
if (lrwc.upgradecount > 0)
{
ExitMyLock();
return;
}
_fUpgradeThreadHoldingRead = false;
}
_owners--;
_upgradeLockOwnerId = -1;
ExitAndWakeUpAppropriateWaiters();
}
/// <summary>
/// A routine for lazily creating a event outside the lock (so if errors
/// happen they are outside the lock and that we don't do much work
/// while holding a spin lock). If all goes well, reenter the lock and
/// set 'waitEvent'
/// </summary>
private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent)
{
#if DEBUG
Debug.Assert(MyLockHeld);
Debug.Assert(waitEvent == null);
#endif
ExitMyLock();
EventWaitHandle newEvent;
if (makeAutoResetEvent)
newEvent = new AutoResetEvent(false);
else
newEvent = new ManualResetEvent(false);
EnterMyLock();
if (waitEvent == null) // maybe someone snuck in.
waitEvent = newEvent;
else
newEvent.Dispose();
}
/// <summary>
/// Waits on 'waitEvent' with a timeout
/// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
/// </summary>
private bool WaitOnEvent(
EventWaitHandle waitEvent,
ref uint numWaiters,
TimeoutTracker timeout,
bool isWriteWaiter,
WaiterStates waiterSignaledState)
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
Debug.Assert(
waiterSignaledState == WaiterStates.None ||
waiterSignaledState == WaiterStates.WriteWaiterSignaled ||
waiterSignaledState == WaiterStates.UpgradeableReadWaiterSignaled);
waitEvent.Reset();
numWaiters++;
HasNoWaiters = false;
//Setting these bits will prevent new readers from getting in.
if (_numWriteWaiters == 1)
SetWritersWaiting();
if (_numWriteUpgradeWaiters == 1)
SetUpgraderWaiting();
bool waitSuccessful = false;
ExitMyLock(); // Do the wait outside of any lock
try
{
waitSuccessful = waitEvent.WaitOne(timeout.RemainingMilliseconds);
}
finally
{
EnterMyLock();
--numWaiters;
if (waitSuccessful && waiterSignaledState != WaiterStates.None)
{
// Indicate that a signaled waiter of this type has woken. Since non-read waiters are signaled to wake one
// at a time, we avoid waking up more than one waiter of that type upon successive enter/exit loops until
// the signaled thread actually wakes up. For example, if there are multiple write waiters and one thread is
// repeatedly entering and exiting a write lock, every exit would otherwise signal a different write waiter
// to wake up unnecessarily when only one woken waiter may actually succeed in entering the write lock.
Debug.Assert((_waiterStates & waiterSignaledState) != WaiterStates.None);
_waiterStates &= ~waiterSignaledState;
}
if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0)
HasNoWaiters = true;
if (_numWriteWaiters == 0)
ClearWritersWaiting();
if (_numWriteUpgradeWaiters == 0)
ClearUpgraderWaiting();
if (!waitSuccessful) // We may also be about to throw for some reason. Exit myLock.
{
if (isWriteWaiter)
{
// Write waiters block read waiters from acquiring the lock. Since this was the last write waiter, try
// to wake up the appropriate read waiters.
ExitAndWakeUpAppropriateReadWaiters();
}
else
ExitMyLock();
}
}
return waitSuccessful;
}
/// <summary>
/// Determines the appropriate events to set, leaves the locks, and sets the events.
/// </summary>
private void ExitAndWakeUpAppropriateWaiters()
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
if (HasNoWaiters)
{
ExitMyLock();
return;
}
ExitAndWakeUpAppropriateWaitersPreferringWriters();
}
private void ExitAndWakeUpAppropriateWaitersPreferringWriters()
{
uint readercount = GetNumReaders();
//We need this case for EU->ER->EW case, as the read count will be 2 in
//that scenario.
if (_fIsReentrant)
{
if (_numWriteUpgradeWaiters > 0 && _fUpgradeThreadHoldingRead && readercount == 2)
{
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
_waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one).
return;
}
}
if (readercount == 1 && _numWriteUpgradeWaiters > 0)
{
//We have to be careful now, as we are dropping the lock.
//No new writes should be allowed to sneak in if an upgrade
//was pending.
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
_waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one).
}
else if (readercount == 0 && _numWriteWaiters > 0)
{
// Check if a waiter of the same type has already been signaled but hasn't woken yet. If so, avoid signaling
// and waking another waiter unnecessarily.
WaiterStates signaled = _waiterStates & WaiterStates.WriteWaiterSignaled;
if (signaled == WaiterStates.None)
{
_waiterStates |= WaiterStates.WriteWaiterSignaled;
}
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
if (signaled == WaiterStates.None)
{
_writeEvent.Set(); // release one writer.
}
}
else
{
ExitAndWakeUpAppropriateReadWaiters();
}
}
private void ExitAndWakeUpAppropriateReadWaiters()
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
if (_numWriteWaiters != 0 || _numWriteUpgradeWaiters != 0 || HasNoWaiters)
{
ExitMyLock();
return;
}
Debug.Assert(_numReadWaiters != 0 || _numUpgradeWaiters != 0);
bool setReadEvent = _numReadWaiters != 0;
bool setUpgradeEvent = _numUpgradeWaiters != 0 && _upgradeLockOwnerId == -1;
if (setUpgradeEvent)
{
// Check if a waiter of the same type has already been signaled but hasn't woken yet. If so, avoid signaling
// and waking another waiter unnecessarily.
if ((_waiterStates & WaiterStates.UpgradeableReadWaiterSignaled) == WaiterStates.None)
{
_waiterStates |= WaiterStates.UpgradeableReadWaiterSignaled;
}
else
{
setUpgradeEvent = false;
}
}
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
if (setReadEvent)
_readEvent.Set(); // release all readers.
if (setUpgradeEvent)
_upgradeEvent.Set(); //release one upgrader.
}
private bool IsWriterAcquired()
{
return (_owners & ~WAITING_WRITERS) == 0;
}
private void SetWriterAcquired()
{
_owners |= WRITER_HELD; // indicate we have a writer.
}
private void ClearWriterAcquired()
{
_owners &= ~WRITER_HELD;
}
private void SetWritersWaiting()
{
_owners |= WAITING_WRITERS;
}
private void ClearWritersWaiting()
{
_owners &= ~WAITING_WRITERS;
}
private void SetUpgraderWaiting()
{
_owners |= WAITING_UPGRADER;
}
private void ClearUpgraderWaiting()
{
_owners &= ~WAITING_UPGRADER;
}
private uint GetNumReaders()
{
return _owners & READER_MASK;
}
private bool ShouldSpinForEnterAnyRead()
{
// If there is a write waiter or write upgrade waiter, the waiter would block a reader from acquiring the RW lock
// because the waiter takes precedence. In that case, the reader is not likely to make progress by spinning.
// Although another thread holding a write lock would prevent this thread from acquiring a read lock, it is by
// itself not a good enough reason to skip spinning.
return HasNoWaiters || (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0);
}
private bool ShouldSpinForEnterAnyWrite(bool isUpgradeToWrite)
{
// If there is a write upgrade waiter, the waiter would block a writer from acquiring the RW lock because the waiter
// holds a read lock. In that case, the writer is not likely to make progress by spinning. Regarding upgrading to a
// write lock, there is no type of waiter that would block the upgrade from happening. Although another thread
// holding a read or write lock would prevent this thread from acquiring the write lock, it is by itself not a good
// enough reason to skip spinning.
return isUpgradeToWrite || _numWriteUpgradeWaiters == 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool TryEnterMyLock()
{
return Interlocked.CompareExchange(ref _myLock, 1, 0) == 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnterMyLock()
{
if (!TryEnterMyLock())
{
EnterMyLockSpin();
}
}
private void EnterMyLockSpin()
{
int processorCount = ProcessorCount;
for (int spinIndex = 0; ; spinIndex++)
{
if (spinIndex < LockSpinCount && processorCount > 1)
{
RuntimeThread.SpinWait(LockSpinCycles * (spinIndex + 1)); // Wait a few dozen instructions to let another processor release lock.
}
else if (spinIndex < (LockSpinCount + LockSleep0Count))
{
RuntimeThread.Sleep(0); // Give up my quantum.
}
else
{
RuntimeThread.Sleep(1); // Give up my quantum.
}
if (_myLock == 0 && TryEnterMyLock())
{
return;
}
}
}
private void ExitMyLock()
{
Debug.Assert(_myLock != 0, "Exiting spin lock that is not held");
Volatile.Write(ref _myLock, 0);
}
#if DEBUG
private bool MyLockHeld { get { return _myLock != 0; } }
#endif
private static void SpinWait(int spinCount)
{
//Exponential back-off
if ((spinCount < 5) && (ProcessorCount > 1))
{
RuntimeThread.SpinWait(LockSpinCycles * spinCount);
}
else
{
RuntimeThread.Sleep(0);
}
// Don't want to Sleep(1) in this spin wait:
// - Don't want to spin for that long, since a proper wait will follow when the spin wait fails. The artifical
// delay introduced by Sleep(1) will in some cases be much longer than desired.
// - Sleep(1) would put the thread into a wait state, and a proper wait will follow when the spin wait fails
// anyway, so it's preferable to put the thread into the proper wait state
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (disposing && !_fDisposed)
{
if (WaitingReadCount > 0 || WaitingUpgradeCount > 0 || WaitingWriteCount > 0)
throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld)
throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
if (_writeEvent != null)
{
_writeEvent.Dispose();
_writeEvent = null;
}
if (_readEvent != null)
{
_readEvent.Dispose();
_readEvent = null;
}
if (_upgradeEvent != null)
{
_upgradeEvent.Dispose();
_upgradeEvent = null;
}
if (_waitUpgradeEvent != null)
{
_waitUpgradeEvent.Dispose();
_waitUpgradeEvent = null;
}
_fDisposed = true;
}
}
public bool IsReadLockHeld
{
get
{
if (RecursiveReadCount > 0)
return true;
else
return false;
}
}
public bool IsUpgradeableReadLockHeld
{
get
{
if (RecursiveUpgradeCount > 0)
return true;
else
return false;
}
}
public bool IsWriteLockHeld
{
get
{
if (RecursiveWriteCount > 0)
return true;
else
return false;
}
}
public LockRecursionPolicy RecursionPolicy
{
get
{
if (_fIsReentrant)
{
return LockRecursionPolicy.SupportsRecursion;
}
else
{
return LockRecursionPolicy.NoRecursion;
}
}
}
public int CurrentReadCount
{
get
{
int numreaders = (int)GetNumReaders();
if (_upgradeLockOwnerId != -1)
return numreaders - 1;
else
return numreaders;
}
}
public int RecursiveReadCount
{
get
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if (lrwc != null)
count = lrwc.readercount;
return count;
}
}
public int RecursiveUpgradeCount
{
get
{
if (_fIsReentrant)
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if (lrwc != null)
count = lrwc.upgradecount;
return count;
}
else
{
if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
return 1;
else
return 0;
}
}
}
public int RecursiveWriteCount
{
get
{
if (_fIsReentrant)
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if (lrwc != null)
count = lrwc.writercount;
return count;
}
else
{
if (Environment.CurrentManagedThreadId == _writeLockOwnerId)
return 1;
else
return 0;
}
}
}
public int WaitingReadCount
{
get
{
return (int)_numReadWaiters;
}
}
public int WaitingUpgradeCount
{
get
{
return (int)_numUpgradeWaiters;
}
}
public int WaitingWriteCount
{
get
{
return (int)_numWriteWaiters;
}
}
[Flags]
private enum WaiterStates : byte
{
None = 0x0,
// Used for quick check when there are no waiters
NoWaiters = 0x1,
// Used to avoid signaling more than one waiter to wake up when only one can make progress, see WaitOnEvent
WriteWaiterSignaled = 0x2,
UpgradeableReadWaiterSignaled = 0x4
// Write upgrade waiters are excluded because there can only be one at any given time
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// 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.Reflection;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Tests.Integration.Migrations;
using Moq;
using NUnit.Framework;
using NUnit.Should;
using System.Linq;
namespace FluentMigrator.Tests.Unit
{
[TestFixture]
public class MigrationRunnerTests
{
private MigrationRunner _runner;
private Mock<IAnnouncer> _announcer;
private Mock<IStopWatch> _stopWatch;
private Mock<IMigrationProcessor> _processorMock;
private Mock<IMigrationInformationLoader> _migrationLoaderMock;
private Mock<IProfileLoader> _profileLoaderMock;
private Mock<IRunnerContext> _runnerContextMock;
private SortedList<long, IMigrationInfo> _migrationList;
private TestVersionLoader _fakeVersionLoader;
private int _applicationContext;
[SetUp]
public void SetUp()
{
_applicationContext = new Random().Next();
_migrationList = new SortedList<long, IMigrationInfo>();
_runnerContextMock = new Mock<IRunnerContext>(MockBehavior.Loose);
_processorMock = new Mock<IMigrationProcessor>(MockBehavior.Loose);
_migrationLoaderMock = new Mock<IMigrationInformationLoader>(MockBehavior.Loose);
_profileLoaderMock = new Mock<IProfileLoader>(MockBehavior.Loose);
_announcer = new Mock<IAnnouncer>();
_stopWatch = new Mock<IStopWatch>();
var options = new ProcessorOptions
{
PreviewOnly = false
};
_processorMock.SetupGet(x => x.Options).Returns(options);
_runnerContextMock.SetupGet(x => x.Namespace).Returns("FluentMigrator.Tests.Integration.Migrations");
_runnerContextMock.SetupGet(x => x.Announcer).Returns(_announcer.Object);
_runnerContextMock.SetupGet(x => x.StopWatch).Returns(_stopWatch.Object);
_runnerContextMock.SetupGet(x => x.Target).Returns(Assembly.GetExecutingAssembly().ToString());
_runnerContextMock.SetupGet(x => x.Connection).Returns(IntegrationTestOptions.SqlServer2008.ConnectionString);
_runnerContextMock.SetupGet(x => x.Database).Returns("sqlserver");
_runnerContextMock.SetupGet(x => x.ApplicationContext).Returns(_applicationContext);
_migrationLoaderMock.Setup(x => x.LoadMigrations()).Returns(()=> _migrationList);
_runner = new MigrationRunner(Assembly.GetAssembly(typeof(MigrationRunnerTests)), _runnerContextMock.Object, _processorMock.Object)
{
MigrationLoader = _migrationLoaderMock.Object,
ProfileLoader = _profileLoaderMock.Object,
};
_fakeVersionLoader = new TestVersionLoader(_runner, _runner.VersionLoader.VersionTableMetaData);
_runner.VersionLoader = _fakeVersionLoader;
_processorMock.Setup(x => x.SchemaExists(It.Is<string>(s => s == _runner.VersionLoader.VersionTableMetaData.SchemaName)))
.Returns(true);
_processorMock.Setup(x => x.TableExists(It.Is<string>(s => s == _runner.VersionLoader.VersionTableMetaData.SchemaName),
It.Is<string>(t => t == _runner.VersionLoader.VersionTableMetaData.TableName)))
.Returns(true);
}
private void LoadVersionData(params long[] fakeVersions)
{
_fakeVersionLoader.Versions.Clear();
_migrationList.Clear();
foreach (var version in fakeVersions)
{
_fakeVersionLoader.Versions.Add(version);
_migrationList.Add(version,new MigrationInfo(version, TransactionBehavior.Default, new TestMigration()));
}
_fakeVersionLoader.LoadVersionInfo();
}
/// <summary>Unit test which ensures that the application context is correctly propagated down to each migration class.</summary>
[Test(Description = "Ensure that the application context is correctly propagated down to each migration class.")]
public void CanPassApplicationContext()
{
IMigration migration = new TestEmptyMigration();
_runner.Up(migration);
Assert.AreEqual(_applicationContext, _runnerContextMock.Object.ApplicationContext, "The runner context does not have the expected application context.");
Assert.AreEqual(_applicationContext, _runner.ApplicationContext, "The MigrationRunner does not have the expected application context.");
Assert.AreEqual(_applicationContext, migration.ApplicationContext, "The migration does not have the expected application context.");
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceUp()
{
_announcer.Setup(x => x.Heading(It.IsRegex(containsAll("Test", "migrating"))));
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceUpFinish()
{
_announcer.Setup(x => x.Say(It.IsRegex(containsAll("Test", "migrated"))));
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceDown()
{
_announcer.Setup(x => x.Heading(It.IsRegex(containsAll("Test", "reverting"))));
_runner.Down(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceDownFinish()
{
_announcer.Setup(x => x.Say(It.IsRegex(containsAll("Test", "reverted"))));
_runner.Down(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceUpElapsedTime()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts)));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceDownElapsedTime()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts)));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
_runner.Down(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanReportExceptions()
{
_processorMock.Setup(x => x.Process(It.IsAny<CreateTableExpression>())).Throws(new Exception("Oops"));
_announcer.Setup(x => x.Error(It.IsRegex(containsAll("Oops"))));
try
{
_runner.Up(new TestMigration());
}
catch (Exception)
{
}
_announcer.VerifyAll();
}
[Test]
public void CanSayExpression()
{
_announcer.Setup(x => x.Say(It.IsRegex(containsAll("CreateTable"))));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(new TimeSpan(0, 0, 0, 1, 3));
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanTimeExpression()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts)));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
private string containsAll(params string[] words)
{
return ".*?" + string.Join(".*?", words) + ".*?";
}
[Test]
public void LoadsCorrectCallingAssembly()
{
_runner.MigrationAssembly.ShouldBe(Assembly.GetAssembly(typeof(MigrationRunnerTests)));
}
[Test]
public void RollbackOnlyOneStepsOfTwoShouldNotDeleteVersionInfoTable()
{
long fakeMigrationVersion = 2009010101;
long fakeMigrationVersion2 = 2009010102;
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
LoadVersionData(fakeMigrationVersion, fakeMigrationVersion2);
_runner.VersionLoader.LoadVersionInfo();
_runner.Rollback(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void RollbackLastVersionShouldDeleteVersionInfoTable()
{
long fakeMigrationVersion = 2009010101;
LoadVersionData(fakeMigrationVersion);
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.Rollback(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeTrue();
}
[Test]
public void RollbackToVersionZeroShouldDeleteVersionInfoTable()
{
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.RollbackToVersion(0);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeTrue();
}
[Test]
public void RollbackToVersionZeroShouldNotCreateVersionInfoTableAfterRemoval()
{
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.RollbackToVersion(0);
//Should only be called once in setup
_processorMock.Verify(
pm => pm.Process(It.Is<CreateTableExpression>(
dte => dte.TableName == versionInfoTableName)
),
Times.Once()
);
}
[Test]
public void RollbackToVersionShouldShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
LoadVersionData(fakeMigration1,fakeMigration3);
_fakeVersionLoader.Versions.Add(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
_runner.RollbackToVersion(2011010101);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
}
[Test]
public void RollbackToVersionZeroShouldShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
LoadVersionData(fakeMigration1, fakeMigration2, fakeMigration3);
_migrationList.Remove(fakeMigration1);
_migrationList.Remove(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
_runner.RollbackToVersion(0);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
}
[Test]
public void RollbackShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
LoadVersionData(fakeMigration1, fakeMigration3);
_fakeVersionLoader.Versions.Add(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
_runner.Rollback(2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void RollbackToVersionShouldLoadVersionInfoIfVersionGreaterThanZero()
{
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.RollbackToVersion(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
//Once in setup
_processorMock.Verify(
pm => pm.Process(It.Is<CreateTableExpression>(
dte => dte.TableName == versionInfoTableName)
),
Times.Exactly(1)
);
//After setup is done, fake version loader owns the proccess
_fakeVersionLoader.DidLoadVersionInfoGetCalled.ShouldBe(true);
}
[Test]
public void ValidateVersionOrderingShouldReturnNothingIfNoUnappliedMigrations()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
LoadVersionData(version1, version2);
_migrationList.Clear();
_migrationList.Add(version1,new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
Assert.DoesNotThrow(() => _runner.ValidateVersionOrder());
_announcer.Verify(a => a.Say("Version ordering valid."));
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void ValidateVersionOrderingShouldReturnNothingIfUnappliedMigrationVersionIsGreaterThanLatestAppliedMigration()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
LoadVersionData(version1);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
Assert.DoesNotThrow(() => _runner.ValidateVersionOrder());
_announcer.Verify(a => a.Say("Version ordering valid."));
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void ValidateVersionOrderingShouldThrowExceptionIfUnappliedMigrationVersionIsLessThanGreatestAppliedMigrationVersion()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
const long version3 = 2011010103;
const long version4 = 2011010104;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
var mockMigration3 = new Mock<IMigration>();
var mockMigration4 = new Mock<IMigration>();
LoadVersionData(version1, version4);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
_migrationList.Add(version3, new MigrationInfo(version3, TransactionBehavior.Default, mockMigration3.Object));
_migrationList.Add(version4, new MigrationInfo(version4, TransactionBehavior.Default, mockMigration4.Object));
var exception = Assert.Throws<VersionOrderInvalidException>(() => _runner.ValidateVersionOrder());
exception.InvalidMigrations.Count().ShouldBe(2);
exception.InvalidMigrations.Any(p => p.Key == version2);
exception.InvalidMigrations.Any(p => p.Key == version3);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void CanListVersions()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
LoadVersionData(version1, version2);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
_runner.ListMigrations();
_announcer.Verify(a => a.Say("2011010101: IMigrationProxy"));
_announcer.Verify(a => a.Emphasize("2011010102: IMigrationProxy (current)"));
}
[Test]
public void IfMigrationHasAnInvalidExpressionDuringUpActionShouldThrowAnExceptionAndAnnounceTheError()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression {TableName = "Test"};
invalidMigration.Setup(m => m.GetUpExpressions(It.IsAny<IMigrationContext>())).Callback((IMigrationContext mc) => mc.Expressions.Add(invalidExpression));
Assert.Throws<InvalidMigrationException>(() => _runner.Up(invalidMigration.Object));
_announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains("UpdateDataExpression: Update statement is missing a condition. Specify one by calling .Where() or target all rows by calling .AllRows()."))));
}
[Test]
public void IfMigrationHasAnInvalidExpressionDuringDownActionShouldThrowAnExceptionAndAnnounceTheError()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression { TableName = "Test" };
invalidMigration.Setup(m => m.GetDownExpressions(It.IsAny<IMigrationContext>())).Callback((IMigrationContext mc) => mc.Expressions.Add(invalidExpression));
Assert.Throws<InvalidMigrationException>(() => _runner.Down(invalidMigration.Object));
_announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains("UpdateDataExpression: Update statement is missing a condition. Specify one by calling .Where() or target all rows by calling .AllRows()."))));
}
[Test]
public void IfMigrationHasTwoInvalidExpressionsShouldAnnounceBothErrors()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression { TableName = "Test" };
var secondInvalidExpression = new CreateColumnExpression();
invalidMigration.Setup(m => m.GetUpExpressions(It.IsAny<IMigrationContext>()))
.Callback((IMigrationContext mc) => { mc.Expressions.Add(invalidExpression); mc.Expressions.Add(secondInvalidExpression); });
Assert.Throws<InvalidMigrationException>(() => _runner.Up(invalidMigration.Object));
_announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains("UpdateDataExpression: Update statement is missing a condition. Specify one by calling .Where() or target all rows by calling .AllRows()."))));
_announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains("CreateColumnExpression: The table's name cannot be null or an empty string. The column's name cannot be null or an empty string. The column does not have a type defined."))));
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using Avalonia.Input.Raw;
using Avalonia.Interactivity;
using Avalonia.Platform;
using Avalonia.VisualTree;
namespace Avalonia.Input
{
/// <summary>
/// Represents a mouse device.
/// </summary>
public class MouseDevice : IMouseDevice
{
private int _clickCount;
private Rect _lastClickRect;
private uint _lastClickTime;
private IInputElement _captured;
private IDisposable _capturedSubscription;
/// <summary>
/// Gets the control that is currently capturing by the mouse, if any.
/// </summary>
/// <remarks>
/// When an element captures the mouse, it recieves mouse input whether the cursor is
/// within the control's bounds or not. To set the mouse capture, call the
/// <see cref="Capture"/> method.
/// </remarks>
public IInputElement Captured
{
get => _captured;
protected set
{
_capturedSubscription?.Dispose();
_capturedSubscription = null;
if (value != null)
{
_capturedSubscription = Observable.FromEventPattern<VisualTreeAttachmentEventArgs>(
x => value.DetachedFromVisualTree += x,
x => value.DetachedFromVisualTree -= x)
.Take(1)
.Subscribe(_ => Captured = null);
}
_captured = value;
}
}
/// <summary>
/// Gets the mouse position, in screen coordinates.
/// </summary>
public Point Position
{
get;
protected set;
}
/// <summary>
/// Captures mouse input to the specified control.
/// </summary>
/// <param name="control">The control.</param>
/// <remarks>
/// When an element captures the mouse, it recieves mouse input whether the cursor is
/// within the control's bounds or not. The current mouse capture control is exposed
/// by the <see cref="Captured"/> property.
/// </remarks>
public virtual void Capture(IInputElement control)
{
// TODO: Check visibility and enabled state before setting capture.
Captured = control;
}
/// <summary>
/// Gets the mouse position relative to a control.
/// </summary>
/// <param name="relativeTo">The control.</param>
/// <returns>The mouse position in the control's coordinates.</returns>
public Point GetPosition(IVisual relativeTo)
{
Contract.Requires<ArgumentNullException>(relativeTo != null);
Point p = default(Point);
IVisual v = relativeTo;
IVisual root = null;
while (v != null)
{
p += v.Bounds.Position;
root = v;
v = v.VisualParent;
}
return root.PointToClient(Position) - p;
}
public void ProcessRawEvent(RawInputEventArgs e)
{
if (!e.Handled && e is RawMouseEventArgs margs)
ProcessRawEvent(margs);
}
private void ProcessRawEvent(RawMouseEventArgs e)
{
Contract.Requires<ArgumentNullException>(e != null);
var mouse = (IMouseDevice)e.Device;
Position = e.Root.PointToScreen(e.Position);
switch (e.Type)
{
case RawMouseEventType.LeaveWindow:
LeaveWindow(mouse, e.Root);
break;
case RawMouseEventType.LeftButtonDown:
case RawMouseEventType.RightButtonDown:
case RawMouseEventType.MiddleButtonDown:
e.Handled = MouseDown(mouse, e.Timestamp, e.Root, e.Position,
e.Type == RawMouseEventType.LeftButtonDown
? MouseButton.Left
: e.Type == RawMouseEventType.RightButtonDown ? MouseButton.Right : MouseButton.Middle,
e.InputModifiers);
break;
case RawMouseEventType.LeftButtonUp:
case RawMouseEventType.RightButtonUp:
case RawMouseEventType.MiddleButtonUp:
e.Handled = MouseUp(mouse, e.Root, e.Position,
e.Type == RawMouseEventType.LeftButtonUp
? MouseButton.Left
: e.Type == RawMouseEventType.RightButtonUp ? MouseButton.Right : MouseButton.Middle,
e.InputModifiers);
break;
case RawMouseEventType.Move:
e.Handled = MouseMove(mouse, e.Root, e.Position, e.InputModifiers);
break;
case RawMouseEventType.Wheel:
e.Handled = MouseWheel(mouse, e.Root, e.Position, ((RawMouseWheelEventArgs)e).Delta, e.InputModifiers);
break;
}
}
private void LeaveWindow(IMouseDevice device, IInputRoot root)
{
Contract.Requires<ArgumentNullException>(device != null);
Contract.Requires<ArgumentNullException>(root != null);
ClearPointerOver(this, root);
}
private bool MouseDown(IMouseDevice device, uint timestamp, IInputElement root, Point p, MouseButton button, InputModifiers inputModifiers)
{
Contract.Requires<ArgumentNullException>(device != null);
Contract.Requires<ArgumentNullException>(root != null);
var hit = HitTest(root, p);
if (hit != null)
{
IInteractive source = GetSource(hit);
if (source != null)
{
var settings = AvaloniaLocator.Current.GetService<IPlatformSettings>();
var doubleClickTime = settings.DoubleClickTime.TotalMilliseconds;
if (!_lastClickRect.Contains(p) || timestamp - _lastClickTime > doubleClickTime)
{
_clickCount = 0;
}
++_clickCount;
_lastClickTime = timestamp;
_lastClickRect = new Rect(p, new Size())
.Inflate(new Thickness(settings.DoubleClickSize.Width / 2, settings.DoubleClickSize.Height / 2));
var e = new PointerPressedEventArgs
{
Device = this,
RoutedEvent = InputElement.PointerPressedEvent,
Source = source,
ClickCount = _clickCount,
MouseButton = button,
InputModifiers = inputModifiers
};
source.RaiseEvent(e);
return e.Handled;
}
}
return false;
}
private bool MouseMove(IMouseDevice device, IInputRoot root, Point p, InputModifiers inputModifiers)
{
Contract.Requires<ArgumentNullException>(device != null);
Contract.Requires<ArgumentNullException>(root != null);
IInputElement source;
if (Captured == null)
{
source = SetPointerOver(this, root, p);
}
else
{
SetPointerOver(this, root, Captured);
source = Captured;
}
var e = new PointerEventArgs
{
Device = this,
RoutedEvent = InputElement.PointerMovedEvent,
Source = source,
InputModifiers = inputModifiers
};
source?.RaiseEvent(e);
return e.Handled;
}
private bool MouseUp(IMouseDevice device, IInputRoot root, Point p, MouseButton button, InputModifiers inputModifiers)
{
Contract.Requires<ArgumentNullException>(device != null);
Contract.Requires<ArgumentNullException>(root != null);
var hit = HitTest(root, p);
if (hit != null)
{
var source = GetSource(hit);
var e = new PointerReleasedEventArgs
{
Device = this,
RoutedEvent = InputElement.PointerReleasedEvent,
Source = source,
MouseButton = button,
InputModifiers = inputModifiers
};
source?.RaiseEvent(e);
return e.Handled;
}
return false;
}
private bool MouseWheel(IMouseDevice device, IInputRoot root, Point p, Vector delta, InputModifiers inputModifiers)
{
Contract.Requires<ArgumentNullException>(device != null);
Contract.Requires<ArgumentNullException>(root != null);
var hit = HitTest(root, p);
if (hit != null)
{
var source = GetSource(hit);
var e = new PointerWheelEventArgs
{
Device = this,
RoutedEvent = InputElement.PointerWheelChangedEvent,
Source = source,
Delta = delta,
InputModifiers = inputModifiers
};
source?.RaiseEvent(e);
return e.Handled;
}
return false;
}
private IInteractive GetSource(IVisual hit)
{
Contract.Requires<ArgumentNullException>(hit != null);
return Captured ??
(hit as IInteractive) ??
hit.GetSelfAndVisualAncestors().OfType<IInteractive>().FirstOrDefault();
}
private IInputElement HitTest(IInputElement root, Point p)
{
Contract.Requires<ArgumentNullException>(root != null);
return Captured ?? root.InputHitTest(p);
}
private void ClearPointerOver(IPointerDevice device, IInputRoot root)
{
Contract.Requires<ArgumentNullException>(device != null);
Contract.Requires<ArgumentNullException>(root != null);
var element = root.PointerOverElement;
var e = new PointerEventArgs
{
RoutedEvent = InputElement.PointerLeaveEvent,
Device = device,
};
while (element != null)
{
e.Source = element;
element.RaiseEvent(e);
element = (IInputElement)element.VisualParent;
}
root.PointerOverElement = null;
}
private IInputElement SetPointerOver(IPointerDevice device, IInputRoot root, Point p)
{
Contract.Requires<ArgumentNullException>(device != null);
Contract.Requires<ArgumentNullException>(root != null);
var element = root.InputHitTest(p);
if (element != root.PointerOverElement)
{
if (element != null)
{
SetPointerOver(device, root, element);
}
else
{
ClearPointerOver(device, root);
}
}
return element;
}
private void SetPointerOver(IPointerDevice device, IInputRoot root, IInputElement element)
{
Contract.Requires<ArgumentNullException>(device != null);
Contract.Requires<ArgumentNullException>(root != null);
Contract.Requires<ArgumentNullException>(element != null);
IInputElement branch = null;
var e = new PointerEventArgs
{
RoutedEvent = InputElement.PointerEnterEvent,
Device = device,
};
var el = element;
while (el != null)
{
if (el.IsPointerOver)
{
branch = el;
break;
}
e.Source = el;
el.RaiseEvent(e);
el = (IInputElement)el.VisualParent;
}
el = root.PointerOverElement;
e.RoutedEvent = InputElement.PointerLeaveEvent;
while (el != null && el != branch)
{
e.Source = el;
el.RaiseEvent(e);
el = (IInputElement)el.VisualParent;
}
root.PointerOverElement = element;
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Xml.Linq;
using System.Windows.Forms;
namespace CCVersions
{
#region HGVersionSpec
class HGVersionSpec : ExeVersionSpec
{
public HGVersionSpec(string value)
: base(value)
{ }
public HGVersionSpec(int revNum)
: base(revNum)
{ }
}
#endregion HGVersionSpec
#region HGRepository
class HGRepository : ExeRepository
{
protected override string ExeName { get { return "hg.exe"; } }
public HGRepository(string workingDirectory)
: base(workingDirectory)
{ }
public bool Clone(string source, string branch = null, int? timeoutMilliseconds = null)
{
var arguments = "clone";
if (branch != null)
{
arguments += " -b \"" + branch + "\"";
Contract.Assert(!String.IsNullOrWhiteSpace(arguments));
}
var timeout = timeoutMilliseconds ?? longTimeout;
var res = this.Invoke(arguments, timeout);
return res.ExitCode == 0;
}
public HGVersionSpec Identify(string revision = null)
{
Contract.Ensures(Contract.Result<HGVersionSpec>() != null);
var arguments = "identify -n";
if (revision != null)
{
arguments += " -r \"" + revision + "\"";
Contract.Assert(!String.IsNullOrWhiteSpace(arguments));
}
var res = this.Invoke(arguments, shortTimeout);
if (res.ExitCode != 0)
{
throw new ExeInvokeException(String.Format("ExitCode = {0}", res.ExitCode));
}
return new HGVersionSpec(res.StdOut);
}
public IEnumerable<HGVersionSpec> Log(HGVersionSpec first, HGVersionSpec last)
{
Contract.Requires(first != null);
Contract.Requires(last != null);
var arguments = "log --template \"{rev}\\n\"";
arguments += " -r " + first.Id + ":" + last.Id;
Contract.Assume(!String.IsNullOrWhiteSpace(arguments));
var res = this.Invoke(arguments, mediumTimeout);
if (res.ExitCode != 0)
{
return null;
}
return res.StdOut.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Select(s => new HGVersionSpec(s));
}
public bool Pull(int? timeoutMilliseconds = null)
{
var arguments = "pull";
var timeout = timeoutMilliseconds ?? longTimeout;
var res = this.Invoke(arguments, timeout);
return res.ExitCode == 0;
}
public bool Update(HGVersionSpec version)
{
Contract.Requires(version != null);
var arguments = "update -C";
arguments += " -r " + version.Id;
Contract.Assume(!String.IsNullOrWhiteSpace(arguments));
var res = this.Invoke(arguments, longTimeout);
return res.ExitCode == 0;
}
protected override IEnumerable<Tuple<string, string>> EnvironmentVariables
{
get { yield break; }
}
}
#endregion
class HGSourceManager : ISourceManager
{
readonly string branch;
readonly string id;
readonly string uri;
string workingDirectory;
HGRepository repository;
bool needClone = false;
bool needPull = false;
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(this.branch != null);
Contract.Invariant(this.id != null);
Contract.Invariant(this.uri != null);
Contract.Invariant(this.repository != null || this.workingDirectory == null); // WorkindDirectory != null implies repository != null
}
public static HGSourceManager Factory(XElement xConfig)
{
Contract.Requires(xConfig != null);
return new HGSourceManager(xConfig);
}
private HGSourceManager(XElement xConfig)
{
Contract.Requires(xConfig != null);
var xProtocol = xConfig.Element("protocol");
var protocol = xProtocol == null ? "http" : xProtocol.Value;
var xServer = xConfig.Element("server");
var server = xServer == null ? "localhost" : xServer.Value;
var xPort = xConfig.Element("port");
var port = xPort == null ? null : xPort.Value;
var xPath = xConfig.Element("path");
var path = xPath == null ? "" : xPath.Value;
var xBranch = xConfig.Element("branch");
this.branch = xBranch == null ? "default" : xBranch.Value;
this.uri = String.Format("{0}://{1}{2}/{3}", protocol, server, port == null ? "" : ":" + port, path);
this.id = IDBuilder.FromUri("HG_", this.uri);
}
public string Id { get { return this.id; } }
private bool CheckRepository()
{
if (this.needClone)
{
var res = MessageBox.Show("Will now clone the whole repository. This operation can take a long time. Continue?", "CCVersions", MessageBoxButtons.YesNo);
if (res == DialogResult.Yes)
{
this.repository.Clone(this.uri);
this.needClone = false;
this.needPull = false;
}
}
if (this.needPull)
{
try
{
var res = MessageBox.Show("Check for new versions?", "CCVersions", MessageBoxButtons.YesNo);
if (res == DialogResult.Yes)
{
this.repository.Pull();
}
this.needPull = false;
}
catch { }
}
return !this.needClone && !this.needPull;
}
public string WorkingDirectory
{
get { return this.workingDirectory; }
set
{
Contract.Ensures(this.WorkingDirectory != null);
this.workingDirectory = value;
this.repository = new HGRepository(this.WorkingDirectory);
try
{
this.repository.Identify();
this.needPull = true;
}
catch (ExeRepository.ExeInvokeException)
{
this.needClone = true;
this.CheckRepository();
}
}
}
public ISourceManagerVersionSpec ParseVersionSpec(string value)
{
if (this.repository != null && !String.IsNullOrWhiteSpace(value))
{
return this.repository.Identify(value);
}
else
{
return new HGVersionSpec(value);
}
}
[Pure]
public IEnumerable<HGVersionSpec> VersionRange(HGVersionSpec First, HGVersionSpec Last)
{
Contract.Requires(First != null);
Contract.Requires(Last != null);
Contract.Ensures(Contract.Result<IEnumerable<HGVersionSpec>>() != null);
if (!this.CheckRepository())
{
return new HGVersionSpec[0];
}
var first = First.IsNull ? this.repository.Identify("null") : First;
var last = Last.IsNull ? this.repository.Identify("tip") : Last;
var log = repository.Log(first, last);
return log ?? new HGVersionSpec[0];
}
public IEnumerable<ISourceManagerVersionSpec> VersionRange(ISourceManagerVersionSpec First, ISourceManagerVersionSpec Last, string filter = null)
{
Contract.Ensures(Contract.Result<IEnumerable<ISourceManagerVersionSpec>>() != null);
return VersionRange((HGVersionSpec)First, (HGVersionSpec)Last);
}
public bool GetSources(HGVersionSpec Version)
{
Contract.Requires(Version != null);
Contract.Requires(this.WorkingDirectory != null);
if (!this.CheckRepository())
{
return false;
}
repository.Update(Version);
return true;
}
public bool GetSources(ISourceManagerVersionSpec Version)
{
return GetSources((HGVersionSpec)Version);
}
public IEnumerable<ISourceManagerVersionSpec> VersionRange(int countPrior, ISourceManagerVersionSpec Last)
{
throw new NotImplementedException();
}
public IEnumerable<ISourceManagerVersionSpec> VersionRange(ISourceManagerVersionSpec first, int countAfter)
{
throw new NotImplementedException();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using ILCompiler.DependencyAnalysisFramework;
using Internal.Text;
using Internal.TypeSystem;
using Internal.Runtime;
using Internal.IL;
using Internal.NativeFormat;
namespace ILCompiler.DependencyAnalysis
{
public abstract partial class NodeFactory
{
private TargetDetails _target;
private CompilerTypeSystemContext _context;
private CompilationModuleGroup _compilationModuleGroup;
private VTableSliceProvider _vtableSliceProvider;
private DictionaryLayoutProvider _dictionaryLayoutProvider;
protected readonly ImportedNodeProvider _importedNodeProvider;
private bool _markingComplete;
public NodeFactory(
CompilerTypeSystemContext context,
CompilationModuleGroup compilationModuleGroup,
MetadataManager metadataManager,
InteropStubManager interoptStubManager,
NameMangler nameMangler,
LazyGenericsPolicy lazyGenericsPolicy,
VTableSliceProvider vtableSliceProvider,
DictionaryLayoutProvider dictionaryLayoutProvider,
ImportedNodeProvider importedNodeProvider)
{
_target = context.Target;
_context = context;
_compilationModuleGroup = compilationModuleGroup;
_vtableSliceProvider = vtableSliceProvider;
_dictionaryLayoutProvider = dictionaryLayoutProvider;
NameMangler = nameMangler;
InteropStubManager = interoptStubManager;
CreateNodeCaches();
MetadataManager = metadataManager;
LazyGenericsPolicy = lazyGenericsPolicy;
_importedNodeProvider = importedNodeProvider;
}
public void SetMarkingComplete()
{
_markingComplete = true;
}
public bool MarkingComplete => _markingComplete;
public TargetDetails Target
{
get
{
return _target;
}
}
public LazyGenericsPolicy LazyGenericsPolicy { get; }
public CompilationModuleGroup CompilationModuleGroup
{
get
{
return _compilationModuleGroup;
}
}
public CompilerTypeSystemContext TypeSystemContext
{
get
{
return _context;
}
}
public MetadataManager MetadataManager
{
get;
}
public NameMangler NameMangler
{
get;
}
public InteropStubManager InteropStubManager
{
get;
}
// Temporary workaround that is used to disable certain features from lighting up
// in CppCodegen because they're not fully implemented yet.
public virtual bool IsCppCodegenTemporaryWorkaround
{
get { return false; }
}
/// <summary>
/// Return true if the type is not permitted by the rules of the runtime to have an EEType.
/// The implementation here is not intended to be complete, but represents many conditions
/// which make a type ineligible to be an EEType. (This function is intended for use in assertions only)
/// </summary>
private static bool TypeCannotHaveEEType(TypeDesc type)
{
if (type.GetTypeDefinition() is INonEmittableType)
return true;
if (type.IsRuntimeDeterminedSubtype)
return true;
if (type.IsSignatureVariable)
return true;
if (type.IsGenericParameter)
return true;
return false;
}
protected struct NodeCache<TKey, TValue>
{
private Func<TKey, TValue> _creator;
private ConcurrentDictionary<TKey, TValue> _cache;
public NodeCache(Func<TKey, TValue> creator, IEqualityComparer<TKey> comparer)
{
_creator = creator;
_cache = new ConcurrentDictionary<TKey, TValue>(comparer);
}
public NodeCache(Func<TKey, TValue> creator)
{
_creator = creator;
_cache = new ConcurrentDictionary<TKey, TValue>();
}
public TValue GetOrAdd(TKey key)
{
return _cache.GetOrAdd(key, _creator);
}
}
private void CreateNodeCaches()
{
_typeSymbols = new NodeCache<TypeDesc, IEETypeNode>((TypeDesc type) =>
{
Debug.Assert(!_compilationModuleGroup.ShouldReferenceThroughImportTable(type));
if (_compilationModuleGroup.ContainsType(type))
{
if (type.IsGenericDefinition)
{
return new GenericDefinitionEETypeNode(this, type);
}
else if (type.IsCanonicalDefinitionType(CanonicalFormKind.Any))
{
return new CanonicalDefinitionEETypeNode(this, type);
}
else if (type.IsCanonicalSubtype(CanonicalFormKind.Any))
{
return new NecessaryCanonicalEETypeNode(this, type);
}
else
{
return new EETypeNode(this, type);
}
}
else
{
return new ExternEETypeSymbolNode(this, type);
}
});
_constructedTypeSymbols = new NodeCache<TypeDesc, IEETypeNode>((TypeDesc type) =>
{
// Canonical definition types are *not* constructed types (call NecessaryTypeSymbol to get them)
Debug.Assert(!type.IsCanonicalDefinitionType(CanonicalFormKind.Any));
Debug.Assert(!_compilationModuleGroup.ShouldReferenceThroughImportTable(type));
if (_compilationModuleGroup.ContainsType(type))
{
if (type.IsCanonicalSubtype(CanonicalFormKind.Any))
{
return new CanonicalEETypeNode(this, type);
}
else
{
return new ConstructedEETypeNode(this, type);
}
}
else
{
return new ExternEETypeSymbolNode(this, type);
}
});
_clonedTypeSymbols = new NodeCache<TypeDesc, IEETypeNode>((TypeDesc type) =>
{
// Only types that reside in other binaries should be cloned
Debug.Assert(_compilationModuleGroup.ShouldReferenceThroughImportTable(type));
return new ClonedConstructedEETypeNode(this, type);
});
_importedTypeSymbols = new NodeCache<TypeDesc, IEETypeNode>((TypeDesc type) =>
{
Debug.Assert(_compilationModuleGroup.ShouldReferenceThroughImportTable(type));
return _importedNodeProvider.ImportedEETypeNode(this, type);
});
_nonGCStatics = new NodeCache<MetadataType, ISortableSymbolNode>((MetadataType type) =>
{
if (_compilationModuleGroup.ContainsType(type) && !_compilationModuleGroup.ShouldReferenceThroughImportTable(type))
{
return new NonGCStaticsNode(type, this);
}
else
{
return _importedNodeProvider.ImportedNonGCStaticNode(this, type);
}
});
_GCStatics = new NodeCache<MetadataType, ISortableSymbolNode>((MetadataType type) =>
{
if (_compilationModuleGroup.ContainsType(type) && !_compilationModuleGroup.ShouldReferenceThroughImportTable(type))
{
return new GCStaticsNode(type);
}
else
{
return _importedNodeProvider.ImportedGCStaticNode(this, type);
}
});
_GCStaticsPreInitDataNodes = new NodeCache<MetadataType, GCStaticsPreInitDataNode>((MetadataType type) =>
{
ISymbolNode gcStaticsNode = TypeGCStaticsSymbol(type);
Debug.Assert(gcStaticsNode is GCStaticsNode);
return ((GCStaticsNode)gcStaticsNode).NewPreInitDataNode();
});
_GCStaticIndirectionNodes = new NodeCache<MetadataType, EmbeddedObjectNode>((MetadataType type) =>
{
ISymbolNode gcStaticsNode = TypeGCStaticsSymbol(type);
Debug.Assert(gcStaticsNode is GCStaticsNode);
return GCStaticsRegion.NewNode((GCStaticsNode)gcStaticsNode);
});
_threadStatics = new NodeCache<MetadataType, ISymbolDefinitionNode>(CreateThreadStaticsNode);
_typeThreadStaticIndices = new NodeCache<MetadataType, TypeThreadStaticIndexNode>(type =>
{
return new TypeThreadStaticIndexNode(type);
});
_GCStaticEETypes = new NodeCache<GCPointerMap, GCStaticEETypeNode>((GCPointerMap gcMap) =>
{
return new GCStaticEETypeNode(Target, gcMap);
});
_readOnlyDataBlobs = new NodeCache<ReadOnlyDataBlobKey, BlobNode>(key =>
{
return new BlobNode(key.Name, ObjectNodeSection.ReadOnlyDataSection, key.Data, key.Alignment);
});
_externSymbols = new NodeCache<string, ExternSymbolNode>((string name) =>
{
return new ExternSymbolNode(name);
});
_pInvokeModuleFixups = new NodeCache<string, PInvokeModuleFixupNode>((string name) =>
{
return new PInvokeModuleFixupNode(name);
});
_pInvokeMethodFixups = new NodeCache<Tuple<string, string, PInvokeFlags>, PInvokeMethodFixupNode>((Tuple<string, string, PInvokeFlags> key) =>
{
return new PInvokeMethodFixupNode(key.Item1, key.Item2, key.Item3);
});
_methodEntrypoints = new NodeCache<MethodDesc, IMethodNode>(CreateMethodEntrypointNode);
_unboxingStubs = new NodeCache<MethodDesc, IMethodNode>(CreateUnboxingStubNode);
_methodAssociatedData = new NodeCache<IMethodNode, MethodAssociatedDataNode>(methodNode =>
{
return new MethodAssociatedDataNode(methodNode);
});
_fatFunctionPointers = new NodeCache<MethodKey, FatFunctionPointerNode>(method =>
{
return new FatFunctionPointerNode(method.Method, method.IsUnboxingStub);
});
_gvmDependenciesNode = new NodeCache<MethodDesc, GVMDependenciesNode>(method =>
{
return new GVMDependenciesNode(method);
});
_gvmTableEntries = new NodeCache<TypeDesc, TypeGVMEntriesNode>(type =>
{
return new TypeGVMEntriesNode(type);
});
_reflectableMethods = new NodeCache<MethodDesc, ReflectableMethodNode>(method =>
{
return new ReflectableMethodNode(method);
});
_shadowConcreteMethods = new NodeCache<MethodKey, IMethodNode>(methodKey =>
{
MethodDesc canonMethod = methodKey.Method.GetCanonMethodTarget(CanonicalFormKind.Specific);
if (methodKey.IsUnboxingStub)
{
return new ShadowConcreteUnboxingThunkNode(methodKey.Method, MethodEntrypoint(canonMethod, true));
}
else
{
return new ShadowConcreteMethodNode(methodKey.Method, MethodEntrypoint(canonMethod));
}
});
_runtimeDeterminedMethods = new NodeCache<MethodDesc, IMethodNode>(method =>
{
return new RuntimeDeterminedMethodNode(method,
MethodEntrypoint(method.GetCanonMethodTarget(CanonicalFormKind.Specific)));
});
_virtMethods = new NodeCache<MethodDesc, VirtualMethodUseNode>((MethodDesc method) =>
{
// We don't need to track virtual method uses for types that have a vtable with a known layout.
// It's a waste of CPU time and memory.
Debug.Assert(!VTable(method.OwningType).HasFixedSlots);
return new VirtualMethodUseNode(method);
});
_readyToRunHelpers = new NodeCache<ReadyToRunHelperKey, ISymbolNode>(CreateReadyToRunHelperNode);
_genericReadyToRunHelpersFromDict = new NodeCache<ReadyToRunGenericHelperKey, ISymbolNode>(data =>
{
return new ReadyToRunGenericLookupFromDictionaryNode(this, data.HelperId, data.Target, data.DictionaryOwner);
});
_genericReadyToRunHelpersFromType = new NodeCache<ReadyToRunGenericHelperKey, ISymbolNode>(data =>
{
return new ReadyToRunGenericLookupFromTypeNode(this, data.HelperId, data.Target, data.DictionaryOwner);
});
_indirectionNodes = new NodeCache<ISortableSymbolNode, ISymbolNode>(indirectedNode =>
{
return new IndirectionNode(Target, indirectedNode, 0);
});
_frozenStringNodes = new NodeCache<string, FrozenStringNode>((string data) =>
{
return new FrozenStringNode(data, Target);
});
_frozenArrayNodes = new NodeCache<PreInitFieldInfo, FrozenArrayNode>((PreInitFieldInfo fieldInfo) =>
{
return new FrozenArrayNode(fieldInfo);
});
_interfaceDispatchCells = new NodeCache<DispatchCellKey, InterfaceDispatchCellNode>(callSiteCell =>
{
return new InterfaceDispatchCellNode(callSiteCell.Target, callSiteCell.CallsiteId);
});
_interfaceDispatchMaps = new NodeCache<TypeDesc, InterfaceDispatchMapNode>((TypeDesc type) =>
{
return new InterfaceDispatchMapNode(this, type);
});
_sealedVtableNodes = new NodeCache<TypeDesc, SealedVTableNode>((TypeDesc type) =>
{
return new SealedVTableNode(type);
});
_runtimeMethodHandles = new NodeCache<MethodDesc, RuntimeMethodHandleNode>((MethodDesc method) =>
{
return new RuntimeMethodHandleNode(method);
});
_runtimeFieldHandles = new NodeCache<FieldDesc, RuntimeFieldHandleNode>((FieldDesc field) =>
{
return new RuntimeFieldHandleNode(field);
});
_interfaceDispatchMapIndirectionNodes = new NodeCache<TypeDesc, EmbeddedObjectNode>((TypeDesc type) =>
{
return DispatchMapTable.NewNodeWithSymbol(InterfaceDispatchMap(type));
});
_genericCompositions = new NodeCache<GenericCompositionDetails, GenericCompositionNode>((GenericCompositionDetails details) =>
{
return new GenericCompositionNode(details);
});
_eagerCctorIndirectionNodes = new NodeCache<MethodDesc, EmbeddedObjectNode>((MethodDesc method) =>
{
Debug.Assert(method.IsStaticConstructor);
Debug.Assert(TypeSystemContext.HasEagerStaticConstructor((MetadataType)method.OwningType));
return EagerCctorTable.NewNode(MethodEntrypoint(method));
});
_namedJumpStubNodes = new NodeCache<Tuple<string, ISymbolNode>, NamedJumpStubNode>((Tuple<string, ISymbolNode> id) =>
{
return new NamedJumpStubNode(id.Item1, id.Item2);
});
_vTableNodes = new NodeCache<TypeDesc, VTableSliceNode>((TypeDesc type ) =>
{
if (CompilationModuleGroup.ShouldProduceFullVTable(type))
return new EagerlyBuiltVTableSliceNode(type);
else
return _vtableSliceProvider.GetSlice(type);
});
_methodGenericDictionaries = new NodeCache<MethodDesc, ISortableSymbolNode>(method =>
{
if (CompilationModuleGroup.ContainsMethodDictionary(method))
{
return new MethodGenericDictionaryNode(method, this);
}
else
{
return _importedNodeProvider.ImportedMethodDictionaryNode(this, method);
}
});
_typeGenericDictionaries = new NodeCache<TypeDesc, ISortableSymbolNode>(type =>
{
if (CompilationModuleGroup.ContainsTypeDictionary(type))
{
Debug.Assert(!this.LazyGenericsPolicy.UsesLazyGenerics(type));
return new TypeGenericDictionaryNode(type, this);
}
else
{
return _importedNodeProvider.ImportedTypeDictionaryNode(this, type);
}
});
_typesWithMetadata = new NodeCache<MetadataType, TypeMetadataNode>(type =>
{
return new TypeMetadataNode(type);
});
_methodsWithMetadata = new NodeCache<MethodDesc, MethodMetadataNode>(method =>
{
return new MethodMetadataNode(method);
});
_fieldsWithMetadata = new NodeCache<FieldDesc, FieldMetadataNode>(field =>
{
return new FieldMetadataNode(field);
});
_modulesWithMetadata = new NodeCache<ModuleDesc, ModuleMetadataNode>(module =>
{
return new ModuleMetadataNode(module);
});
_genericDictionaryLayouts = new NodeCache<TypeSystemEntity, DictionaryLayoutNode>(_dictionaryLayoutProvider.GetLayout);
_stringAllocators = new NodeCache<MethodDesc, IMethodNode>(constructor =>
{
return new StringAllocatorMethodNode(constructor);
});
_defaultConstructorFromLazyNodes = new NodeCache<TypeDesc, DefaultConstructorFromLazyNode>(type =>
{
return new DefaultConstructorFromLazyNode(type);
});
NativeLayout = new NativeLayoutHelper(this);
WindowsDebugData = new WindowsDebugDataHelper(this);
}
protected abstract IMethodNode CreateMethodEntrypointNode(MethodDesc method);
protected abstract IMethodNode CreateUnboxingStubNode(MethodDesc method);
protected abstract ISymbolNode CreateReadyToRunHelperNode(ReadyToRunHelperKey helperCall);
protected virtual ISymbolDefinitionNode CreateThreadStaticsNode(MetadataType type)
{
return new ThreadStaticsNode(type, this);
}
private NodeCache<TypeDesc, IEETypeNode> _typeSymbols;
public IEETypeNode NecessaryTypeSymbol(TypeDesc type)
{
if (_compilationModuleGroup.ShouldReferenceThroughImportTable(type))
{
return ImportedEETypeSymbol(type);
}
if (_compilationModuleGroup.ShouldPromoteToFullType(type))
{
return ConstructedTypeSymbol(type);
}
Debug.Assert(!TypeCannotHaveEEType(type));
return _typeSymbols.GetOrAdd(type);
}
private NodeCache<TypeDesc, IEETypeNode> _constructedTypeSymbols;
public IEETypeNode ConstructedTypeSymbol(TypeDesc type)
{
if (_compilationModuleGroup.ShouldReferenceThroughImportTable(type))
{
return ImportedEETypeSymbol(type);
}
Debug.Assert(!TypeCannotHaveEEType(type));
return _constructedTypeSymbols.GetOrAdd(type);
}
private NodeCache<TypeDesc, IEETypeNode> _clonedTypeSymbols;
public IEETypeNode MaximallyConstructableType(TypeDesc type)
{
if (ConstructedEETypeNode.CreationAllowed(type))
return ConstructedTypeSymbol(type);
else
return NecessaryTypeSymbol(type);
}
public IEETypeNode ConstructedClonedTypeSymbol(TypeDesc type)
{
Debug.Assert(!TypeCannotHaveEEType(type));
return _clonedTypeSymbols.GetOrAdd(type);
}
private NodeCache<TypeDesc, IEETypeNode> _importedTypeSymbols;
private IEETypeNode ImportedEETypeSymbol(TypeDesc type)
{
Debug.Assert(_compilationModuleGroup.ShouldReferenceThroughImportTable(type));
return _importedTypeSymbols.GetOrAdd(type);
}
private NodeCache<MetadataType, ISortableSymbolNode> _nonGCStatics;
public ISortableSymbolNode TypeNonGCStaticsSymbol(MetadataType type)
{
Debug.Assert(!TypeCannotHaveEEType(type));
return _nonGCStatics.GetOrAdd(type);
}
private NodeCache<MetadataType, ISortableSymbolNode> _GCStatics;
public ISortableSymbolNode TypeGCStaticsSymbol(MetadataType type)
{
Debug.Assert(!TypeCannotHaveEEType(type));
return _GCStatics.GetOrAdd(type);
}
private NodeCache<MetadataType, GCStaticsPreInitDataNode> _GCStaticsPreInitDataNodes;
public GCStaticsPreInitDataNode GCStaticsPreInitDataNode(MetadataType type)
{
return _GCStaticsPreInitDataNodes.GetOrAdd(type);
}
private NodeCache<MetadataType, EmbeddedObjectNode> _GCStaticIndirectionNodes;
public EmbeddedObjectNode GCStaticIndirection(MetadataType type)
{
return _GCStaticIndirectionNodes.GetOrAdd(type);
}
private NodeCache<MetadataType, ISymbolDefinitionNode> _threadStatics;
public ISymbolDefinitionNode TypeThreadStaticsSymbol(MetadataType type)
{
// This node is always used in the context of its index within the region.
// We should never ask for this if the current compilation doesn't contain the
// associated type.
Debug.Assert(_compilationModuleGroup.ContainsType(type));
return _threadStatics.GetOrAdd(type);
}
private NodeCache<MetadataType, TypeThreadStaticIndexNode> _typeThreadStaticIndices;
public ISymbolNode TypeThreadStaticIndex(MetadataType type)
{
if (_compilationModuleGroup.ContainsType(type))
{
return _typeThreadStaticIndices.GetOrAdd(type);
}
else
{
return ExternSymbol("__TypeThreadStaticIndex_" + NameMangler.GetMangledTypeName(type));
}
}
private NodeCache<DispatchCellKey, InterfaceDispatchCellNode> _interfaceDispatchCells;
public InterfaceDispatchCellNode InterfaceDispatchCell(MethodDesc method, string callSite = null)
{
return _interfaceDispatchCells.GetOrAdd(new DispatchCellKey(method, callSite));
}
private NodeCache<MethodDesc, RuntimeMethodHandleNode> _runtimeMethodHandles;
public RuntimeMethodHandleNode RuntimeMethodHandle(MethodDesc method)
{
return _runtimeMethodHandles.GetOrAdd(method);
}
private NodeCache<FieldDesc, RuntimeFieldHandleNode> _runtimeFieldHandles;
public RuntimeFieldHandleNode RuntimeFieldHandle(FieldDesc field)
{
return _runtimeFieldHandles.GetOrAdd(field);
}
private NodeCache<GCPointerMap, GCStaticEETypeNode> _GCStaticEETypes;
public ISymbolNode GCStaticEEType(GCPointerMap gcMap)
{
return _GCStaticEETypes.GetOrAdd(gcMap);
}
private NodeCache<ReadOnlyDataBlobKey, BlobNode> _readOnlyDataBlobs;
public BlobNode ReadOnlyDataBlob(Utf8String name, byte[] blobData, int alignment)
{
return _readOnlyDataBlobs.GetOrAdd(new ReadOnlyDataBlobKey(name, blobData, alignment));
}
private NodeCache<TypeDesc, SealedVTableNode> _sealedVtableNodes;
internal SealedVTableNode SealedVTable(TypeDesc type)
{
return _sealedVtableNodes.GetOrAdd(type);
}
private NodeCache<TypeDesc, InterfaceDispatchMapNode> _interfaceDispatchMaps;
internal InterfaceDispatchMapNode InterfaceDispatchMap(TypeDesc type)
{
return _interfaceDispatchMaps.GetOrAdd(type);
}
private NodeCache<TypeDesc, EmbeddedObjectNode> _interfaceDispatchMapIndirectionNodes;
public EmbeddedObjectNode InterfaceDispatchMapIndirection(TypeDesc type)
{
return _interfaceDispatchMapIndirectionNodes.GetOrAdd(type);
}
private NodeCache<GenericCompositionDetails, GenericCompositionNode> _genericCompositions;
internal ISymbolNode GenericComposition(GenericCompositionDetails details)
{
return _genericCompositions.GetOrAdd(details);
}
private NodeCache<string, ExternSymbolNode> _externSymbols;
public ISortableSymbolNode ExternSymbol(string name)
{
return _externSymbols.GetOrAdd(name);
}
private NodeCache<string, PInvokeModuleFixupNode> _pInvokeModuleFixups;
public ISymbolNode PInvokeModuleFixup(string moduleName)
{
return _pInvokeModuleFixups.GetOrAdd(moduleName);
}
private NodeCache<Tuple<string, string, PInvokeFlags>, PInvokeMethodFixupNode> _pInvokeMethodFixups;
public PInvokeMethodFixupNode PInvokeMethodFixup(string moduleName, string entryPointName, PInvokeFlags flags)
{
return _pInvokeMethodFixups.GetOrAdd(Tuple.Create(moduleName, entryPointName, flags));
}
private NodeCache<TypeDesc, VTableSliceNode> _vTableNodes;
public VTableSliceNode VTable(TypeDesc type)
{
return _vTableNodes.GetOrAdd(type);
}
private NodeCache<MethodDesc, ISortableSymbolNode> _methodGenericDictionaries;
public ISortableSymbolNode MethodGenericDictionary(MethodDesc method)
{
return _methodGenericDictionaries.GetOrAdd(method);
}
private NodeCache<TypeDesc, ISortableSymbolNode> _typeGenericDictionaries;
public ISortableSymbolNode TypeGenericDictionary(TypeDesc type)
{
return _typeGenericDictionaries.GetOrAdd(type);
}
private NodeCache<TypeSystemEntity, DictionaryLayoutNode> _genericDictionaryLayouts;
public DictionaryLayoutNode GenericDictionaryLayout(TypeSystemEntity methodOrType)
{
return _genericDictionaryLayouts.GetOrAdd(methodOrType);
}
private NodeCache<MethodDesc, IMethodNode> _stringAllocators;
public IMethodNode StringAllocator(MethodDesc stringConstructor)
{
return _stringAllocators.GetOrAdd(stringConstructor);
}
private NodeCache<MethodDesc, IMethodNode> _methodEntrypoints;
private NodeCache<MethodDesc, IMethodNode> _unboxingStubs;
private NodeCache<IMethodNode, MethodAssociatedDataNode> _methodAssociatedData;
public IMethodNode MethodEntrypoint(MethodDesc method, bool unboxingStub = false)
{
if (unboxingStub)
{
return _unboxingStubs.GetOrAdd(method);
}
return _methodEntrypoints.GetOrAdd(method);
}
public MethodAssociatedDataNode MethodAssociatedData(IMethodNode methodNode)
{
return _methodAssociatedData.GetOrAdd(methodNode);
}
private NodeCache<MethodKey, FatFunctionPointerNode> _fatFunctionPointers;
public IMethodNode FatFunctionPointer(MethodDesc method, bool isUnboxingStub = false)
{
return _fatFunctionPointers.GetOrAdd(new MethodKey(method, isUnboxingStub));
}
public IMethodNode ExactCallableAddress(MethodDesc method, bool isUnboxingStub = false)
{
MethodDesc canonMethod = method.GetCanonMethodTarget(CanonicalFormKind.Specific);
if (method != canonMethod)
return FatFunctionPointer(method, isUnboxingStub);
else
return MethodEntrypoint(method, isUnboxingStub);
}
public IMethodNode CanonicalEntrypoint(MethodDesc method, bool isUnboxingStub = false)
{
MethodDesc canonMethod = method.GetCanonMethodTarget(CanonicalFormKind.Specific);
if (method != canonMethod)
return ShadowConcreteMethod(method, isUnboxingStub);
else
return MethodEntrypoint(method, isUnboxingStub);
}
private NodeCache<MethodDesc, GVMDependenciesNode> _gvmDependenciesNode;
public GVMDependenciesNode GVMDependencies(MethodDesc method)
{
return _gvmDependenciesNode.GetOrAdd(method);
}
private NodeCache<TypeDesc, TypeGVMEntriesNode> _gvmTableEntries;
internal TypeGVMEntriesNode TypeGVMEntries(TypeDesc type)
{
return _gvmTableEntries.GetOrAdd(type);
}
private NodeCache<MethodDesc, ReflectableMethodNode> _reflectableMethods;
public ReflectableMethodNode ReflectableMethod(MethodDesc method)
{
return _reflectableMethods.GetOrAdd(method);
}
private NodeCache<MethodKey, IMethodNode> _shadowConcreteMethods;
public IMethodNode ShadowConcreteMethod(MethodDesc method, bool isUnboxingStub = false)
{
return _shadowConcreteMethods.GetOrAdd(new MethodKey(method, isUnboxingStub));
}
private NodeCache<MethodDesc, IMethodNode> _runtimeDeterminedMethods;
public IMethodNode RuntimeDeterminedMethod(MethodDesc method)
{
return _runtimeDeterminedMethods.GetOrAdd(method);
}
private NodeCache<TypeDesc, DefaultConstructorFromLazyNode> _defaultConstructorFromLazyNodes;
internal DefaultConstructorFromLazyNode DefaultConstructorFromLazy(TypeDesc type)
{
return _defaultConstructorFromLazyNodes.GetOrAdd(type);
}
private static readonly string[][] s_helperEntrypointNames = new string[][] {
new string[] { "System.Runtime.CompilerServices", "ClassConstructorRunner", "CheckStaticClassConstructionReturnGCStaticBase" },
new string[] { "System.Runtime.CompilerServices", "ClassConstructorRunner", "CheckStaticClassConstructionReturnNonGCStaticBase" },
new string[] { "System.Runtime.CompilerServices", "ClassConstructorRunner", "CheckStaticClassConstructionReturnThreadStaticBase" },
new string[] { "Internal.Runtime", "ThreadStatics", "GetThreadStaticBaseForType" }
};
private ISymbolNode[] _helperEntrypointSymbols;
public ISymbolNode HelperEntrypoint(HelperEntrypoint entrypoint)
{
if (_helperEntrypointSymbols == null)
_helperEntrypointSymbols = new ISymbolNode[s_helperEntrypointNames.Length];
int index = (int)entrypoint;
ISymbolNode symbol = _helperEntrypointSymbols[index];
if (symbol == null)
{
var entry = s_helperEntrypointNames[index];
var type = _context.SystemModule.GetKnownType(entry[0], entry[1]);
var method = type.GetKnownMethod(entry[2], null);
symbol = MethodEntrypoint(method);
_helperEntrypointSymbols[index] = symbol;
}
return symbol;
}
private MetadataType _systemArrayOfTClass;
public MetadataType ArrayOfTClass
{
get
{
if (_systemArrayOfTClass == null)
{
_systemArrayOfTClass = _context.SystemModule.GetKnownType("System", "Array`1");
}
return _systemArrayOfTClass;
}
}
private TypeDesc _systemArrayOfTEnumeratorType;
public TypeDesc ArrayOfTEnumeratorType
{
get
{
if (_systemArrayOfTEnumeratorType == null)
{
_systemArrayOfTEnumeratorType = ArrayOfTClass.GetNestedType("ArrayEnumerator");
}
return _systemArrayOfTEnumeratorType;
}
}
private TypeDesc _systemICastableType;
public TypeDesc ICastableInterface
{
get
{
if (_systemICastableType == null)
{
_systemICastableType = _context.SystemModule.GetKnownType("System.Runtime.CompilerServices", "ICastable");
}
return _systemICastableType;
}
}
private NodeCache<MethodDesc, VirtualMethodUseNode> _virtMethods;
public DependencyNodeCore<NodeFactory> VirtualMethodUse(MethodDesc decl)
{
return _virtMethods.GetOrAdd(decl);
}
private NodeCache<ReadyToRunHelperKey, ISymbolNode> _readyToRunHelpers;
public ISymbolNode ReadyToRunHelper(ReadyToRunHelperId id, Object target)
{
return _readyToRunHelpers.GetOrAdd(new ReadyToRunHelperKey(id, target));
}
private NodeCache<ReadyToRunGenericHelperKey, ISymbolNode> _genericReadyToRunHelpersFromDict;
public ISymbolNode ReadyToRunHelperFromDictionaryLookup(ReadyToRunHelperId id, Object target, TypeSystemEntity dictionaryOwner)
{
return _genericReadyToRunHelpersFromDict.GetOrAdd(new ReadyToRunGenericHelperKey(id, target, dictionaryOwner));
}
private NodeCache<ReadyToRunGenericHelperKey, ISymbolNode> _genericReadyToRunHelpersFromType;
public ISymbolNode ReadyToRunHelperFromTypeLookup(ReadyToRunHelperId id, Object target, TypeSystemEntity dictionaryOwner)
{
return _genericReadyToRunHelpersFromType.GetOrAdd(new ReadyToRunGenericHelperKey(id, target, dictionaryOwner));
}
private NodeCache<ISortableSymbolNode, ISymbolNode> _indirectionNodes;
public ISymbolNode Indirection(ISortableSymbolNode symbol)
{
if (symbol.RepresentsIndirectionCell)
{
return symbol;
}
else
{
return _indirectionNodes.GetOrAdd(symbol);
}
}
private NodeCache<MetadataType, TypeMetadataNode> _typesWithMetadata;
internal TypeMetadataNode TypeMetadata(MetadataType type)
{
return _typesWithMetadata.GetOrAdd(type);
}
private NodeCache<MethodDesc, MethodMetadataNode> _methodsWithMetadata;
internal MethodMetadataNode MethodMetadata(MethodDesc method)
{
return _methodsWithMetadata.GetOrAdd(method);
}
private NodeCache<FieldDesc, FieldMetadataNode> _fieldsWithMetadata;
internal FieldMetadataNode FieldMetadata(FieldDesc field)
{
return _fieldsWithMetadata.GetOrAdd(field);
}
private NodeCache<ModuleDesc, ModuleMetadataNode> _modulesWithMetadata;
internal ModuleMetadataNode ModuleMetadata(ModuleDesc module)
{
return _modulesWithMetadata.GetOrAdd(module);
}
private NodeCache<string, FrozenStringNode> _frozenStringNodes;
public FrozenStringNode SerializedStringObject(string data)
{
return _frozenStringNodes.GetOrAdd(data);
}
private NodeCache<PreInitFieldInfo, FrozenArrayNode> _frozenArrayNodes;
public FrozenArrayNode SerializedFrozenArray(PreInitFieldInfo preInitFieldInfo)
{
return _frozenArrayNodes.GetOrAdd(preInitFieldInfo);
}
private NodeCache<MethodDesc, EmbeddedObjectNode> _eagerCctorIndirectionNodes;
public EmbeddedObjectNode EagerCctorIndirection(MethodDesc cctorMethod)
{
return _eagerCctorIndirectionNodes.GetOrAdd(cctorMethod);
}
public ISymbolNode ConstantUtf8String(string str)
{
int stringBytesCount = Encoding.UTF8.GetByteCount(str);
byte[] stringBytes = new byte[stringBytesCount + 1];
Encoding.UTF8.GetBytes(str, 0, str.Length, stringBytes, 0);
string symbolName = "__utf8str_" + NameMangler.GetMangledStringName(str);
return ReadOnlyDataBlob(symbolName, stringBytes, 1);
}
private NodeCache<Tuple<string, ISymbolNode>, NamedJumpStubNode> _namedJumpStubNodes;
public ISymbolNode NamedJumpStub(string name, ISymbolNode target)
{
return _namedJumpStubNodes.GetOrAdd(new Tuple<string, ISymbolNode>(name, target));
}
/// <summary>
/// Returns alternative symbol name that object writer should produce for given symbols
/// in addition to the regular one.
/// </summary>
public string GetSymbolAlternateName(ISymbolNode node)
{
string value;
if (!NodeAliases.TryGetValue(node, out value))
return null;
return value;
}
public ArrayOfEmbeddedPointersNode<GCStaticsNode> GCStaticsRegion = new ArrayOfEmbeddedPointersNode<GCStaticsNode>(
"__GCStaticRegionStart",
"__GCStaticRegionEnd",
new SortableDependencyNode.ObjectNodeComparer(new CompilerComparer()));
public ArrayOfEmbeddedDataNode<ThreadStaticsNode> ThreadStaticsRegion = new ArrayOfEmbeddedDataNode<ThreadStaticsNode>(
"__ThreadStaticRegionStart",
"__ThreadStaticRegionEnd",
new SortableDependencyNode.EmbeddedObjectNodeComparer(new CompilerComparer()));
public ArrayOfEmbeddedPointersNode<IMethodNode> EagerCctorTable = new ArrayOfEmbeddedPointersNode<IMethodNode>(
"__EagerCctorStart",
"__EagerCctorEnd",
null);
public ArrayOfEmbeddedPointersNode<InterfaceDispatchMapNode> DispatchMapTable = new ArrayOfEmbeddedPointersNode<InterfaceDispatchMapNode>(
"__DispatchMapTableStart",
"__DispatchMapTableEnd",
new SortableDependencyNode.ObjectNodeComparer(new CompilerComparer()));
public ArrayOfEmbeddedDataNode<EmbeddedObjectNode> FrozenSegmentRegion = new ArrayOfFrozenObjectsNode<EmbeddedObjectNode>(
"__FrozenSegmentRegionStart",
"__FrozenSegmentRegionEnd",
new SortableDependencyNode.EmbeddedObjectNodeComparer(new CompilerComparer()));
public ArrayOfEmbeddedPointersNode<MrtProcessedImportAddressTableNode> ImportAddressTablesTable = new ArrayOfEmbeddedPointersNode<MrtProcessedImportAddressTableNode>(
"__ImportTablesTableStart",
"__ImportTablesTableEnd",
new SortableDependencyNode.ObjectNodeComparer(new CompilerComparer()));
public ReadyToRunHeaderNode ReadyToRunHeader;
public Dictionary<ISymbolNode, string> NodeAliases = new Dictionary<ISymbolNode, string>();
protected internal TypeManagerIndirectionNode TypeManagerIndirection = new TypeManagerIndirectionNode();
public virtual void AttachToDependencyGraph(DependencyAnalyzerBase<NodeFactory> graph)
{
ReadyToRunHeader = new ReadyToRunHeaderNode(Target);
graph.AddRoot(ReadyToRunHeader, "ReadyToRunHeader is always generated");
graph.AddRoot(new ModulesSectionNode(Target), "ModulesSection is always generated");
graph.AddRoot(GCStaticsRegion, "GC StaticsRegion is always generated");
graph.AddRoot(ThreadStaticsRegion, "ThreadStaticsRegion is always generated");
graph.AddRoot(EagerCctorTable, "EagerCctorTable is always generated");
graph.AddRoot(TypeManagerIndirection, "TypeManagerIndirection is always generated");
graph.AddRoot(DispatchMapTable, "DispatchMapTable is always generated");
graph.AddRoot(FrozenSegmentRegion, "FrozenSegmentRegion is always generated");
if (Target.IsWindows)
{
// We need 2 delimiter symbols to bound the unboxing stubs region on Windows platforms (these symbols are
// accessed using extern "C" variables in the bootstrapper)
// On non-Windows platforms, the linker emits special symbols with special names at the begining/end of a section
// so we do not need to emit them ourselves.
graph.AddRoot(new WindowsUnboxingStubsRegionNode(false), "UnboxingStubsRegion delimiter for Windows platform");
graph.AddRoot(new WindowsUnboxingStubsRegionNode(true), "UnboxingStubsRegion delimiter for Windows platform");
}
ReadyToRunHeader.Add(ReadyToRunSectionType.GCStaticRegion, GCStaticsRegion, GCStaticsRegion.StartSymbol, GCStaticsRegion.EndSymbol);
ReadyToRunHeader.Add(ReadyToRunSectionType.ThreadStaticRegion, ThreadStaticsRegion, ThreadStaticsRegion.StartSymbol, ThreadStaticsRegion.EndSymbol);
ReadyToRunHeader.Add(ReadyToRunSectionType.EagerCctor, EagerCctorTable, EagerCctorTable.StartSymbol, EagerCctorTable.EndSymbol);
ReadyToRunHeader.Add(ReadyToRunSectionType.TypeManagerIndirection, TypeManagerIndirection, TypeManagerIndirection);
ReadyToRunHeader.Add(ReadyToRunSectionType.InterfaceDispatchTable, DispatchMapTable, DispatchMapTable.StartSymbol);
ReadyToRunHeader.Add(ReadyToRunSectionType.FrozenObjectRegion, FrozenSegmentRegion, FrozenSegmentRegion.StartSymbol, FrozenSegmentRegion.EndSymbol);
var commonFixupsTableNode = new ExternalReferencesTableNode("CommonFixupsTable", this);
InteropStubManager.AddToReadyToRunHeader(ReadyToRunHeader, this, commonFixupsTableNode);
MetadataManager.AddToReadyToRunHeader(ReadyToRunHeader, this, commonFixupsTableNode);
MetadataManager.AttachToDependencyGraph(graph);
ReadyToRunHeader.Add(MetadataManager.BlobIdToReadyToRunSection(ReflectionMapBlob.CommonFixupsTable), commonFixupsTableNode, commonFixupsTableNode, commonFixupsTableNode.EndSymbol);
}
protected struct MethodKey : IEquatable<MethodKey>
{
public readonly MethodDesc Method;
public readonly bool IsUnboxingStub;
public MethodKey(MethodDesc method, bool isUnboxingStub)
{
Method = method;
IsUnboxingStub = isUnboxingStub;
}
public bool Equals(MethodKey other) => Method == other.Method && IsUnboxingStub == other.IsUnboxingStub;
public override bool Equals(object obj) => obj is MethodKey && Equals((MethodKey)obj);
public override int GetHashCode() => Method.GetHashCode();
}
protected struct ReadyToRunHelperKey : IEquatable<ReadyToRunHelperKey>
{
public readonly object Target;
public readonly ReadyToRunHelperId HelperId;
public ReadyToRunHelperKey(ReadyToRunHelperId helperId, object target)
{
HelperId = helperId;
Target = target;
}
public bool Equals(ReadyToRunHelperKey other) => HelperId == other.HelperId && Target.Equals(other.Target);
public override bool Equals(object obj) => obj is ReadyToRunHelperKey && Equals((ReadyToRunHelperKey)obj);
public override int GetHashCode()
{
int hashCode = (int)HelperId * 0x5498341 + 0x832424;
hashCode = hashCode * 23 + Target.GetHashCode();
return hashCode;
}
}
protected struct ReadyToRunGenericHelperKey : IEquatable<ReadyToRunGenericHelperKey>
{
public readonly object Target;
public readonly TypeSystemEntity DictionaryOwner;
public readonly ReadyToRunHelperId HelperId;
public ReadyToRunGenericHelperKey(ReadyToRunHelperId helperId, object target, TypeSystemEntity dictionaryOwner)
{
HelperId = helperId;
Target = target;
DictionaryOwner = dictionaryOwner;
}
public bool Equals(ReadyToRunGenericHelperKey other)
=> HelperId == other.HelperId && DictionaryOwner == other.DictionaryOwner && Target.Equals(other.Target);
public override bool Equals(object obj) => obj is ReadyToRunGenericHelperKey && Equals((ReadyToRunGenericHelperKey)obj);
public override int GetHashCode()
{
int hashCode = (int)HelperId * 0x5498341 + 0x832424;
hashCode = hashCode * 23 + Target.GetHashCode();
hashCode = hashCode * 23 + DictionaryOwner.GetHashCode();
return hashCode;
}
}
protected struct DispatchCellKey : IEquatable<DispatchCellKey>
{
public readonly MethodDesc Target;
public readonly string CallsiteId;
public DispatchCellKey(MethodDesc target, string callsiteId)
{
Target = target;
CallsiteId = callsiteId;
}
public bool Equals(DispatchCellKey other) => Target == other.Target && CallsiteId == other.CallsiteId;
public override bool Equals(object obj) => obj is DispatchCellKey && Equals((DispatchCellKey)obj);
public override int GetHashCode()
{
int hashCode = Target.GetHashCode();
if (CallsiteId != null)
hashCode = hashCode * 23 + CallsiteId.GetHashCode();
return hashCode;
}
}
protected struct ReadOnlyDataBlobKey : IEquatable<ReadOnlyDataBlobKey>
{
public readonly Utf8String Name;
public readonly byte[] Data;
public readonly int Alignment;
public ReadOnlyDataBlobKey(Utf8String name, byte[] data, int alignment)
{
Name = name;
Data = data;
Alignment = alignment;
}
// The assumption here is that the name of the blob is unique.
// We can't emit two blobs with the same name and different contents.
// The name is part of the symbolic name and we don't do any mangling on it.
public bool Equals(ReadOnlyDataBlobKey other) => Name.Equals(other.Name);
public override bool Equals(object obj) => obj is ReadOnlyDataBlobKey && Equals((ReadOnlyDataBlobKey)obj);
public override int GetHashCode() => Name.GetHashCode();
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Management.Automation;
using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models;
namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
/// <summary>
/// Creates Azure Site Recovery Policy object in memory.
/// </summary>
[Cmdlet(
VerbsCommon.New,
"AzureRmRecoveryServicesAsrPolicy",
DefaultParameterSetName = ASRParameterSets.EnterpriseToAzure,
SupportsShouldProcess = true)]
[Alias("New-ASRPolicy")]
[OutputType(typeof(ASRJob))]
public class NewAzureRmRecoveryServicesAsrPolicy : SiteRecoveryCmdletBase
{
/// <summary>
/// Holds Name (if passed) of the Policy object.
/// </summary>
private string targetName = string.Empty;
/// <summary>
/// Gets or sets Name of the Policy.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToEnterprise,
Mandatory = true)]
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToAzure,
Mandatory = true)]
public string Name { get; set; }
/// <summary>
/// Gets or sets Replication Provider of the Policy.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToEnterprise,
Mandatory = true)]
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToAzure,
Mandatory = true)]
[ValidateNotNullOrEmpty]
[ValidateSet(
Constants.HyperVReplica2012R2,
Constants.HyperVReplica2012,
Constants.HyperVReplicaAzure)]
public string ReplicationProvider { get; set; }
/// <summary>
/// Gets or sets a value for Replication Method of the Policy.
/// </summary>
[Parameter(ParameterSetName = ASRParameterSets.EnterpriseToEnterprise)]
[ValidateNotNullOrEmpty]
[ValidateSet(
Constants.OnlineReplicationMethod,
Constants.OfflineReplicationMethod)]
public string ReplicationMethod { get; set; }
/// <summary>
/// Gets or sets Replication Frequency of the Policy in seconds.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToEnterprise,
Mandatory = true)]
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToAzure,
Mandatory = true)]
[ValidateNotNullOrEmpty]
[ValidateSet(
Constants.Thirty,
Constants.ThreeHundred,
Constants.NineHundred)]
public string ReplicationFrequencyInSeconds { get; set; }
/// <summary>
/// Gets or sets Recovery Points of the Policy.
/// </summary>
[Parameter(ParameterSetName = ASRParameterSets.EnterpriseToEnterprise)]
[Parameter(ParameterSetName = ASRParameterSets.EnterpriseToAzure)]
[ValidateNotNullOrEmpty]
[DefaultValue(0)]
[Alias("RecoveryPoints")]
public int NumberOfRecoveryPointsToRetain { get; set; }
/// <summary>
/// Gets or sets Application Consistent Snapshot Frequency of the Policy in hours.
/// </summary>
[Parameter(ParameterSetName = ASRParameterSets.EnterpriseToEnterprise)]
[Parameter(ParameterSetName = ASRParameterSets.EnterpriseToAzure)]
[ValidateNotNullOrEmpty]
[DefaultValue(0)]
public int ApplicationConsistentSnapshotFrequencyInHours { get; set; }
/// <summary>
/// Gets or sets a value indicating whether Compression needs to be Enabled on the Policy.
/// </summary>
[Parameter(ParameterSetName = ASRParameterSets.EnterpriseToEnterprise)]
[DefaultValue(Constants.Disable)]
[ValidateSet(
Constants.Enable,
Constants.Disable)]
public string Compression { get; set; }
/// <summary>
/// Gets or sets the Replication Port of the Policy.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToEnterprise,
Mandatory = true)]
[ValidateNotNullOrEmpty]
public ushort ReplicationPort { get; set; }
/// <summary>
/// Gets or sets the Replication Port of the Policy.
/// </summary>
[Parameter(ParameterSetName = ASRParameterSets.EnterpriseToEnterprise)]
[ValidateNotNullOrEmpty]
[ValidateSet(
Constants.AuthenticationTypeCertificate,
Constants.AuthenticationTypeKerberos)]
public string Authentication { get; set; }
/// <summary>
/// Gets or sets Replication Start time of the Policy.
/// </summary>
[Parameter(ParameterSetName = ASRParameterSets.EnterpriseToEnterprise)]
[Parameter(ParameterSetName = ASRParameterSets.EnterpriseToAzure)]
[ValidateNotNullOrEmpty]
public TimeSpan? ReplicationStartTime { get; set; }
/// <summary>
/// Gets or sets a value indicating whether Replica should be Deleted on
/// disabling protection of a protection entity protected by the Policy.
/// </summary>
[Parameter(ParameterSetName = ASRParameterSets.EnterpriseToEnterprise)]
[DefaultValue(Constants.NotRequired)]
[ValidateSet(
Constants.Required,
Constants.NotRequired)]
public string ReplicaDeletion { get; set; }
/// <summary>
/// Gets or sets Recovery Azure Storage Account Name of the Policy for E2A scenarios.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.EnterpriseToAzure,
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string RecoveryAzureStorageAccountId { get; set; }
/// <summary>
/// Gets or sets Encrypt parameter. On passing, data will be encrypted.
/// </summary>
[Parameter(ParameterSetName = ASRParameterSets.EnterpriseToAzure)]
[DefaultValue(Constants.Disable)]
[ValidateSet(
Constants.Enable,
Constants.Disable)]
public string Encryption { get; set; }
/// <summary>
/// ProcessRecord of the command.
/// </summary>
public override void ExecuteSiteRecoveryCmdlet()
{
base.ExecuteSiteRecoveryCmdlet();
if (this.ShouldProcess(
this.Name,
VerbsCommon.New))
{
switch (this.ParameterSetName)
{
case ASRParameterSets.EnterpriseToEnterprise:
this.EnterpriseToEnterprisePolicyObject();
break;
case ASRParameterSets.EnterpriseToAzure:
this.EnterpriseToAzurePolicyObject();
break;
}
}
}
/// <summary>
/// Creates an E2A Policy Object
/// </summary>
private void EnterpriseToAzurePolicyObject()
{
if (string.Compare(
this.ReplicationProvider,
Constants.HyperVReplicaAzure,
StringComparison.OrdinalIgnoreCase) !=
0)
{
throw new InvalidOperationException(
string.Format(
Resources.IncorrectReplicationProvider,
this.ReplicationProvider));
}
PSRecoveryServicesClient.ValidateReplicationStartTime(this.ReplicationStartTime);
var replicationFrequencyInSeconds =
PSRecoveryServicesClient.ConvertReplicationFrequencyToUshort(
this.ReplicationFrequencyInSeconds);
var hyperVReplicaAzurePolicyInput = new HyperVReplicaAzurePolicyInput
{
ApplicationConsistentSnapshotFrequencyInHours =
this.ApplicationConsistentSnapshotFrequencyInHours,
Encryption =
this.MyInvocation.BoundParameters.ContainsKey(
Utilities.GetMemberName(() => this.Encryption)) ? this.Encryption
: Constants.Disable,
OnlineReplicationStartTime =
this.ReplicationStartTime == null ? null : this.ReplicationStartTime.ToString(),
RecoveryPointHistoryDuration = this.NumberOfRecoveryPointsToRetain,
ReplicationInterval = replicationFrequencyInSeconds
};
hyperVReplicaAzurePolicyInput.StorageAccounts = new List<string>();
if (this.RecoveryAzureStorageAccountId != null)
{
var storageAccount = this.RecoveryAzureStorageAccountId;
hyperVReplicaAzurePolicyInput.StorageAccounts.Add(storageAccount);
}
var createPolicyInputProperties =
new CreatePolicyInputProperties
{
ProviderSpecificInput = hyperVReplicaAzurePolicyInput
};
var createPolicyInput =
new CreatePolicyInput { Properties = createPolicyInputProperties };
var response = this.RecoveryServicesClient.CreatePolicy(
this.Name,
createPolicyInput);
var jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails(
PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location));
this.WriteObject(new ASRJob(jobResponse));
}
/// <summary>
/// Creates an E2E Policy object
/// </summary>
private void EnterpriseToEnterprisePolicyObject()
{
if ((string.Compare(
this.ReplicationProvider,
Constants.HyperVReplica2012,
StringComparison.OrdinalIgnoreCase) !=
0) &&
(string.Compare(
this.ReplicationProvider,
Constants.HyperVReplica2012R2,
StringComparison.OrdinalIgnoreCase) !=
0))
{
throw new InvalidOperationException(
string.Format(
Resources.IncorrectReplicationProvider,
this.ReplicationProvider));
}
PSRecoveryServicesClient.ValidateReplicationStartTime(this.ReplicationStartTime);
var replicationFrequencyInSeconds =
PSRecoveryServicesClient.ConvertReplicationFrequencyToUshort(
this.ReplicationFrequencyInSeconds);
var createPolicyInputProperties = new CreatePolicyInputProperties();
if (string.Compare(
this.ReplicationProvider,
Constants.HyperVReplica2012,
StringComparison.OrdinalIgnoreCase) ==
0)
{
createPolicyInputProperties.ProviderSpecificInput = new HyperVReplicaPolicyInput
{
AllowedAuthenticationType = (ushort)(string.Compare(
this.Authentication,
Constants.AuthenticationTypeKerberos,
StringComparison.OrdinalIgnoreCase) ==
0 ? 1 : 2),
ApplicationConsistentSnapshotFrequencyInHours =
this.ApplicationConsistentSnapshotFrequencyInHours,
Compression =
this.MyInvocation.BoundParameters.ContainsKey(
Utilities.GetMemberName(() => this.Compression)) ? this.Compression
: Constants.Disable,
InitialReplicationMethod = string.Compare(
this.ReplicationMethod,
Constants.OnlineReplicationMethod,
StringComparison.OrdinalIgnoreCase) ==
0 ? "OverNetwork" : "Offline",
OnlineReplicationStartTime = this.ReplicationStartTime.ToString(),
RecoveryPoints = this.NumberOfRecoveryPointsToRetain,
ReplicaDeletion =
this.MyInvocation.BoundParameters.ContainsKey(
Utilities.GetMemberName(() => this.ReplicaDeletion))
? this.ReplicaDeletion : Constants.NotRequired,
ReplicationPort = this.ReplicationPort
};
}
else
{
createPolicyInputProperties.ProviderSpecificInput =
new HyperVReplicaBluePolicyInput
{
AllowedAuthenticationType = (ushort)(string.Compare(
this.Authentication,
Constants
.AuthenticationTypeKerberos,
StringComparison
.OrdinalIgnoreCase) ==
0 ? 1 : 2),
ApplicationConsistentSnapshotFrequencyInHours =
this.ApplicationConsistentSnapshotFrequencyInHours,
Compression =
this.MyInvocation.BoundParameters.ContainsKey(
Utilities.GetMemberName(() => this.Compression)) ? this.Compression
: Constants.Disable,
InitialReplicationMethod = string.Compare(
this.ReplicationMethod,
Constants.OnlineReplicationMethod,
StringComparison.OrdinalIgnoreCase) ==
0 ? "OverNetwork" : "Offline",
OnlineReplicationStartTime = this.ReplicationStartTime.ToString(),
RecoveryPoints = this.NumberOfRecoveryPointsToRetain,
ReplicaDeletion =
this.MyInvocation.BoundParameters.ContainsKey(
Utilities.GetMemberName(() => this.ReplicaDeletion))
? this.ReplicaDeletion : Constants.NotRequired,
ReplicationFrequencyInSeconds = replicationFrequencyInSeconds,
ReplicationPort = this.ReplicationPort
};
}
var createPolicyInput =
new CreatePolicyInput { Properties = createPolicyInputProperties };
var responseBlue = this.RecoveryServicesClient.CreatePolicy(
this.Name,
createPolicyInput);
var jobResponseBlue = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails(
PSRecoveryServicesClient.GetJobIdFromReponseLocation(responseBlue.Location));
this.WriteObject(new ASRJob(jobResponseBlue));
}
}
}
| |
// 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 ShiftLeftLogical128BitLaneInt641()
{
var test = new ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt641();
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__ShiftLeftLogical128BitLaneInt641
{
private struct TestStruct
{
public Vector128<Int64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt641 testClass)
{
var result = Sse2.ShiftLeftLogical128BitLane(_fld, 1);
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<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static Int64[] _data = new Int64[Op1ElementCount];
private static Vector128<Int64> _clsVar;
private Vector128<Int64> _fld;
private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable;
static ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt641()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
}
public ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt641()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)8; }
_dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[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.ShiftLeftLogical128BitLane(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ShiftLeftLogical128BitLane(
Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ShiftLeftLogical128BitLane(
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)),
1
);
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.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ShiftLeftLogical128BitLane(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt641();
var result = Sse2.ShiftLeftLogical128BitLane(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ShiftLeftLogical128BitLane(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ShiftLeftLogical128BitLane(test._fld, 1);
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<Int64> firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != 2048)
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != 2048)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical128BitLane)}<Int64>(Vector128<Int64><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.Entities;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Persistence.Querying;
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.Services.Implement
{
public class RelationService : RepositoryService, IRelationService
{
private readonly IEntityService _entityService;
private readonly IRelationRepository _relationRepository;
private readonly IRelationTypeRepository _relationTypeRepository;
private readonly IAuditRepository _auditRepository;
public RelationService(IScopeProvider uowProvider, ILoggerFactory loggerFactory, IEventMessagesFactory eventMessagesFactory, IEntityService entityService,
IRelationRepository relationRepository, IRelationTypeRepository relationTypeRepository, IAuditRepository auditRepository)
: base(uowProvider, loggerFactory, eventMessagesFactory)
{
_relationRepository = relationRepository;
_relationTypeRepository = relationTypeRepository;
_auditRepository = auditRepository;
_entityService = entityService ?? throw new ArgumentNullException(nameof(entityService));
}
/// <inheritdoc />
public IRelation GetById(int id)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _relationRepository.Get(id);
}
}
/// <inheritdoc />
public IRelationType GetRelationTypeById(int id)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _relationTypeRepository.Get(id);
}
}
/// <inheritdoc />
public IRelationType GetRelationTypeById(Guid id)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _relationTypeRepository.Get(id);
}
}
/// <inheritdoc />
public IRelationType GetRelationTypeByAlias(string alias) => GetRelationType(alias);
/// <inheritdoc />
public IEnumerable<IRelation> GetAllRelations(params int[] ids)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _relationRepository.GetMany(ids);
}
}
/// <inheritdoc />
public IEnumerable<IRelation> GetAllRelationsByRelationType(IRelationType relationType)
{
return GetAllRelationsByRelationType(relationType.Id);
}
/// <inheritdoc />
public IEnumerable<IRelation> GetAllRelationsByRelationType(int relationTypeId)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
var query = Query<IRelation>().Where(x => x.RelationTypeId == relationTypeId);
return _relationRepository.Get(query);
}
}
/// <inheritdoc />
public IEnumerable<IRelationType> GetAllRelationTypes(params int[] ids)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _relationTypeRepository.GetMany(ids);
}
}
/// <inheritdoc />
public IEnumerable<IRelation> GetByParentId(int id) => GetByParentId(id, null);
/// <inheritdoc />
public IEnumerable<IRelation> GetByParentId(int id, string relationTypeAlias)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
if (relationTypeAlias.IsNullOrWhiteSpace())
{
var qry1 = Query<IRelation>().Where(x => x.ParentId == id);
return _relationRepository.Get(qry1);
}
var relationType = GetRelationType(relationTypeAlias);
if (relationType == null)
return Enumerable.Empty<IRelation>();
var qry2 = Query<IRelation>().Where(x => x.ParentId == id && x.RelationTypeId == relationType.Id);
return _relationRepository.Get(qry2);
}
}
/// <inheritdoc />
public IEnumerable<IRelation> GetByParent(IUmbracoEntity parent) => GetByParentId(parent.Id);
/// <inheritdoc />
public IEnumerable<IRelation> GetByParent(IUmbracoEntity parent, string relationTypeAlias) => GetByParentId(parent.Id, relationTypeAlias);
/// <inheritdoc />
public IEnumerable<IRelation> GetByChildId(int id) => GetByChildId(id, null);
/// <inheritdoc />
public IEnumerable<IRelation> GetByChildId(int id, string relationTypeAlias)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
if (relationTypeAlias.IsNullOrWhiteSpace())
{
var qry1 = Query<IRelation>().Where(x => x.ChildId == id);
return _relationRepository.Get(qry1);
}
var relationType = GetRelationType(relationTypeAlias);
if (relationType == null)
return Enumerable.Empty<IRelation>();
var qry2 = Query<IRelation>().Where(x => x.ChildId == id && x.RelationTypeId == relationType.Id);
return _relationRepository.Get(qry2);
}
}
/// <inheritdoc />
public IEnumerable<IRelation> GetByChild(IUmbracoEntity child) => GetByChildId(child.Id);
/// <inheritdoc />
public IEnumerable<IRelation> GetByChild(IUmbracoEntity child, string relationTypeAlias) => GetByChildId(child.Id, relationTypeAlias);
/// <inheritdoc />
public IEnumerable<IRelation> GetByParentOrChildId(int id)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
var query = Query<IRelation>().Where(x => x.ChildId == id || x.ParentId == id);
return _relationRepository.Get(query);
}
}
public IEnumerable<IRelation> GetByParentOrChildId(int id, string relationTypeAlias)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
var relationType = GetRelationType(relationTypeAlias);
if (relationType == null)
return Enumerable.Empty<IRelation>();
var query = Query<IRelation>().Where(x => (x.ChildId == id || x.ParentId == id) && x.RelationTypeId == relationType.Id);
return _relationRepository.Get(query);
}
}
/// <inheritdoc />
public IRelation GetByParentAndChildId(int parentId, int childId, IRelationType relationType)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
var query = Query<IRelation>().Where(x => x.ParentId == parentId &&
x.ChildId == childId &&
x.RelationTypeId == relationType.Id);
return _relationRepository.Get(query).FirstOrDefault();
}
}
/// <inheritdoc />
public IEnumerable<IRelation> GetByRelationTypeName(string relationTypeName)
{
List<int> relationTypeIds;
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
//This is a silly query - but i guess it's needed in case someone has more than one relation with the same Name (not alias), odd.
var query = Query<IRelationType>().Where(x => x.Name == relationTypeName);
var relationTypes = _relationTypeRepository.Get(query);
relationTypeIds = relationTypes.Select(x => x.Id).ToList();
}
return relationTypeIds.Count == 0
? Enumerable.Empty<IRelation>()
: GetRelationsByListOfTypeIds(relationTypeIds);
}
/// <inheritdoc />
public IEnumerable<IRelation> GetByRelationTypeAlias(string relationTypeAlias)
{
var relationType = GetRelationType(relationTypeAlias);
return relationType == null
? Enumerable.Empty<IRelation>()
: GetRelationsByListOfTypeIds(new[] { relationType.Id });
}
/// <inheritdoc />
public IEnumerable<IRelation> GetByRelationTypeId(int relationTypeId)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
var query = Query<IRelation>().Where(x => x.RelationTypeId == relationTypeId);
return _relationRepository.Get(query);
}
}
/// <inheritdoc />
public IEnumerable<IRelation> GetPagedByRelationTypeId(int relationTypeId, long pageIndex, int pageSize, out long totalRecords, Ordering ordering = null)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
var query = Query<IRelation>().Where(x => x.RelationTypeId == relationTypeId);
return _relationRepository.GetPagedRelationsByQuery(query, pageIndex, pageSize, out totalRecords, ordering);
}
}
/// <inheritdoc />
public IUmbracoEntity GetChildEntityFromRelation(IRelation relation)
{
var objectType = ObjectTypes.GetUmbracoObjectType(relation.ChildObjectType);
return _entityService.Get(relation.ChildId, objectType);
}
/// <inheritdoc />
public IUmbracoEntity GetParentEntityFromRelation(IRelation relation)
{
var objectType = ObjectTypes.GetUmbracoObjectType(relation.ParentObjectType);
return _entityService.Get(relation.ParentId, objectType);
}
/// <inheritdoc />
public Tuple<IUmbracoEntity, IUmbracoEntity> GetEntitiesFromRelation(IRelation relation)
{
var childObjectType = ObjectTypes.GetUmbracoObjectType(relation.ChildObjectType);
var parentObjectType = ObjectTypes.GetUmbracoObjectType(relation.ParentObjectType);
var child = _entityService.Get(relation.ChildId, childObjectType);
var parent = _entityService.Get(relation.ParentId, parentObjectType);
return new Tuple<IUmbracoEntity, IUmbracoEntity>(parent, child);
}
/// <inheritdoc />
public IEnumerable<IUmbracoEntity> GetChildEntitiesFromRelations(IEnumerable<IRelation> relations)
{
// Trying to avoid full N+1 lookups, so we'll group by the object type and then use the GetAll
// method to lookup batches of entities for each parent object type
foreach (var groupedRelations in relations.GroupBy(x => ObjectTypes.GetUmbracoObjectType(x.ChildObjectType)))
{
var objectType = groupedRelations.Key;
var ids = groupedRelations.Select(x => x.ChildId).ToArray();
foreach (var e in _entityService.GetAll(objectType, ids))
yield return e;
}
}
/// <inheritdoc />
public IEnumerable<IUmbracoEntity> GetParentEntitiesFromRelations(IEnumerable<IRelation> relations)
{
// Trying to avoid full N+1 lookups, so we'll group by the object type and then use the GetAll
// method to lookup batches of entities for each parent object type
foreach (var groupedRelations in relations.GroupBy(x => ObjectTypes.GetUmbracoObjectType(x.ParentObjectType)))
{
var objectType = groupedRelations.Key;
var ids = groupedRelations.Select(x => x.ParentId).ToArray();
foreach (var e in _entityService.GetAll(objectType, ids))
yield return e;
}
}
/// <inheritdoc />
public IEnumerable<IUmbracoEntity> GetPagedParentEntitiesByChildId(int id, long pageIndex, int pageSize, out long totalChildren, params UmbracoObjectTypes[] entityTypes)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _relationRepository.GetPagedParentEntitiesByChildId(id, pageIndex, pageSize, out totalChildren, entityTypes.Select(x => x.GetGuid()).ToArray());
}
}
/// <inheritdoc />
public IEnumerable<IUmbracoEntity> GetPagedChildEntitiesByParentId(int id, long pageIndex, int pageSize, out long totalChildren, params UmbracoObjectTypes[] entityTypes)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _relationRepository.GetPagedChildEntitiesByParentId(id, pageIndex, pageSize, out totalChildren, entityTypes.Select(x => x.GetGuid()).ToArray());
}
}
/// <inheritdoc />
public IEnumerable<Tuple<IUmbracoEntity, IUmbracoEntity>> GetEntitiesFromRelations(IEnumerable<IRelation> relations)
{
//TODO: Argh! N+1
foreach (var relation in relations)
{
var childObjectType = ObjectTypes.GetUmbracoObjectType(relation.ChildObjectType);
var parentObjectType = ObjectTypes.GetUmbracoObjectType(relation.ParentObjectType);
var child = _entityService.Get(relation.ChildId, childObjectType);
var parent = _entityService.Get(relation.ParentId, parentObjectType);
yield return new Tuple<IUmbracoEntity, IUmbracoEntity>(parent, child);
}
}
/// <inheritdoc />
public IRelation Relate(int parentId, int childId, IRelationType relationType)
{
// Ensure that the RelationType has an identity before using it to relate two entities
if (relationType.HasIdentity == false)
{
Save(relationType);
}
//TODO: We don't check if this exists first, it will throw some sort of data integrity exception if it already exists, is that ok?
var relation = new Relation(parentId, childId, relationType);
using (IScope scope = ScopeProvider.CreateScope())
{
EventMessages eventMessages = EventMessagesFactory.Get();
var savingNotification = new RelationSavingNotification(relation, eventMessages);
if (scope.Notifications.PublishCancelable(savingNotification))
{
scope.Complete();
return relation; // TODO: returning sth that does not exist here?!
}
_relationRepository.Save(relation);
scope.Notifications.Publish(new RelationSavedNotification(relation, eventMessages).WithStateFrom(savingNotification));
scope.Complete();
return relation;
}
}
/// <inheritdoc />
public IRelation Relate(IUmbracoEntity parent, IUmbracoEntity child, IRelationType relationType)
{
return Relate(parent.Id, child.Id, relationType);
}
/// <inheritdoc />
public IRelation Relate(int parentId, int childId, string relationTypeAlias)
{
var relationType = GetRelationTypeByAlias(relationTypeAlias);
if (relationType == null || string.IsNullOrEmpty(relationType.Alias))
throw new ArgumentNullException(string.Format("No RelationType with Alias '{0}' exists.", relationTypeAlias));
return Relate(parentId, childId, relationType);
}
/// <inheritdoc />
public IRelation Relate(IUmbracoEntity parent, IUmbracoEntity child, string relationTypeAlias)
{
var relationType = GetRelationTypeByAlias(relationTypeAlias);
if (relationType == null || string.IsNullOrEmpty(relationType.Alias))
throw new ArgumentNullException(string.Format("No RelationType with Alias '{0}' exists.", relationTypeAlias));
return Relate(parent.Id, child.Id, relationType);
}
/// <inheritdoc />
public bool HasRelations(IRelationType relationType)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
var query = Query<IRelation>().Where(x => x.RelationTypeId == relationType.Id);
return _relationRepository.Get(query).Any();
}
}
/// <inheritdoc />
public bool IsRelated(int id)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
var query = Query<IRelation>().Where(x => x.ParentId == id || x.ChildId == id);
return _relationRepository.Get(query).Any();
}
}
/// <inheritdoc />
public bool AreRelated(int parentId, int childId)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
var query = Query<IRelation>().Where(x => x.ParentId == parentId && x.ChildId == childId);
return _relationRepository.Get(query).Any();
}
}
/// <inheritdoc />
public bool AreRelated(int parentId, int childId, string relationTypeAlias)
{
var relType = GetRelationTypeByAlias(relationTypeAlias);
if (relType == null)
return false;
return AreRelated(parentId, childId, relType);
}
/// <inheritdoc />
public bool AreRelated(int parentId, int childId, IRelationType relationType)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
var query = Query<IRelation>().Where(x => x.ParentId == parentId && x.ChildId == childId && x.RelationTypeId == relationType.Id);
return _relationRepository.Get(query).Any();
}
}
/// <inheritdoc />
public bool AreRelated(IUmbracoEntity parent, IUmbracoEntity child)
{
return AreRelated(parent.Id, child.Id);
}
/// <inheritdoc />
public bool AreRelated(IUmbracoEntity parent, IUmbracoEntity child, string relationTypeAlias)
{
return AreRelated(parent.Id, child.Id, relationTypeAlias);
}
/// <inheritdoc />
public void Save(IRelation relation)
{
using (var scope = ScopeProvider.CreateScope())
{
EventMessages eventMessages = EventMessagesFactory.Get();
var savingNotification = new RelationSavingNotification(relation, eventMessages);
if (scope.Notifications.PublishCancelable(savingNotification))
{
scope.Complete();
return;
}
_relationRepository.Save(relation);
scope.Complete();
scope.Notifications.Publish(new RelationSavedNotification(relation, eventMessages).WithStateFrom(savingNotification));
}
}
public void Save(IEnumerable<IRelation> relations)
{
using (IScope scope = ScopeProvider.CreateScope())
{
IRelation[] relationsA = relations.ToArray();
EventMessages messages = EventMessagesFactory.Get();
var savingNotification = new RelationSavingNotification(relationsA, messages);
if (scope.Notifications.PublishCancelable(savingNotification))
{
scope.Complete();
return;
}
_relationRepository.Save(relationsA);
scope.Complete();
scope.Notifications.Publish(new RelationSavedNotification(relationsA, messages).WithStateFrom(savingNotification));
}
}
/// <inheritdoc />
public void Save(IRelationType relationType)
{
using (IScope scope = ScopeProvider.CreateScope())
{
EventMessages eventMessages = EventMessagesFactory.Get();
var savingNotification = new RelationTypeSavingNotification(relationType, eventMessages);
if (scope.Notifications.PublishCancelable(savingNotification))
{
scope.Complete();
return;
}
_relationTypeRepository.Save(relationType);
Audit(AuditType.Save, Cms.Core.Constants.Security.SuperUserId, relationType.Id, $"Saved relation type: {relationType.Name}");
scope.Complete();
scope.Notifications.Publish(new RelationTypeSavedNotification(relationType, eventMessages).WithStateFrom(savingNotification));
}
}
/// <inheritdoc />
public void Delete(IRelation relation)
{
using (IScope scope = ScopeProvider.CreateScope())
{
EventMessages eventMessages = EventMessagesFactory.Get();
var deletingNotification = new RelationDeletingNotification(relation, eventMessages);
if (scope.Notifications.PublishCancelable(deletingNotification))
{
scope.Complete();
return;
}
_relationRepository.Delete(relation);
scope.Complete();
scope.Notifications.Publish(new RelationDeletedNotification(relation, eventMessages).WithStateFrom(deletingNotification));
}
}
/// <inheritdoc />
public void Delete(IRelationType relationType)
{
using (IScope scope = ScopeProvider.CreateScope())
{
EventMessages eventMessages = EventMessagesFactory.Get();
var deletingNotification = new RelationTypeDeletingNotification(relationType, eventMessages);
if (scope.Notifications.PublishCancelable(deletingNotification))
{
scope.Complete();
return;
}
_relationTypeRepository.Delete(relationType);
scope.Complete();
scope.Notifications.Publish(new RelationTypeDeletedNotification(relationType, eventMessages).WithStateFrom(deletingNotification));
}
}
/// <inheritdoc />
public void DeleteRelationsOfType(IRelationType relationType)
{
var relations = new List<IRelation>();
using (IScope scope = ScopeProvider.CreateScope())
{
IQuery<IRelation> query = Query<IRelation>().Where(x => x.RelationTypeId == relationType.Id);
relations.AddRange(_relationRepository.Get(query).ToList());
//TODO: N+1, we should be able to do this in a single call
foreach (IRelation relation in relations)
{
_relationRepository.Delete(relation);
}
scope.Complete();
scope.Notifications.Publish(new RelationDeletedNotification(relations, EventMessagesFactory.Get()));
}
}
#region Private Methods
private IRelationType GetRelationType(string relationTypeAlias)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
var query = Query<IRelationType>().Where(x => x.Alias == relationTypeAlias);
return _relationTypeRepository.Get(query).FirstOrDefault();
}
}
private IEnumerable<IRelation> GetRelationsByListOfTypeIds(IEnumerable<int> relationTypeIds)
{
var relations = new List<IRelation>();
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
foreach (var relationTypeId in relationTypeIds)
{
var id = relationTypeId;
var query = Query<IRelation>().Where(x => x.RelationTypeId == id);
relations.AddRange(_relationRepository.Get(query));
}
}
return relations;
}
private void Audit(AuditType type, int userId, int objectId, string message = null)
{
_auditRepository.Save(new AuditItem(objectId, type, userId, ObjectTypes.GetName(UmbracoObjectTypes.RelationType), message));
}
#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.Reflection;
namespace System.Runtime.Serialization
{
#if NET_NATIVE
public class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext
#else
internal class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext
#endif
{
private bool _preserveObjectReferences;
private SerializationMode _mode;
private ISerializationSurrogateProvider _serializationSurrogateProvider;
internal XmlObjectSerializerReadContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
: base(serializer, rootTypeDataContract, dataContractResolver)
{
_mode = SerializationMode.SharedContract;
_preserveObjectReferences = serializer.PreserveObjectReferences;
_serializationSurrogateProvider = serializer.SerializationSurrogateProvider;
}
internal XmlObjectSerializerReadContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
: base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject)
{
}
internal override SerializationMode Mode
{
get { return _mode; }
}
internal override object InternalDeserialize(XmlReaderDelegator xmlReader, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, string name, string ns)
{
if (_mode == SerializationMode.SharedContract)
{
if (_serializationSurrogateProvider == null)
return base.InternalDeserialize(xmlReader, declaredTypeID, declaredTypeHandle, name, ns);
else
return InternalDeserializeWithSurrogate(xmlReader, Type.GetTypeFromHandle(declaredTypeHandle), null /*surrogateDataContract*/, name, ns);
}
else
{
return InternalDeserializeInSharedTypeMode(xmlReader, declaredTypeID, Type.GetTypeFromHandle(declaredTypeHandle), name, ns);
}
}
internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns)
{
if (_mode == SerializationMode.SharedContract)
{
if (_serializationSurrogateProvider == null)
return base.InternalDeserialize(xmlReader, declaredType, name, ns);
else
return InternalDeserializeWithSurrogate(xmlReader, declaredType, null /*surrogateDataContract*/, name, ns);
}
else
{
return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns);
}
}
internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns)
{
if (_mode == SerializationMode.SharedContract)
{
if (_serializationSurrogateProvider == null)
return base.InternalDeserialize(xmlReader, declaredType, dataContract, name, ns);
else
return InternalDeserializeWithSurrogate(xmlReader, declaredType, dataContract, name, ns);
}
else
{
return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns);
}
}
private object InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, int declaredTypeID, Type declaredType, string name, string ns)
{
object retObj = null;
if (TryHandleNullOrRef(xmlReader, declaredType, name, ns, ref retObj))
return retObj;
DataContract dataContract;
string assemblyName = attributes.ClrAssembly;
string typeName = attributes.ClrType;
if (assemblyName != null && typeName != null)
{
Assembly assembly;
Type type;
dataContract = ResolveDataContractInSharedTypeMode(assemblyName, typeName, out assembly, out type);
if (dataContract == null)
{
if (assembly == null)
throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.AssemblyNotFound, assemblyName));
if (type == null)
throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ClrTypeNotFound, assembly.FullName, typeName));
}
//Array covariance is not supported in XSD. If declared type is array, data is sent in format of base array
if (declaredType != null && declaredType.IsArray)
dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
}
else
{
if (assemblyName != null)
throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
else if (typeName != null)
throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrAssemblyLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
else if (declaredType == null)
throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
}
return ReadDataContractValue(dataContract, xmlReader);
}
private object InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, string name, string ns)
{
DataContract dataContract = surrogateDataContract ??
GetDataContract(DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, declaredType));
if (this.IsGetOnlyCollection && dataContract.UnderlyingType != declaredType)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(declaredType))));
}
ReadAttributes(xmlReader);
string objectId = GetObjectId();
object oldObj = InternalDeserialize(xmlReader, name, ns, ref dataContract);
object obj = DataContractSurrogateCaller.GetDeserializedObject(_serializationSurrogateProvider, oldObj, dataContract.UnderlyingType, declaredType);
ReplaceDeserializedObject(objectId, oldObj, obj);
return obj;
}
private Type ResolveDataContractTypeInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly)
{
throw new PlatformNotSupportedException();
}
private DataContract ResolveDataContractInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly, out Type type)
{
type = ResolveDataContractTypeInSharedTypeMode(assemblyName, typeName, out assembly);
if (type != null)
{
return GetDataContract(type);
}
return null;
}
protected override DataContract ResolveDataContractFromTypeName()
{
if (_mode == SerializationMode.SharedContract)
{
return base.ResolveDataContractFromTypeName();
}
else
{
if (attributes.ClrAssembly != null && attributes.ClrType != null)
{
Assembly assembly;
Type type;
return ResolveDataContractInSharedTypeMode(attributes.ClrAssembly, attributes.ClrType, out assembly, out type);
}
}
return null;
}
internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable)
{
if (_serializationSurrogateProvider != null)
{
while (memberType.IsArray)
memberType = memberType.GetElementType();
memberType = DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, memberType);
if (!DataContract.IsTypeSerializable(memberType))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TypeNotSerializable, memberType)));
return;
}
base.CheckIfTypeSerializable(memberType, isMemberTypeSerializable);
}
internal override Type GetSurrogatedType(Type type)
{
if (_serializationSurrogateProvider == null)
{
return base.GetSurrogatedType(type);
}
else
{
type = DataContract.UnwrapNullableType(type);
Type surrogateType = DataContractSerializer.GetSurrogatedType(_serializationSurrogateProvider, type);
if (this.IsGetOnlyCollection && surrogateType != type)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser,
DataContract.GetClrTypeFullName(type))));
}
else
{
return surrogateType;
}
}
}
#if USE_REFEMIT
public override int GetArraySize()
#else
internal override int GetArraySize()
#endif
{
return _preserveObjectReferences ? attributes.ArraySZSize : -1;
}
}
}
| |
#region License
// Copyright 2014 MorseCode Software
// 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
namespace MorseCode.RxMvvm.Observable.Property.Internal
{
using System;
using System.Diagnostics.Contracts;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Threading.Tasks;
using MorseCode.RxMvvm.Common;
using MorseCode.RxMvvm.Common.DiscriminatedUnion;
[Serializable]
internal class CancellableAsyncCalculatedProperty<TFirst, TSecond, T> : CalculatedPropertyBase<T>, ISerializable
{
#region Fields
private readonly IObservable<TFirst> firstProperty;
private readonly IObservable<TSecond> secondProperty;
private readonly TimeSpan throttleTime;
private readonly Func<AsyncCalculationHelper, TFirst, TSecond, Task<T>> calculateValue;
private readonly bool isLongRunningCalculation;
private IDisposable scheduledTask;
#endregion
#region Constructors and Destructors
internal CancellableAsyncCalculatedProperty(
IObservable<TFirst> firstProperty,
IObservable<TSecond> secondProperty,
TimeSpan throttleTime,
Func<AsyncCalculationHelper, TFirst, TSecond, Task<T>> calculateValue,
bool isLongRunningCalculation)
{
Contract.Requires<ArgumentNullException>(firstProperty != null, "firstProperty");
Contract.Requires<ArgumentNullException>(secondProperty != null, "secondProperty");
Contract.Requires<ArgumentNullException>(calculateValue != null, "calculateValue");
Contract.Ensures(this.firstProperty != null);
Contract.Ensures(this.secondProperty != null);
Contract.Ensures(this.calculateValue != null);
RxMvvmConfiguration.EnsureSerializableDelegateIfUsingSerialization(calculateValue);
this.firstProperty = firstProperty;
this.secondProperty = secondProperty;
this.throttleTime = throttleTime;
this.calculateValue = calculateValue;
this.isLongRunningCalculation = isLongRunningCalculation;
Func<AsyncCalculationHelper, TFirst, TSecond, Task<IDiscriminatedUnion<object, T, Exception>>> calculate =
async (helper, first, second) =>
{
IDiscriminatedUnion<object, T, Exception> discriminatedUnion;
try
{
discriminatedUnion =
DiscriminatedUnion.First<object, T, Exception>(
await calculateValue(helper, first, second).ConfigureAwait(true));
}
catch (Exception e)
{
discriminatedUnion = DiscriminatedUnion.Second<object, T, Exception>(e);
}
return discriminatedUnion;
};
this.SetHelper(
new CalculatedPropertyHelper(
(resultSubject, isCalculatingSubject) =>
{
CompositeDisposable d = new CompositeDisposable();
IScheduler scheduler = isLongRunningCalculation
? RxMvvmConfiguration.GetLongRunningCalculationScheduler()
: RxMvvmConfiguration.GetCalculationScheduler();
IObservable<Tuple<TFirst, TSecond>> o = firstProperty.CombineLatest(
secondProperty, Tuple.Create);
o = throttleTime > TimeSpan.Zero
? o.Throttle(throttleTime, scheduler)
: o.ObserveOn(scheduler);
d.Add(
o.Subscribe(
v =>
{
using (this.scheduledTask)
{
}
isCalculatingSubject.OnNext(true);
this.scheduledTask = scheduler.ScheduleAsync(
async (s, t) =>
{
try
{
await s.Yield().ConfigureAwait(true);
IDiscriminatedUnion<object, T, Exception> result =
await
calculate(
new AsyncCalculationHelper(s, t), v.Item1, v.Item2).ConfigureAwait(true);
await s.Yield().ConfigureAwait(true);
resultSubject.OnNext(result);
}
catch (OperationCanceledException)
{
}
catch (Exception e)
{
resultSubject.OnNext(
DiscriminatedUnion.Second<object, T, Exception>(e));
}
isCalculatingSubject.OnNext(false);
});
}));
return d;
}));
}
/// <summary>
/// Initializes a new instance of the <see cref="CancellableAsyncCalculatedProperty{TFirst,TSecond,T}"/> class.
/// </summary>
/// <param name="info">
/// The serialization info.
/// </param>
/// <param name="context">
/// The serialization context.
/// </param>
[ContractVerification(false)]
// ReSharper disable UnusedParameter.Local
protected CancellableAsyncCalculatedProperty(SerializationInfo info, StreamingContext context)
// ReSharper restore UnusedParameter.Local
: this(
(IObservable<TFirst>)info.GetValue("p1", typeof(IObservable<TFirst>)),
(IObservable<TSecond>)info.GetValue("p2", typeof(IObservable<TSecond>)),
(TimeSpan)(info.GetValue("t", typeof(TimeSpan)) ?? default(TimeSpan)),
(Func<AsyncCalculationHelper, TFirst, TSecond, Task<T>>)
info.GetValue("f", typeof(Func<AsyncCalculationHelper, TFirst, TSecond, Task<T>>)),
(bool)info.GetValue("l", typeof(bool)))
{
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Gets the object data to serialize.
/// </summary>
/// <param name="info">
/// The serialization info.
/// </param>
/// <param name="context">
/// The serialization context.
/// </param>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("p1", this.firstProperty);
info.AddValue("p2", this.secondProperty);
info.AddValue("t", this.throttleTime);
info.AddValue("f", this.calculateValue);
info.AddValue("l", this.isLongRunningCalculation);
}
#endregion
#region Methods
/// <summary>
/// Disposes of the property.
/// </summary>
protected override void Dispose()
{
base.Dispose();
using (this.scheduledTask)
{
}
}
[ContractInvariantMethod]
private void CodeContractsInvariants()
{
Contract.Invariant(this.firstProperty != null);
Contract.Invariant(this.secondProperty != null);
Contract.Invariant(this.calculateValue != null);
}
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Networking/Requests/Messages/EncounterMessage.proto
#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 POGOProtos.Networking.Requests.Messages {
/// <summary>Holder for reflection information generated from POGOProtos/Networking/Requests/Messages/EncounterMessage.proto</summary>
public static partial class EncounterMessageReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Networking/Requests/Messages/EncounterMessage.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static EncounterMessageReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cj5QT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVxdWVzdHMvTWVzc2FnZXMvRW5j",
"b3VudGVyTWVzc2FnZS5wcm90bxInUE9HT1Byb3Rvcy5OZXR3b3JraW5nLlJl",
"cXVlc3RzLk1lc3NhZ2VzInMKEEVuY291bnRlck1lc3NhZ2USFAoMZW5jb3Vu",
"dGVyX2lkGAEgASgGEhYKDnNwYXduX3BvaW50X2lkGAIgASgJEhcKD3BsYXll",
"cl9sYXRpdHVkZRgDIAEoARIYChBwbGF5ZXJfbG9uZ2l0dWRlGAQgASgBYgZw",
"cm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Requests.Messages.EncounterMessage), global::POGOProtos.Networking.Requests.Messages.EncounterMessage.Parser, new[]{ "EncounterId", "SpawnPointId", "PlayerLatitude", "PlayerLongitude" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class EncounterMessage : pb::IMessage<EncounterMessage> {
private static readonly pb::MessageParser<EncounterMessage> _parser = new pb::MessageParser<EncounterMessage>(() => new EncounterMessage());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<EncounterMessage> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Networking.Requests.Messages.EncounterMessageReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EncounterMessage() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EncounterMessage(EncounterMessage other) : this() {
encounterId_ = other.encounterId_;
spawnPointId_ = other.spawnPointId_;
playerLatitude_ = other.playerLatitude_;
playerLongitude_ = other.playerLongitude_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EncounterMessage Clone() {
return new EncounterMessage(this);
}
/// <summary>Field number for the "encounter_id" field.</summary>
public const int EncounterIdFieldNumber = 1;
private ulong encounterId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong EncounterId {
get { return encounterId_; }
set {
encounterId_ = value;
}
}
/// <summary>Field number for the "spawn_point_id" field.</summary>
public const int SpawnPointIdFieldNumber = 2;
private string spawnPointId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string SpawnPointId {
get { return spawnPointId_; }
set {
spawnPointId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "player_latitude" field.</summary>
public const int PlayerLatitudeFieldNumber = 3;
private double playerLatitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double PlayerLatitude {
get { return playerLatitude_; }
set {
playerLatitude_ = value;
}
}
/// <summary>Field number for the "player_longitude" field.</summary>
public const int PlayerLongitudeFieldNumber = 4;
private double playerLongitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double PlayerLongitude {
get { return playerLongitude_; }
set {
playerLongitude_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as EncounterMessage);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(EncounterMessage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (EncounterId != other.EncounterId) return false;
if (SpawnPointId != other.SpawnPointId) return false;
if (PlayerLatitude != other.PlayerLatitude) return false;
if (PlayerLongitude != other.PlayerLongitude) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (EncounterId != 0UL) hash ^= EncounterId.GetHashCode();
if (SpawnPointId.Length != 0) hash ^= SpawnPointId.GetHashCode();
if (PlayerLatitude != 0D) hash ^= PlayerLatitude.GetHashCode();
if (PlayerLongitude != 0D) hash ^= PlayerLongitude.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (EncounterId != 0UL) {
output.WriteRawTag(9);
output.WriteFixed64(EncounterId);
}
if (SpawnPointId.Length != 0) {
output.WriteRawTag(18);
output.WriteString(SpawnPointId);
}
if (PlayerLatitude != 0D) {
output.WriteRawTag(25);
output.WriteDouble(PlayerLatitude);
}
if (PlayerLongitude != 0D) {
output.WriteRawTag(33);
output.WriteDouble(PlayerLongitude);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (EncounterId != 0UL) {
size += 1 + 8;
}
if (SpawnPointId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(SpawnPointId);
}
if (PlayerLatitude != 0D) {
size += 1 + 8;
}
if (PlayerLongitude != 0D) {
size += 1 + 8;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(EncounterMessage other) {
if (other == null) {
return;
}
if (other.EncounterId != 0UL) {
EncounterId = other.EncounterId;
}
if (other.SpawnPointId.Length != 0) {
SpawnPointId = other.SpawnPointId;
}
if (other.PlayerLatitude != 0D) {
PlayerLatitude = other.PlayerLatitude;
}
if (other.PlayerLongitude != 0D) {
PlayerLongitude = other.PlayerLongitude;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 9: {
EncounterId = input.ReadFixed64();
break;
}
case 18: {
SpawnPointId = input.ReadString();
break;
}
case 25: {
PlayerLatitude = input.ReadDouble();
break;
}
case 33: {
PlayerLongitude = input.ReadDouble();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Manager class.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Threading;
#pragma warning disable 612,618
namespace Lextm.SharpSnmpLib.Messaging
{
/// <summary>
/// SNMP manager component that provides SNMP operations.
/// </summary>
/// <remarks>
/// <para>Drag this component into your form in designer, or create an instance in code.</para>
/// <para>Currently only SNMP v1 and v2c operations are supported.</para>
/// </remarks>
[CLSCompliant(false)]
[Obsolete("Please use Messenger class instead.")]
public sealed class Manager
{
private const int DefaultPort = 161;
private readonly object _locker = new object();
private int _timeout = 5000;
private VersionCode _version;
/// <summary>
/// Initializes a new instance of the <see cref="Manager"/> class.
/// </summary>
public Manager()
{
MaxRepetitions = 10;
}
/// <summary>
/// Default protocol version for operations.
/// </summary>
/// <remarks>By default, the value is SNMP v1.</remarks>
public VersionCode DefaultVersion
{
get
{
return _version;
}
set
{
lock (_locker)
{
_version = value;
}
}
}
/// <summary>
/// Timeout value.
/// </summary>
/// <remarks>By default, the value is 5,000-milliseconds (5 seconds).</remarks>
public int Timeout
{
get
{
return _timeout;
}
set
{
Interlocked.Exchange(ref _timeout, value);
}
}
/// <summary>
/// Gets or sets the objects.
/// </summary>
/// <value>The objects.</value>
/// <remarks>Changed from 2.0: it will return null if not set.</remarks>
public IObjectRegistry Objects { get; set; }
/// <summary>
/// Gets a variable bind.
/// </summary>
/// <param name="endpoint">Endpoint.</param>
/// <param name="community">Community name.</param>
/// <param name="variable">Variable bind.</param>
/// <returns></returns>
public Variable GetSingle(IPEndPoint endpoint, string community, Variable variable)
{
var variables = new List<Variable> { variable };
return Messenger.Get(_version, endpoint, new OctetString(community), variables, _timeout)[0];
}
/// <summary>
/// Gets a variable bind.
/// </summary>
/// <param name="address">Address.</param>
/// <param name="community">Community name.</param>
/// <param name="variable">Variable bind.</param>
/// <returns></returns>
public Variable GetSingle(string address, string community, Variable variable)
{
return GetSingle(IPAddress.Parse(address), community, variable);
}
/// <summary>
/// Gets a variable bind.
/// </summary>
/// <param name="address">Address.</param>
/// <param name="community">Community name.</param>
/// <param name="variable">Variable bind.</param>
/// <returns></returns>
public Variable GetSingle(IPAddress address, string community, Variable variable)
{
return GetSingle(new IPEndPoint(address, DefaultPort), community, variable);
}
/// <summary>
/// Gets a list of variable binds.
/// </summary>
/// <param name="endpoint">Endpoint.</param>
/// <param name="community">Community name.</param>
/// <param name="variables">Variable binds.</param>
/// <returns></returns>
public IList<Variable> Get(IPEndPoint endpoint, string community, IList<Variable> variables)
{
return Messenger.Get(_version, endpoint, new OctetString(community), variables, _timeout);
}
/// <summary>
/// Gets a list of variable binds.
/// </summary>
/// <param name="address">Address.</param>
/// <param name="community">Community name.</param>
/// <param name="variables">Variable binds.</param>
/// <returns></returns>
public IList<Variable> Get(string address, string community, IList<Variable> variables)
{
return Get(IPAddress.Parse(address), community, variables);
}
/// <summary>
/// Gets a list of variable binds.
/// </summary>
/// <param name="address">Address.</param>
/// <param name="community">Community name.</param>
/// <param name="variables">Variable binds.</param>
/// <returns></returns>
public IList<Variable> Get(IPAddress address, string community, IList<Variable> variables)
{
return Get(new IPEndPoint(address, DefaultPort), community, variables);
}
/// <summary>
/// Sets a variable bind.
/// </summary>
/// <param name="endpoint">Endpoint.</param>
/// <param name="community">Community name.</param>
/// <param name="variable">Variable bind.</param>
/// <returns></returns>
public Variable SetSingle(IPEndPoint endpoint, string community, Variable variable)
{
var variables = new List<Variable> { variable };
return Messenger.Set(_version, endpoint, new OctetString(community), variables, _timeout)[0];
}
/// <summary>
/// Sets a variable bind.
/// </summary>
/// <param name="address">Address.</param>
/// <param name="community">Community name.</param>
/// <param name="variable">Variable bind.</param>
/// <returns></returns>
public Variable SetSingle(IPAddress address, string community, Variable variable)
{
return SetSingle(new IPEndPoint(address, DefaultPort), community, variable);
}
/// <summary>
/// Sets a variable bind.
/// </summary>
/// <param name="address">Address.</param>
/// <param name="community">Community name.</param>
/// <param name="variable">Variable bind.</param>
/// <returns></returns>
public Variable SetSingle(string address, string community, Variable variable)
{
return SetSingle(IPAddress.Parse(address), community, variable);
}
/// <summary>
/// Sets a list of variable binds.
/// </summary>
/// <param name="endpoint">Endpoint.</param>
/// <param name="community">Community name.</param>
/// <param name="variables">Variable binds.</param>
/// <returns></returns>
public IList<Variable> Set(IPEndPoint endpoint, string community, IList<Variable> variables)
{
return Messenger.Set(_version, endpoint, new OctetString(community), variables, _timeout);
}
/// <summary>
/// Sets a list of variable binds.
/// </summary>
/// <param name="address">Address.</param>
/// <param name="community">Community name.</param>
/// <param name="variables">Variable binds.</param>
/// <returns></returns>
public IList<Variable> Set(string address, string community, IList<Variable> variables)
{
return Set(IPAddress.Parse(address), community, variables);
}
/// <summary>
/// Sets a list of variable binds.
/// </summary>
/// <param name="address">Address.</param>
/// <param name="community">Community name.</param>
/// <param name="variables">Variable binds.</param>
/// <returns></returns>
public IList<Variable> Set(IPAddress address, string community, IList<Variable> variables)
{
return Set(new IPEndPoint(address, DefaultPort), community, variables);
}
/// <summary>
/// Gets a table of variables.
/// </summary>
/// <param name="endpoint">Endpoint.</param>
/// <param name="community">Community name.</param>
/// <param name="table">Table OID.</param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "Return", Justification = "ByDesign")]
public Variable[,] GetTable(IPEndPoint endpoint, string community, ObjectIdentifier table)
{
return Messenger.GetTable(DefaultVersion, endpoint, new OctetString(community), table, Timeout, MaxRepetitions, Objects);
}
/// <summary>
/// Gets or sets the max repetitions for GET BULK operations.
/// </summary>
/// <value>The max repetitions.</value>
public int MaxRepetitions { get; set; }
/// <summary>
/// Gets a table of variables.
/// </summary>
/// <param name="address">Address.</param>
/// <param name="community">Community name.</param>
/// <param name="table">Table OID.</param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "Return", Justification = "ByDesign")]
public Variable[,] GetTable(IPAddress address, string community, ObjectIdentifier table)
{
return GetTable(new IPEndPoint(address, DefaultPort), community, table);
}
/// <summary>
/// Gets a table of variables.
/// </summary>
/// <param name="address">Address.</param>
/// <param name="community">Community name.</param>
/// <param name="table">Table OID.</param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "Return", Justification = "ByDesign")]
public Variable[,] GetTable(string address, string community, ObjectIdentifier table)
{
return GetTable(IPAddress.Parse(address), community, table);
}
/// <summary>
/// Returns a <see cref="String"/> that represents this <see cref="Manager"/>.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "SNMP manager: timeout: {0}; version: {1}", Timeout.ToString(CultureInfo.InvariantCulture), DefaultVersion);
}
}
}
#pragma warning restore 612,618
| |
using System;
using System.Collections.Generic;
using OpenInvoicePeru.Comun;
using OpenInvoicePeru.Comun.Dto.Contratos;
using OpenInvoicePeru.Comun.Dto.Modelos;
using OpenInvoicePeru.Estructuras.CommonAggregateComponents;
using OpenInvoicePeru.Estructuras.CommonBasicComponents;
using OpenInvoicePeru.Estructuras.EstandarUbl;
using OpenInvoicePeru.Estructuras.SunatAggregateComponents;
namespace OpenInvoicePeru.Xml
{
public class ResumenDiarioXml : IDocumentoXml
{
IEstructuraXml IDocumentoXml.Generar(IDocumentoElectronico request)
{
var documento = (ResumenDiario)request;
var summary = new SummaryDocuments
{
Id = documento.IdDocumento,
IssueDate = Convert.ToDateTime(documento.FechaEmision),
ReferenceDate = Convert.ToDateTime(documento.FechaReferencia),
CustomizationId = "1.0",
UblVersionId = "2.0",
Signature = new SignatureCac
{
Id = documento.IdDocumento,
SignatoryParty = new SignatoryParty
{
PartyIdentification = new PartyIdentification
{
Id = new PartyIdentificationId
{
Value = documento.Emisor.NroDocumento
}
},
PartyName = new PartyName
{
Name = documento.Emisor.NombreLegal
}
},
DigitalSignatureAttachment = new DigitalSignatureAttachment
{
ExternalReference = new ExternalReference
{
Uri = $"{documento.Emisor.NroDocumento}-{documento.IdDocumento}"
}
}
},
AccountingSupplierParty = new AccountingSupplierParty
{
CustomerAssignedAccountId = documento.Emisor.NroDocumento,
AdditionalAccountId = documento.Emisor.TipoDocumento,
Party = new Party
{
PartyLegalEntity = new PartyLegalEntity
{
RegistrationName = documento.Emisor.NombreLegal
}
}
}
};
foreach (var grupo in documento.Resumenes)
{
var linea = new VoidedDocumentsLine
{
LineId = grupo.Id,
DocumentTypeCode = grupo.TipoDocumento,
DocumentSerialId = grupo.Serie,
StartDocumentNumberId = grupo.CorrelativoInicio,
EndDocumentNumberId = grupo.CorrelativoFin,
TotalAmount = new PayableAmount
{
CurrencyId = grupo.Moneda,
Value = grupo.TotalVenta
},
BillingPayments = new List<BillingPayment>()
{
new BillingPayment
{
PaidAmount = new PayableAmount
{
CurrencyId = grupo.Moneda,
Value = grupo.Gravadas
},
InstructionId = "01"
},
new BillingPayment
{
PaidAmount = new PayableAmount
{
CurrencyId = grupo.Moneda,
Value = grupo.Exoneradas
},
InstructionId = "02"
},
new BillingPayment
{
PaidAmount = new PayableAmount
{
CurrencyId = grupo.Moneda,
Value = grupo.Inafectas
},
InstructionId = "03"
},
},
AllowanceCharge = new AllowanceCharge
{
ChargeIndicator = true,
Amount = new PayableAmount
{
CurrencyId = grupo.Moneda,
Value = grupo.TotalDescuentos
}
},
TaxTotals = new List<TaxTotal>()
{
new TaxTotal
{
TaxAmount = new PayableAmount
{
CurrencyId = grupo.Moneda,
Value = grupo.TotalIsc
},
TaxSubtotal = new TaxSubtotal
{
TaxAmount = new PayableAmount
{
CurrencyId = grupo.Moneda,
Value = grupo.TotalIsc
},
TaxCategory = new TaxCategory
{
TaxScheme = new TaxScheme
{
Id = "2000",
Name = "ISC",
TaxTypeCode = "EXC"
}
}
}
},
new TaxTotal
{
TaxAmount = new PayableAmount
{
CurrencyId = grupo.Moneda,
Value = grupo.TotalIgv
},
TaxSubtotal = new TaxSubtotal
{
TaxAmount = new PayableAmount
{
CurrencyId = grupo.Moneda,
Value = grupo.TotalIgv
},
TaxCategory = new TaxCategory
{
TaxScheme = new TaxScheme
{
Id = "1000",
Name = "IGV",
TaxTypeCode = "VAT"
}
}
}
},
new TaxTotal
{
TaxAmount = new PayableAmount
{
CurrencyId = grupo.Moneda,
Value = grupo.TotalOtrosImpuestos
},
TaxSubtotal = new TaxSubtotal
{
TaxAmount = new PayableAmount
{
CurrencyId = grupo.Moneda,
Value = grupo.TotalOtrosImpuestos
},
TaxCategory = new TaxCategory
{
TaxScheme = new TaxScheme
{
Id = "9999",
Name = "OTROS",
TaxTypeCode = "OTH"
}
}
}
},
}
};
if (grupo.Exportacion > 0)
{
linea.BillingPayments.Add(new BillingPayment
{
PaidAmount = new PayableAmount
{
CurrencyId = grupo.Moneda,
Value = grupo.Exportacion
},
InstructionId = "04"
});
}
if (grupo.Gratuitas > 0)
{
linea.BillingPayments.Add(new BillingPayment
{
PaidAmount = new PayableAmount
{
CurrencyId = grupo.Moneda,
Value = grupo.Gratuitas
},
InstructionId = "05"
});
}
summary.SummaryDocumentsLines.Add(linea);
}
return summary;
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder Utilities
// File : DocumentationSource.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 06/05/2010
// Note : Copyright 2006-2010, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a class representing a documentation source such as an
// assembly, an XML comments file, a solution, or a project.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.0.0.0 08/02/2006 EFW Created the code
// 1.3.2.0 11/10/2006 EFW Added CommentsOnly property.
// 1.3.4.0 12/31/2006 EFW Converted path properties to FilePath objects
// 1.6.0.7 04/16/2008 EFW Added support for wildcards
// 1.8.0.0 06/23/2008 EFW Rewrote to support the MSBuild project format
// 1.8.0.4 06/05/2010 EFW Added support for getting build include status and
// configuration settings from the solution file.
//=============================================================================
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing.Design;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using SandcastleBuilder.Utils.Design;
namespace SandcastleBuilder.Utils
{
/// <summary>
/// This represents an assembly, an XML comments file, a Visual Studio
/// Solution (C#, VB.NET, or J#), or a Visual Studio solution containing
/// one or more C#, VB.NET or J# projects to use for building a help file.
/// </summary>
/// <remarks>Wildcards are supported in the <see cref="SourceFile"/>
/// property.</remarks>
[DefaultProperty("SourceFile")]
public class DocumentationSource : PropertyBasedCollectionItem
{
#region Private data members
//=====================================================================
private FilePath sourceFile;
private string configuration, platform;
private bool includeSubFolders;
// Regular expression used to parse solution files
private static Regex reExtractProjectGuids = new Regex(
"^Project\\(\"\\{(" +
"FAE04EC0-301F-11D3-BF4B-00C04F79EFBC|" + // C#
"F184B08F-C81C-45F6-A57F-5ABD9991F28F|" + // VB.NET
"8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942|" + // C++
"F2A71F9B-5D33-465A-A702-920D77279786|" + // F#
"E6FDF86B-F3D1-11D4-8576-0002A516ECE8" + // J#
")\\}\"\\) = \".*?\", \"(?!http)" +
"(?<Path>.*?proj)\", \"\\{(?<GUID>.*?)\\}\"", RegexOptions.Multiline);
#endregion
#region Properties
//=====================================================================
/// <summary>
/// This is used to get or set the project configuration to use when
/// the source path refers to a Visual Studio solution or project.
/// </summary>
/// <value>If not set, the configuration value from the owning help
/// file project will be used. This will be ignored for assembly
/// and XML comments file entries.</value>
[Category("Project"), Description("The configuration to use for a " +
"solution or project documentation source. If blank, the " +
"configuration from the owning help file project will be used."),
DefaultValue(null)]
public string Configuration
{
get { return configuration; }
set
{
base.CheckProjectIsEditable();
if(value != null)
value = value.Trim();
configuration = value;
}
}
/// <summary>
/// This is used to get or set the project platform to use when the
/// source path refers to a Visual Studio solution or project.
/// </summary>
/// <value>If not set, the platform value from the owning help file
/// project will be used. This will be ignored for assembly and XML
/// comments file entries.</value>
[Category("Project"), Description("The platform to use for a " +
"solution or project documentation source. If blank, the " +
"platform from the owning help file project will be used."),
DefaultValue(null)]
public string Platform
{
get { return platform; }
set
{
base.CheckProjectIsEditable();
if(value != null)
value = value.Trim();
platform = value;
}
}
/// <summary>
/// This is used to set or get the documentation source file path
/// </summary>
/// <value>Wildcards are supported. If used, all files matching
/// the wildcard will be included as long as their extension is one of
/// the following: .exe, .dll, .*proj, .sln.</value>
[Category("File"), Description("The path to the documentation source file(s)"),
MergableProperty(false), Editor(typeof(FilePathObjectEditor), typeof(UITypeEditor)),
RefreshProperties(RefreshProperties.All),
FileDialog("Select the documentation source",
"Documentation Sources (*.sln, *.*proj, *.dll, *.exe, *.xml)|*.sln;*.*proj;*.dll;*.exe;*.xml|" +
"Assemblies and Comments Files (*.dll, *.exe, *.xml)|*.dll;*.exe;*.xml|" +
"Library Files (*.dll)|*.dll|Executable Files (*.exe)|*.exe|" +
"XML Comments Files (*.xml)|*.xml|" +
"Visual Studio Solution Files (*.sln)|*.sln|" +
"Visual Studio Project Files (*.*proj)|*.*proj|" +
"All Files (*.*)|*.*", FileDialogType.FileOpen)]
public FilePath SourceFile
{
get { return sourceFile; }
set
{
if(value == null || value.Path.Length == 0)
throw new ArgumentException("A file path must be specified",
"value");
base.CheckProjectIsEditable();
sourceFile = value;
sourceFile.PersistablePathChanging += new EventHandler(
sourceFile_PersistablePathChanging);
}
}
/// <summary>
/// This is used to get or set whether subfolders are included when
/// searching for files if the <see cref="SourceFile" /> value
/// contains wildcards.
/// </summary>
/// <value>If set to true and the source file value contains wildcards,
/// subfolders will be included. If set to false, the default, or the
/// source file value does not contain wildcards, only the top-level
/// folder is included in the search.</value>
[Category("File"), Description("True to include subfolders in " +
"wildcard searches or false to only search the top-level folder."),
DefaultValue(false)]
public bool IncludeSubFolders
{
get { return includeSubFolders; }
set
{
base.CheckProjectIsEditable();
includeSubFolders = value;
}
}
/// <summary>
/// This returns a description of the entry suitable for display in a
/// bound list control.
/// </summary>
[Browsable(false)]
public string SourceDescription
{
get
{
string path, config = null, subFolders = null, ext;
char[] wildcards = new char[] { '*', '?' };
path = Path.GetFileName(sourceFile.PersistablePath);
if(path[0] == '*' && path[1] == '.')
path = sourceFile.PersistablePath;
ext = Path.GetExtension(path).ToLower(CultureInfo.InvariantCulture);
if((ext.IndexOfAny(wildcards) != -1 || ext == ".sln" ||
ext.EndsWith("proj", StringComparison.Ordinal)) &&
(!String.IsNullOrEmpty(configuration) ||
!String.IsNullOrEmpty(platform)))
config = String.Format(CultureInfo.InvariantCulture, " ({0}|{1})",
(String.IsNullOrEmpty(configuration)) ? "$(Configuration)" : configuration,
(String.IsNullOrEmpty(platform)) ? "$(Platform)" : platform);
if(path.IndexOfAny(wildcards) != -1 && includeSubFolders)
subFolders = " including subfolders";
return String.Concat(path, config, subFolders);
}
}
#endregion
#region Private helper methods
//=====================================================================
/// <summary>
/// This is used to handle changes in the <see cref="FilePath" />
/// properties such that the source path gets stored in the project
/// file.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void sourceFile_PersistablePathChanging(object sender, EventArgs e)
{
base.CheckProjectIsEditable();
}
/// <summary>
/// Extract all project files from the given Visual Studio solution file
/// </summary>
/// <param name="solutionFile">The Visual Studio solution from which to
/// extract the projects.</param>
/// <param name="configuration">The configuration to use</param>
/// <param name="platform">The platform to use</param>
/// <param name="projectFiles">The collection used to return the
/// extracted projects.</param>
private static void ExtractProjectsFromSolution(string solutionFile,
string configuration, string platform, Collection<ProjectFileConfiguration> projectFiles)
{
Regex reIsInBuild;
Match buildMatch;
string solutionContent, folder = Path.GetDirectoryName(solutionFile);
using(StreamReader sr = new StreamReader(solutionFile))
{
solutionContent = sr.ReadToEnd();
sr.Close();
}
// Only add projects that are likely to contain assemblies
MatchCollection projects = reExtractProjectGuids.Matches(solutionContent);
foreach(Match solutionMatch in projects)
{
// See if the project is included in the build and get the configuration and platform
reIsInBuild = new Regex(String.Format(CultureInfo.InvariantCulture,
@"\{{{0}\}}\.{1}\|{2}\.Build\.0\s*=\s*(?<Configuration>.*?)\|(?<Platform>.*)",
solutionMatch.Groups["GUID"].Value, configuration, platform), RegexOptions.IgnoreCase);
buildMatch = reIsInBuild.Match(solutionContent);
// If the platform is "AnyCPU" and it didn't match, try "Any CPU" (with a space)
if(!buildMatch.Success && platform.Equals("AnyCPU", StringComparison.OrdinalIgnoreCase))
{
reIsInBuild = new Regex(String.Format(CultureInfo.InvariantCulture,
@"\{{{0}\}}\.{1}\|Any CPU\.Build\.0\s*=\s*(?<Configuration>.*?)\|(?<Platform>.*)",
solutionMatch.Groups["GUID"].Value, configuration), RegexOptions.IgnoreCase);
buildMatch = reIsInBuild.Match(solutionContent);
}
if(buildMatch.Success)
projectFiles.Add(new ProjectFileConfiguration(Path.Combine(folder,
solutionMatch.Groups["Path"].Value))
{
Configuration = buildMatch.Groups["Configuration"].Value.Trim(),
Platform = buildMatch.Groups["Platform"].Value.Trim()
});
}
}
#endregion
#region Constructor
//=====================================================================
/// <summary>
/// Internal constructor
/// </summary>
/// <param name="filename">The filename of the documentation source</param>
/// <param name="projConfig">The configuration to use for projects</param>
/// <param name="projPlatform">The platform to use for projects</param>
/// <param name="subFolders">True to include subfolders, false to
/// only search the top-level folder.</param>
/// <param name="project">The owning project</param>
internal DocumentationSource(string filename, string projConfig,
string projPlatform, bool subFolders, SandcastleProject project) :
base(project)
{
sourceFile = new FilePath(filename, project);
sourceFile.PersistablePathChanging += sourceFile_PersistablePathChanging;
configuration = projConfig;
platform = projPlatform;
includeSubFolders = subFolders;
}
#endregion
#region Equality and ToString methods
//=====================================================================
/// <summary>
/// See if specified item equals this one
/// </summary>
/// <param name="obj">The object to compare to this one</param>
/// <returns>True if equal, false if not</returns>
/// <remarks>For documentation sources, equality is based solely on
/// the <see cref="SourceFile" /> value. The configuration and
/// platform settings are not considered.</remarks>
public override bool Equals(object obj)
{
DocumentationSource ds = obj as DocumentationSource;
if(ds == null)
return false;
return (this == ds || this.SourceFile == ds.SourceFile);
}
/// <summary>
/// Get a hash code for this item
/// </summary>
/// <returns>Returns the hash code for the assembly path and
/// XML comments path.</returns>
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
/// <summary>
/// Return a string representation of the item
/// </summary>
/// <returns>Returns the assembly path and XML comments path separated
/// by a comma.</returns>
public override string ToString()
{
return this.SourceDescription;
}
#endregion
#region Wildcard expansion methods
//=====================================================================
/// <summary>
/// This returns a collection of assemblies based on the specified
/// wildcard.
/// </summary>
/// <param name="wildcard">The wildcard to use to find assemblies.</param>
/// <param name="includeSubfolders">If true and the wildcard parameter
/// includes wildcard characters, subfolders will be searched as well.
/// If not, only the top-level folder is searched.</param>
/// <returns>A list of assemblies matching the wildcard</returns>
public static Collection<string> Assemblies(string wildcard, bool includeSubfolders)
{
Collection<string> assemblies = new Collection<string>();
SearchOption searchOpt = SearchOption.TopDirectoryOnly;
string dirName;
dirName = Path.GetDirectoryName(wildcard);
if(Directory.Exists(dirName))
{
if(wildcard.IndexOfAny(new char[] { '*', '?' }) != -1 && includeSubfolders)
searchOpt = SearchOption.AllDirectories;
foreach(string f in Directory.GetFiles(dirName, Path.GetFileName(wildcard), searchOpt))
if(f.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
assemblies.Add(f);
}
return assemblies;
}
/// <summary>
/// This returns a collection of XML comments files based on the
/// specified wildcard.
/// </summary>
/// <param name="wildcard">The wildcard to use to find comments
/// files.</param>
/// <param name="includeSubfolders">If true and the wildcard parameter
/// includes wildcard characters, subfolders will be searched as well.
/// If not, only the top-level folder is searched.</param>
/// <returns>A list of XML comments files matching the wildcard</returns>
public static Collection<string> CommentsFiles(string wildcard, bool includeSubfolders)
{
Collection<string> comments = new Collection<string>();
SearchOption searchOpt = SearchOption.TopDirectoryOnly;
string dirName;
dirName = Path.GetDirectoryName(wildcard);
if(Directory.Exists(dirName))
{
if(wildcard.IndexOfAny(new char[] { '*', '?' }) != -1 && includeSubfolders)
searchOpt = SearchOption.AllDirectories;
foreach(string f in Directory.GetFiles(dirName, Path.GetFileName(wildcard), searchOpt))
if(f.EndsWith(".xml", StringComparison.OrdinalIgnoreCase))
comments.Add(f);
}
return comments;
}
/// <summary>
/// This returns a collection of MSBuild project filenames based on the
/// specified wildcard.
/// </summary>
/// <param name="wildcard">The wildcard to use to find solutions and
/// projects.</param>
/// <param name="includeSubfolders">If true and the wildcard parameter
/// includes wildcard characters, subfolders will be searched as well.
/// If not, only the top-level folder is searched.</param>
/// <param name="configuration">The configuration to use</param>
/// <param name="platform">The platform to use</param>
/// <returns>A list of projects matching the wildcard. Any solution
/// files (.sln) found are returned last, each followed by the projects
/// extracted from it.</returns>
public static Collection<ProjectFileConfiguration> Projects(string wildcard,
bool includeSubfolders, string configuration, string platform)
{
List<string> solutions = new List<string>();
Collection<ProjectFileConfiguration> projects = new Collection<ProjectFileConfiguration>();
SearchOption searchOpt = SearchOption.TopDirectoryOnly;
string dirName;
dirName = Path.GetDirectoryName(wildcard);
if(Directory.Exists(dirName))
{
if(wildcard.IndexOfAny(new char[] { '*', '?' }) != -1 && includeSubfolders)
searchOpt = SearchOption.AllDirectories;
foreach(string f in Directory.GetFiles(dirName, Path.GetFileName(wildcard), searchOpt))
{
if(f.EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
solutions.Add(f);
else
if(f.EndsWith("proj", StringComparison.OrdinalIgnoreCase))
projects.Add(new ProjectFileConfiguration(f));
}
// Add solutions last followed by the projects that they contain.
// The caller can then set solution specific values in each project
// related to the solution.
foreach(string s in solutions)
{
projects.Add(new ProjectFileConfiguration(s));
ExtractProjectsFromSolution(s, configuration, platform, projects);
}
}
return projects;
}
#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;
using System.Collections.Generic;
using System.Reflection;
using System.Xaml;
using MS.Internal.Xaml.Parser;
namespace MS.Internal.Xaml.Context
{
internal class XamlParserContext : XamlContext
{
private XamlContextStack<XamlParserFrame> _stack;
private Dictionary<string, string> _prescopeNamespaces;
public bool AllowProtectedMembersOnRoot { get; set; }
public Func<string, string> XmlNamespaceResolver { get; set; }
public XamlParserContext(XamlSchemaContext schemaContext, Assembly localAssembly)
:base(schemaContext)
{
_stack = new XamlContextStack<XamlParserFrame>(()=>new XamlParserFrame());
_prescopeNamespaces = new Dictionary<string, string>();
base._localAssembly = localAssembly;
}
// ----- abstracts overriden from XamlContext.
public override void AddNamespacePrefix(String prefix, string xamlNS)
{
_prescopeNamespaces.Add(prefix, xamlNS);
}
public string FindNamespaceByPrefixInParseStack(String prefix)
{
string xamlNs;
if (null != _prescopeNamespaces)
{
if (_prescopeNamespaces.TryGetValue(prefix, out xamlNs))
{
return xamlNs;
}
}
XamlParserFrame frame = _stack.CurrentFrame;
while (frame.Depth > 0)
{
if (frame.TryGetNamespaceByPrefix(prefix, out xamlNs))
{
return xamlNs;
}
frame = (XamlParserFrame)frame.Previous;
}
return null;
}
public override string FindNamespaceByPrefix(String prefix)
{
// For proper operation of some corner senarios the XmlNamespaceResolver
// must be set. But if it isn't we fall back to a look in our own stack.
// Senarios that REQUIRE an XmlNamespaceResolver
// 1) Prefix defs that ONLY exist in the XmlNsManager are only found this way
// 2) Prefix defs on MarkupCompat Tags have effect but don't appear
// in the Xml node stream the XAML parser sees.
// But for normal XAML the XmlNamespaceResolver does not need to be used.
if (XmlNamespaceResolver != null)
{
return XmlNamespaceResolver(prefix);
}
return FindNamespaceByPrefixInParseStack(prefix);
}
public override IEnumerable<NamespaceDeclaration> GetNamespacePrefixes()
{
XamlParserFrame frame = _stack.CurrentFrame;
Dictionary<string, string> keys = new Dictionary<string, string>();
while (frame.Depth > 0)
{
if (frame._namespaces != null)
{
foreach (NamespaceDeclaration namespaceDeclaration in frame.GetNamespacePrefixes())
{
if (!keys.ContainsKey(namespaceDeclaration.Prefix))
{
keys.Add(namespaceDeclaration.Prefix, null);
yield return namespaceDeclaration;
}
}
}
frame = (XamlParserFrame)frame.Previous;
}
if (_prescopeNamespaces != null)
{
foreach (KeyValuePair<string, string> kvp in _prescopeNamespaces)
{
if (!keys.ContainsKey(kvp.Key))
{
keys.Add(kvp.Key, null);
yield return new NamespaceDeclaration(kvp.Value, kvp.Key);
}
}
}
}
// Only pass rootObjectType if the member is being looked up on the root object
internal override bool IsVisible(XamlMember member, XamlType rootObjectType)
{
if (member == null)
{
return false;
}
Type allowProtectedForType = null;
if (AllowProtectedMembersOnRoot && rootObjectType != null)
{
allowProtectedForType = rootObjectType.UnderlyingType;
}
// First check if the property setter is visible
if (member.IsWriteVisibleTo(LocalAssembly, allowProtectedForType))
{
return true;
}
// If the property setter is not visible, but the property getter is, treat the property
// as if it were read-only
if (member.IsReadOnly || (member.Type != null && member.Type.IsUsableAsReadOnly))
{
return member.IsReadVisibleTo(LocalAssembly, allowProtectedForType);
}
return false;
}
// ----- new public methods.
public void PushScope()
{
_stack.PushScope();
if (_prescopeNamespaces.Count > 0)
{
_stack.CurrentFrame.SetNamespaces(_prescopeNamespaces);
_prescopeNamespaces = new Dictionary<string, string>();
}
}
public void PopScope()
{
_stack.PopScope();
}
internal void InitBracketCharacterCacheForType(XamlType extensionType)
{
CurrentEscapeCharacterMapForMarkupExtension = SchemaContext.InitBracketCharacterCacheForType(extensionType);
}
/// <summary>
/// Finds the list of parameters of the constructor with the most number
/// of arguments.
/// </summary>
internal void InitLongestConstructor(XamlType xamlType)
{
IEnumerable<ConstructorInfo> constructors = xamlType.GetConstructors();
ParameterInfo[] constructorParameters = null;
int parameterCount = 0;
foreach (ConstructorInfo ctr in constructors)
{
ParameterInfo[] parInfo = ctr.GetParameters();
if (parInfo.Length >= parameterCount)
{
parameterCount = parInfo.Length;
constructorParameters = parInfo;
}
}
CurrentLongestConstructorOfMarkupExtension = constructorParameters;
}
// FxCop says this is never called
//public int Depth
//{
// get { return _stack.Depth; }
//}
public XamlType CurrentType
{
get { return _stack.CurrentFrame.XamlType; }
set { _stack.CurrentFrame.XamlType = value; }
}
internal BracketModeParseParameters CurrentBracketModeParseParameters
{
get { return _stack.CurrentFrame.BracketModeParseParameters; }
set { _stack.CurrentFrame.BracketModeParseParameters = value; }
}
internal ParameterInfo[] CurrentLongestConstructorOfMarkupExtension
{
get { return _stack.CurrentFrame.LongestConstructorOfCurrentMarkupExtensionType; }
set { _stack.CurrentFrame.LongestConstructorOfCurrentMarkupExtensionType = value; }
}
internal Dictionary<string, SpecialBracketCharacters> CurrentEscapeCharacterMapForMarkupExtension
{
get { return _stack.CurrentFrame.EscapeCharacterMapForMarkupExtension; }
set { _stack.CurrentFrame.EscapeCharacterMapForMarkupExtension = value; }
}
// This property refers to a namespace specified explicitly in the XAML document.
// If this is an implicit type (e.g. GO, x:Data, implicit array) just leave it as null.
public string CurrentTypeNamespace
{
get { return _stack.CurrentFrame.TypeNamespace; }
set { _stack.CurrentFrame.TypeNamespace = value; }
}
public bool CurrentInContainerDirective
{
get { return _stack.CurrentFrame.InContainerDirective; }
set { _stack.CurrentFrame.InContainerDirective = value; }
}
// FxCop says this is not called
//public XamlType ParentType
//{
// get { return _stack.PreviousFrame.XamlType; }
//}
public XamlMember CurrentMember
{
get { return _stack.CurrentFrame.Member; }
set { _stack.CurrentFrame.Member = value; }
}
// FxCop says this is not called
//public XamlProperty MemberProperty
//{
// get { return _stack.PreviousFrame.Member; }
//}
public int CurrentArgCount
{
get { return _stack.CurrentFrame.CtorArgCount; }
set { _stack.CurrentFrame.CtorArgCount = value; }
}
public bool CurrentForcedToUseConstructor
{
get { return _stack.CurrentFrame.ForcedToUseConstructor; }
set { _stack.CurrentFrame.ForcedToUseConstructor = value; }
}
public bool CurrentInItemsProperty
{
get { return _stack.CurrentFrame.Member == XamlLanguage.Items; }
}
public bool CurrentInInitProperty
{
get { return _stack.CurrentFrame.Member == XamlLanguage.Initialization; }
}
public bool CurrentInUnknownContent
{
get { return _stack.CurrentFrame.Member == XamlLanguage.UnknownContent; }
}
public bool CurrentInImplicitArray
{
get { return _stack.CurrentFrame.InImplicitArray; }
set { _stack.CurrentFrame.InImplicitArray = value; }
}
public bool CurrentInCollectionFromMember
{
get { return _stack.CurrentFrame.InCollectionFromMember; }
set { _stack.CurrentFrame.InCollectionFromMember = value; }
}
public XamlType CurrentPreviousChildType
{
get { return _stack.CurrentFrame.PreviousChildType; }
set { _stack.CurrentFrame.PreviousChildType = value; }
}
public bool CurrentMemberIsWriteVisible()
{
Type allowProtectedForType = null;
if (AllowProtectedMembersOnRoot && _stack.Depth == 1)
{
allowProtectedForType = CurrentType.UnderlyingType;
}
return CurrentMember.IsWriteVisibleTo(LocalAssembly, allowProtectedForType);
}
public bool CurrentTypeIsRoot
{
get { return _stack.CurrentFrame.XamlType != null && _stack.Depth == 1; }
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
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>
/// HttpServerFailure operations.
/// </summary>
public partial class HttpServerFailure : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpServerFailure
{
/// <summary>
/// Initializes a new instance of the HttpServerFailure class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public HttpServerFailure(AutoRestHttpInfrastructureTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHttpInfrastructureTestService
/// </summary>
public AutoRestHttpInfrastructureTestService Client { get; private set; }
/// <summary>
/// Return 501 status code - should be represented in the client as an error
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Error>> Head501WithHttpMessagesAsync(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("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Head501", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/501").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("HEAD");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 501 status code - should be represented in the client as an error
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Error>> Get501WithHttpMessagesAsync(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("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get501", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/501").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 505 status code - should be represented in the client as an error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Error>> Post505WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Post505", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/505").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(booleanValue != null)
{
_requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.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();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 505 status code - should be represented in the client as an error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Error>> Delete505WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete505", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/505").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(booleanValue != null)
{
_requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.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();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//
// (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.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using Autodesk.Revit.DB;
using System.Drawing.Drawing2D;
namespace Revit.SDK.Samples.NewHostedSweep.CS
{
/// <summary>
/// This form is intent to fetch edges for hosted sweep creation or modification.
/// It contains a picture box for geometry preview and a tree view to list all the edges
/// which hosted sweep can be created on.
/// If the user mouse-over an edge where a hosted sweep can be created, the edge will be
/// highlighted in yellow. If user clicks on the highlighted edge, the edge will
/// be marked as selected in red color. Click it again to un-select, the color will turn back.
/// Edge selection from preview box will be reflected in edge list and vice versa.
/// The geometry displayed in the picture box can be rotated with left mouse or
/// arrow keys (up, down, left and right) and zoomed with right mouse.
/// </summary>
public partial class EdgeFetchForm : System.Windows.Forms.Form
{
#region Fields and Constructors
/// <summary>
/// Contains all the data need to fetch edges.
/// </summary>
private CreationData m_creationData;
/// <summary>
/// Flag to indicate whether or not we should cancel expand or collapse
/// the tree-node which contains children.
/// </summary>
private bool m_cancelExpandOrCollapse;
/// <summary>
/// Active element displayed in the preview.
/// </summary>
private Autodesk.Revit.DB.Element m_activeElem;
/// <summary>
/// Yield rotation and scale transformation for current geometry display.
/// </summary>
private TrackBall m_trackBall;
/// <summary>
/// Move the Graphics origin to preview center and flip its y-Axis.
/// </summary>
private Matrix m_centerMatrix;
/// <summary>
/// Default constructor.
/// </summary>
public EdgeFetchForm()
{
InitializeComponent();
}
/// <summary>
/// Customize constructor.
/// </summary>
/// <param name="creationData"></param>
public EdgeFetchForm(CreationData creationData)
: this()
{
m_creationData = creationData;
treeViewHost.StateImageList = imageListForCheckBox;
m_trackBall = new TrackBall();
}
#endregion
#region Initialize Methods
/// <summary>
/// Initialize the combo box data source with Autodesk.Revit.DB.
/// e.g. FasciaTypes, GutterTypes, SlabEdgeTypes, and so on.
/// </summary>
private void InitializeTypes()
{
List<object> objects = new List<object>();
object selected = null;
foreach (object obj in m_creationData.Creator.AllTypes)
{
objects.Add(obj);
if (m_creationData.Symbol != null)
{
if ((obj as Autodesk.Revit.DB.ElementType).Id.IntegerValue == m_creationData.Symbol.Id.IntegerValue)
{
selected = obj;
}
}
}
comboBoxTypes.DataSource = objects;
comboBoxTypes.DisplayMember = "Name";
if (selected != null)
comboBoxTypes.SelectedItem = selected;
}
/// <summary>
/// Initialize the TreeView: create a tree according to geometry edges
/// and set each node's check status to unchecked.
/// </summary>
private void InitializeTree()
{
HostedSweepCreator creator = m_creationData.Creator;
TreeNode rootNode = new TreeNode();
rootNode.StateImageIndex = (int)CheckState.Unchecked;
foreach (KeyValuePair<Autodesk.Revit.DB.Element, List<Edge>> pair in creator.SupportEdges)
{
Autodesk.Revit.DB.Element elem = pair.Key;
TreeNode elemNode = new TreeNode("[Id:" + elem.Id.IntegerValue + "] " + elem.Name);
elemNode.StateImageIndex = (int)CheckState.Unchecked;
rootNode.Nodes.Add(elemNode);
elemNode.Tag = elem;
int i = 1;
foreach (Edge edge in pair.Value)
{
TreeNode edgeNode = new TreeNode("Edge " + i);
edgeNode.StateImageIndex = (int)CheckState.Unchecked;
edgeNode.Tag = edge;
elemNode.Nodes.Add(edgeNode);
++i;
}
}
rootNode.Text = "Roofs";
if (creator is SlabEdgeCreator)
{
rootNode.Text = "Floors";
}
treeViewHost.Nodes.Add(rootNode);
treeViewHost.TopNode.Expand();
}
/// <summary>
/// Initialize element geometry.
/// </summary>
private void InitializeElementGeometry()
{
foreach (ElementGeometry elemGeom in m_creationData.Creator.ElemGeomDic.Values)
{
elemGeom.InitializeTransform(pictureBoxPreview.Width * 0.8, pictureBoxPreview.Height * 0.8);
elemGeom.ResetEdgeStates();
}
}
/// <summary>
/// Initialize tree check states according to edges which hosted sweep can be created on.
/// </summary>
private void InitializeTreeCheckStates()
{
if (m_creationData.EdgesForHostedSweep.Count == 0) return;
// Initialize edge binding selection state
foreach(Edge edge in m_creationData.EdgesForHostedSweep)
{
foreach(ElementGeometry elemGeom in m_creationData.Creator.ElemGeomDic.Values)
{
if(elemGeom.EdgeBindingDic.ContainsKey(edge))
{
elemGeom.EdgeBindingDic[edge].IsSelected = true;
}
}
}
// Initialize tree node selection state
// check on all the edges on which we created hostd sweeps
TreeNode root = treeViewHost.Nodes[0];
foreach(TreeNode elemNode in root.Nodes)
{
foreach(TreeNode edgeNode in elemNode.Nodes)
{
Edge edge = edgeNode.Tag as Edge;
if(m_creationData.EdgesForHostedSweep.IndexOf(edge) != -1)
{
edgeNode.StateImageIndex = (int)CheckState.Checked;
UpdateParent(edgeNode);
}
}
}
}
/// <summary>
/// Initialize text properties of this form.
/// </summary>
private void InitializeText()
{
this.Text = "Pick edges for " + m_creationData.Creator.Name;
this.label.Text = "Select a type for " + m_creationData.Creator.Name;
this.groupBoxEdges.Text = "All edges for " + m_creationData.Creator.Name;
}
/// <summary>
/// Initialize something related to the geometry preview.
/// </summary>
private void InitializePreview()
{
m_centerMatrix = new Matrix(1, 0, 0, -1,
(float)pictureBoxPreview.Width / 2.0f, (float)pictureBoxPreview.Height / 2.0f);
this.KeyPreview = true;
foreach (Autodesk.Revit.DB.Element elem in m_creationData.Creator.ElemGeomDic.Keys)
{
m_activeElem = elem;
break;
}
}
#endregion
#region Auxiliary Methods
/// <summary>
/// Extract the checked edges in the whole tree to CreationData.EdgesForHostedSweep.
/// </summary>
private void ExtractCheckedEdgesAndSelectedSymbol()
{
m_creationData.EdgesForHostedSweep.Clear();
TreeNode rootNode = treeViewHost.Nodes[0];
foreach (TreeNode hostNode in rootNode.Nodes)
{
foreach (TreeNode edgeNode in hostNode.Nodes)
{
if (edgeNode.StateImageIndex == (int)CheckState.Checked)
m_creationData.EdgesForHostedSweep.Add(edgeNode.Tag as Edge);
}
}
m_creationData.Symbol = comboBoxTypes.SelectedItem as Autodesk.Revit.DB.ElementType;
}
/// <summary>
/// Update tree node check status, it will impact its children and parents' status.
/// </summary>
/// <param name="node">Tree node to update</param>
/// <param name="state">CheckState value</param>
private void UpdateNodeCheckStatus(TreeNode node, CheckState state)
{
node.StateImageIndex = (int)state;
if(node.Tag != null && node.Tag is Edge && m_activeElem != null)
{
Edge edge = node.Tag as Edge;
Autodesk.Revit.DB.Element elem = node.Parent.Tag as Autodesk.Revit.DB.Element;
ElementGeometry elemGeom = m_creationData.Creator.ElemGeomDic[elem];
elemGeom.EdgeBindingDic[edge].IsSelected =
(node.StateImageIndex == (int)CheckState.Checked);
}
UpdateChildren(node);
UpdateParent(node);
}
/// <summary>
/// Recursively update tree children's status to match its parent status.
/// </summary>
/// <param name="node">Parent node whose children will be updated</param>
private void UpdateChildren(TreeNode node)
{
foreach (TreeNode child in node.Nodes)
{
if (child.StateImageIndex != node.StateImageIndex)
{
child.StateImageIndex = node.StateImageIndex;
if(m_activeElem != null && child.Tag != null && child.Tag is Edge)
{
Edge edge = child.Tag as Edge;
Autodesk.Revit.DB.Element elem = child.Parent.Tag as Autodesk.Revit.DB.Element;
ElementGeometry elemGeom = m_creationData.Creator.ElemGeomDic[elem];
elemGeom.EdgeBindingDic[edge].IsSelected =
(child.StateImageIndex == (int)CheckState.Checked);
}
}
UpdateChildren(child);
}
}
/// <summary>
/// Recursively update tree parent's status to match its children status.
/// </summary>
/// <param name="node">Child whose parents will be updated</param>
private void UpdateParent(TreeNode node)
{
TreeNode parent = node.Parent;
if (parent == null) return;
foreach (TreeNode brother in parent.Nodes)
{
if (brother.StateImageIndex != node.StateImageIndex)
{
parent.StateImageIndex = (int)CheckState.Indeterminate;
UpdateParent(parent);
return;
}
}
parent.StateImageIndex = node.StateImageIndex;
UpdateParent(parent);
}
/// <summary>
/// Switch geometry displayed in the preview according to the tree node.
/// </summary>
/// <param name="node">Tree node to active</param>
private void ActiveNode(TreeNode node)
{
if (node.Tag == null) return;
if (node.Tag is Autodesk.Revit.DB.Element)
m_activeElem = node.Tag as Autodesk.Revit.DB.Element;
else if (node.Tag is Edge)
{
m_activeElem = node.Parent.Tag as Autodesk.Revit.DB.Element;
}
}
/// <summary>
/// Clear Highlighted status of all highlighted edges.
/// </summary>
private void ClearAllHighLight()
{
if (m_activeElem == null) return;
ElementGeometry elemGeom = m_creationData.Creator.ElemGeomDic[m_activeElem];
foreach (Edge edge in m_creationData.Creator.SupportEdges[m_activeElem])
{
elemGeom.EdgeBindingDic[edge].IsHighLighted = false;
}
}
/// <summary>
/// Get the related tree node of an edit
/// </summary>
/// <param name="edge">Given edge to find its tree-node</param>
/// <returns>Tree-node matched with the given edge</returns>
private TreeNode GetEdgeTreeNode(Edge edge)
{
TreeNode result = null;
TreeNode root = treeViewHost.Nodes[0];
Stack<TreeNode> todo = new Stack<TreeNode>();
todo.Push(root);
while (todo.Count > 0)
{
TreeNode node = todo.Pop();
if (node.Tag != null && node.Tag is Edge && (node.Tag as Edge) == edge)
{
result = node;
break;
}
foreach (TreeNode tmpNode in node.Nodes)
{
todo.Push(tmpNode);
}
}
return result;
}
#endregion
#region Event handles
/// <summary>
/// Extract checked edges and verify there are edges
/// checked in the treeView, if there aren't edges to be checked, complain
/// about it with a message box, otherwise close this from.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonOK_Click(object sender, EventArgs e)
{
ExtractCheckedEdgesAndSelectedSymbol();
if (m_creationData.EdgesForHostedSweep.Count == 0)
{
MessageBox.Show("At least one edge should be selected!");
return;
}
this.DialogResult = DialogResult.OK;
this.Close();
}
/// <summary>
/// Close this form.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
/// <summary>
/// This form Load event handle, all the initializations will be in here.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void EdgeFetch_Load(object sender, EventArgs e)
{
InitializeTypes();
InitializeTree();
InitializeElementGeometry();
InitializeTreeCheckStates();
InitializeText();
InitializePreview();
}
/// <summary>
/// Suppress the default behaviors that double-click
/// on a tree-node which contains children will make the tree-node collapse or expand.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void treeViewHost_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
{
if (m_cancelExpandOrCollapse)
e.Cancel = true;
m_cancelExpandOrCollapse = false;
}
/// <summary>
/// Suppress the default behaviors that double-click
/// on a tree-node which contains children will make the tree-node collapse or expand.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void treeViewHost_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
if (m_cancelExpandOrCollapse)
e.Cancel = true;
m_cancelExpandOrCollapse = false;
}
/// <summary>
/// Draw the geometry.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pictureBoxPreview_Paint(object sender, PaintEventArgs e)
{
if (m_activeElem == null) return;
ElementGeometry elemGeo = null;
if (!m_creationData.Creator.ElemGeomDic.TryGetValue(m_activeElem, out elemGeo)) return;
e.Graphics.Transform = m_centerMatrix;
e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
elemGeo.Draw(e.Graphics);
}
/// <summary>
/// Initialize the track ball.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pictureBoxPreview_MouseDown(object sender, MouseEventArgs e)
{
m_trackBall.OnMouseDown(pictureBoxPreview.Width, pictureBoxPreview.Height, e);
}
/// <summary>
/// Rotate or zoom the displayed geometry, or highlight the edge under the mouse location.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pictureBoxPreview_MouseMove(object sender, MouseEventArgs e)
{
if (m_activeElem == null) return;
m_trackBall.OnMouseMove(e);
if (e.Button == MouseButtons.Left)
{
m_creationData.Creator.ElemGeomDic[m_activeElem].Rotation *= m_trackBall.Rotation;
pictureBoxPreview.Refresh();
}
else if (e.Button == MouseButtons.Right)
{
m_creationData.Creator.ElemGeomDic[m_activeElem].Scale *= m_trackBall.Scale;
pictureBoxPreview.Refresh();
}
if (e.Button == MouseButtons.None)
{
ClearAllHighLight();
pictureBoxPreview.Refresh();
Matrix mat = (Matrix)m_centerMatrix.Clone();
mat.Invert();
PointF[] pts = new PointF[1] { e.Location };
mat.TransformPoints(pts);
ElementGeometry elemGeom = m_creationData.Creator.ElemGeomDic[m_activeElem];
foreach (Edge edge in m_creationData.Creator.SupportEdges[m_activeElem])
{
if (elemGeom.EdgeBindingDic.ContainsKey(edge))
{
if (elemGeom.EdgeBindingDic[edge].HighLight(pts[0].X, pts[0].Y))
{
pictureBoxPreview.Refresh();
}
}
}
}
}
/// <summary>
/// Select or unselect edge
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pictureBoxPreview_MouseClick(object sender, MouseEventArgs e)
{
if (m_activeElem == null || e.Button != MouseButtons.Left) return;
ElementGeometry elemGeom = m_creationData.Creator.ElemGeomDic[m_activeElem];
foreach (Edge edge in m_creationData.Creator.SupportEdges[m_activeElem])
{
if (elemGeom.EdgeBindingDic.ContainsKey(edge))
{
if (elemGeom.EdgeBindingDic[edge].IsHighLighted)
{
bool isSelect = elemGeom.EdgeBindingDic[edge].IsSelected;
elemGeom.EdgeBindingDic[edge].IsHighLighted = false;
elemGeom.EdgeBindingDic[edge].IsSelected = !isSelect;
TreeNode node = GetEdgeTreeNode(edge);
CheckState state = isSelect ? CheckState.Unchecked : CheckState.Checked;
UpdateNodeCheckStatus(node, state);
pictureBoxPreview.Refresh();
treeViewHost.Refresh();
return;
}
}
}
}
/// <summary>
/// Highlight the edge in the preview
/// if mouse-over an edge tree-node.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void treeViewHost_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e)
{
TreeNode node = e.Node;
treeViewHost.SelectedNode = e.Node;
ClearAllHighLight();
ActiveNode(node);
pictureBoxPreview.Refresh();
if (m_activeElem == null || node.Tag == null || !(node.Tag is Edge)) return;
ElementGeometry elemGeom = m_creationData.Creator.ElemGeomDic[m_activeElem];
elemGeom.EdgeBindingDic[node.Tag as Edge].IsHighLighted = true;
pictureBoxPreview.Refresh();
}
/// <summary>
/// Use arrow keys to rotate the display of geometry.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void EdgeFetch_KeyDown(object sender, KeyEventArgs e)
{
m_trackBall.OnKeyDown(e);
switch (e.KeyCode)
{
case Keys.Up:
case Keys.Down:
case Keys.Left:
case Keys.Right:
m_creationData.Creator.ElemGeomDic[m_activeElem].Rotation *= m_trackBall.Rotation;
pictureBoxPreview.Refresh();
break;
default: break;
}
}
/// <summary>
/// Suppress the key input.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void treeViewHost_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
}
/// <summary>
/// Select or un-select the key-node
/// if down the left mouse button in the area of check-box or label.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void treeViewHost_MouseDown(object sender, MouseEventArgs e)
{
TreeViewHitTestInfo hitInfo = treeViewHost.HitTest(e.Location);
if(e.Button == MouseButtons.Left &&
(hitInfo.Location == TreeViewHitTestLocations.StateImage ||
hitInfo.Location == TreeViewHitTestLocations.Label))
{
// mouse down in area of state image or label.
TreeNode node = hitInfo.Node;
if(node.Nodes.Count > 0)
// cancel the expand or collapse of node which has children.
m_cancelExpandOrCollapse = true;
// active the node.
ActiveNode(node);
// select or un-select the node.
CheckState checkState = (CheckState)((node.StateImageIndex + 1) % 2);
UpdateNodeCheckStatus(node, checkState);
pictureBoxPreview.Refresh();
}
}
#endregion
}
}
| |
/*
* 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.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenMetaverse.Assets;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Services.Interfaces;
using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType;
namespace OpenSim.Region.Framework.Scenes
{
/// <summary>
/// Gather uuids for a given entity.
/// </summary>
/// <remarks>
/// This does a deep inspection of the entity to retrieve all the assets it uses (whether as textures, as scripts
/// contained in inventory, as scripts contained in objects contained in another object's inventory, etc. Assets
/// are only retrieved when they are necessary to carry out the inspection (i.e. a serialized object needs to be
/// retrieved to work out which assets it references).
/// </remarks>
public class UuidGatherer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Is gathering complete?
/// </summary>
public bool Complete { get { return m_assetUuidsToInspect.Count <= 0; } }
/// <summary>
/// The dictionary of UUIDs gathered so far. If Complete == true then this is all the reachable UUIDs.
/// </summary>
/// <value>The gathered uuids.</value>
public IDictionary<UUID, sbyte> GatheredUuids { get; private set; }
/// <summary>
/// Gets the next UUID to inspect.
/// </summary>
/// <value>If there is no next UUID then returns null</value>
public UUID? NextUuidToInspect
{
get
{
if (Complete)
return null;
else
return m_assetUuidsToInspect.Peek();
}
}
protected IAssetService m_assetService;
protected Queue<UUID> m_assetUuidsToInspect;
/// <summary>
/// Initializes a new instance of the <see cref="OpenSim.Region.Framework.Scenes.UuidGatherer"/> class.
/// </summary>
/// <remarks>In this case the collection of gathered assets will start out blank.</remarks>
/// <param name="assetService">
/// Asset service.
/// </param>
public UuidGatherer(IAssetService assetService) : this(assetService, new Dictionary<UUID, sbyte>()) {}
/// <summary>
/// Initializes a new instance of the <see cref="OpenSim.Region.Framework.Scenes.UuidGatherer"/> class.
/// </summary>
/// <param name="assetService">
/// Asset service.
/// </param>
/// <param name="collector">
/// Gathered UUIDs will be collected in this dictinaory.
/// It can be pre-populated if you want to stop the gatherer from analyzing assets that have already been fetched and inspected.
/// </param>
public UuidGatherer(IAssetService assetService, IDictionary<UUID, sbyte> collector)
{
m_assetService = assetService;
GatheredUuids = collector;
// FIXME: Not efficient for searching, can improve.
m_assetUuidsToInspect = new Queue<UUID>();
}
/// <summary>
/// Adds the asset uuid for inspection during the gathering process.
/// </summary>
/// <returns><c>true</c>, if for inspection was added, <c>false</c> otherwise.</returns>
/// <param name="uuid">UUID.</param>
public bool AddForInspection(UUID uuid)
{
if (m_assetUuidsToInspect.Contains(uuid))
return false;
// m_log.DebugFormat("[UUID GATHERER]: Adding asset {0} for inspection", uuid);
m_assetUuidsToInspect.Enqueue(uuid);
return true;
}
/// <summary>
/// Gather all the asset uuids associated with a given object.
/// </summary>
/// <remarks>
/// This includes both those directly associated with
/// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
/// within this object).
/// </remarks>
/// <param name="sceneObject">The scene object for which to gather assets</param>
public void AddForInspection(SceneObjectGroup sceneObject)
{
// m_log.DebugFormat(
// "[ASSET GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID);
SceneObjectPart[] parts = sceneObject.Parts;
for (int i = 0; i < parts.Length; i++)
{
SceneObjectPart part = parts[i];
// m_log.DebugFormat(
// "[ARCHIVER]: Getting part {0}, {1} for object {2}", part.Name, part.UUID, sceneObject.UUID);
try
{
Primitive.TextureEntry textureEntry = part.Shape.Textures;
if (textureEntry != null)
{
// Get the prim's default texture. This will be used for faces which don't have their own texture
if (textureEntry.DefaultTexture != null)
RecordTextureEntryAssetUuids(textureEntry.DefaultTexture);
if (textureEntry.FaceTextures != null)
{
// Loop through the rest of the texture faces (a non-null face means the face is different from DefaultTexture)
foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures)
{
if (texture != null)
RecordTextureEntryAssetUuids(texture);
}
}
}
// If the prim is a sculpt then preserve this information too
if (part.Shape.SculptTexture != UUID.Zero)
GatheredUuids[part.Shape.SculptTexture] = (sbyte)AssetType.Texture;
if (part.Shape.ProjectionTextureUUID != UUID.Zero)
GatheredUuids[part.Shape.ProjectionTextureUUID] = (sbyte)AssetType.Texture;
if (part.CollisionSound != UUID.Zero)
GatheredUuids[part.CollisionSound] = (sbyte)AssetType.Sound;
if (part.ParticleSystem.Length > 0)
{
try
{
Primitive.ParticleSystem ps = new Primitive.ParticleSystem(part.ParticleSystem, 0);
if (ps.Texture != UUID.Zero)
GatheredUuids[ps.Texture] = (sbyte)AssetType.Texture;
}
catch (Exception)
{
m_log.WarnFormat(
"[UUID GATHERER]: Could not check particle system for part {0} {1} in object {2} {3} since it is corrupt. Continuing.",
part.Name, part.UUID, sceneObject.Name, sceneObject.UUID);
}
}
TaskInventoryDictionary taskDictionary = (TaskInventoryDictionary)part.TaskInventory.Clone();
// Now analyze this prim's inventory items to preserve all the uuids that they reference
foreach (TaskInventoryItem tii in taskDictionary.Values)
{
// m_log.DebugFormat(
// "[ARCHIVER]: Analysing item {0} asset type {1} in {2} {3}",
// tii.Name, tii.Type, part.Name, part.UUID);
if (!GatheredUuids.ContainsKey(tii.AssetID))
AddForInspection(tii.AssetID, (sbyte)tii.Type);
}
// FIXME: We need to make gathering modular but we cannot yet, since gatherers are not guaranteed
// to be called with scene objects that are in a scene (e.g. in the case of hg asset mapping and
// inventory transfer. There needs to be a way for a module to register a method without assuming a
// Scene.EventManager is present.
// part.ParentGroup.Scene.EventManager.TriggerGatherUuids(part, assetUuids);
// still needed to retrieve textures used as materials for any parts containing legacy materials stored in DynAttrs
RecordMaterialsUuids(part);
}
catch (Exception e)
{
m_log.ErrorFormat("[UUID GATHERER]: Failed to get part - {0}", e);
m_log.DebugFormat(
"[UUID GATHERER]: Texture entry length for prim was {0} (min is 46)",
part.Shape.TextureEntry.Length);
}
}
}
/// <summary>
/// Gathers the next set of assets returned by the next uuid to get from the asset service.
/// </summary>
/// <returns>false if gathering is already complete, true otherwise</returns>
public bool GatherNext()
{
if (Complete)
return false;
UUID nextToInspect = m_assetUuidsToInspect.Dequeue();
// m_log.DebugFormat("[UUID GATHERER]: Inspecting asset {0}", nextToInspect);
GetAssetUuids(nextToInspect);
return true;
}
/// <summary>
/// Gathers all remaining asset UUIDS no matter how many calls are required to the asset service.
/// </summary>
/// <returns>false if gathering is already complete, true otherwise</returns>
public bool GatherAll()
{
if (Complete)
return false;
while (GatherNext());
return true;
}
/// <summary>
/// Gather all the asset uuids associated with the asset referenced by a given uuid
/// </summary>
/// <remarks>
/// This includes both those directly associated with
/// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
/// within this object).
/// This method assumes that the asset type associated with this asset in persistent storage is correct (which
/// should always be the case). So with this method we always need to retrieve asset data even if the asset
/// is of a type which is known not to reference any other assets
/// </remarks>
/// <param name="assetUuid">The uuid of the asset for which to gather referenced assets</param>
private void GetAssetUuids(UUID assetUuid)
{
// avoid infinite loops
if (GatheredUuids.ContainsKey(assetUuid))
return;
try
{
AssetBase assetBase = GetAsset(assetUuid);
if (null != assetBase)
{
sbyte assetType = assetBase.Type;
GatheredUuids[assetUuid] = assetType;
if ((sbyte)AssetType.Bodypart == assetType || (sbyte)AssetType.Clothing == assetType)
{
RecordWearableAssetUuids(assetBase);
}
else if ((sbyte)AssetType.Gesture == assetType)
{
RecordGestureAssetUuids(assetBase);
}
else if ((sbyte)AssetType.Notecard == assetType)
{
RecordTextEmbeddedAssetUuids(assetBase);
}
else if ((sbyte)AssetType.LSLText == assetType)
{
RecordTextEmbeddedAssetUuids(assetBase);
}
else if ((sbyte)OpenSimAssetType.Material == assetType)
{
RecordMaterialAssetUuids(assetBase);
}
else if ((sbyte)AssetType.Object == assetType)
{
RecordSceneObjectAssetUuids(assetBase);
}
}
}
catch (Exception)
{
m_log.ErrorFormat("[UUID GATHERER]: Failed to gather uuids for asset id {0}", assetUuid);
throw;
}
}
private void AddForInspection(UUID assetUuid, sbyte assetType)
{
// Here, we want to collect uuids which require further asset fetches but mark the others as gathered
try
{
if ((sbyte)AssetType.Bodypart == assetType
|| (sbyte)AssetType.Clothing == assetType
|| (sbyte)AssetType.Gesture == assetType
|| (sbyte)AssetType.Notecard == assetType
|| (sbyte)AssetType.LSLText == assetType
|| (sbyte)OpenSimAssetType.Material == assetType
|| (sbyte)AssetType.Object == assetType)
{
AddForInspection(assetUuid);
}
else
{
GatheredUuids[assetUuid] = assetType;
}
}
catch (Exception)
{
m_log.ErrorFormat(
"[UUID GATHERER]: Failed to gather uuids for asset id {0}, type {1}",
assetUuid, assetType);
throw;
}
}
/// <summary>
/// Collect all the asset uuids found in one face of a Texture Entry.
/// </summary>
private void RecordTextureEntryAssetUuids(Primitive.TextureEntryFace texture)
{
GatheredUuids[texture.TextureID] = (sbyte)AssetType.Texture;
if (texture.MaterialID != UUID.Zero)
AddForInspection(texture.MaterialID);
}
/// <summary>
/// Gather all of the texture asset UUIDs used to reference "Materials" such as normal and specular maps
/// stored in legacy format in part.DynAttrs
/// </summary>
/// <param name="part"></param>
private void RecordMaterialsUuids(SceneObjectPart part)
{
// scan thru the dynAttrs map of this part for any textures used as materials
OSD osdMaterials = null;
lock (part.DynAttrs)
{
if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
{
OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
if (materialsStore == null)
return;
materialsStore.TryGetValue("Materials", out osdMaterials);
}
if (osdMaterials != null)
{
//m_log.Info("[UUID Gatherer]: found Materials: " + OSDParser.SerializeJsonString(osd));
if (osdMaterials is OSDArray)
{
OSDArray matsArr = osdMaterials as OSDArray;
foreach (OSDMap matMap in matsArr)
{
try
{
if (matMap.ContainsKey("Material"))
{
OSDMap mat = matMap["Material"] as OSDMap;
if (mat.ContainsKey("NormMap"))
{
UUID normalMapId = mat["NormMap"].AsUUID();
if (normalMapId != UUID.Zero)
{
GatheredUuids[normalMapId] = (sbyte)AssetType.Texture;
//m_log.Info("[UUID Gatherer]: found normal map ID: " + normalMapId.ToString());
}
}
if (mat.ContainsKey("SpecMap"))
{
UUID specularMapId = mat["SpecMap"].AsUUID();
if (specularMapId != UUID.Zero)
{
GatheredUuids[specularMapId] = (sbyte)AssetType.Texture;
//m_log.Info("[UUID Gatherer]: found specular map ID: " + specularMapId.ToString());
}
}
}
}
catch (Exception e)
{
m_log.Warn("[UUID Gatherer]: exception getting materials: " + e.Message);
}
}
}
}
}
}
/// <summary>
/// Get an asset synchronously, potentially using an asynchronous callback. If the
/// asynchronous callback is used, we will wait for it to complete.
/// </summary>
/// <param name="uuid"></param>
/// <returns></returns>
protected virtual AssetBase GetAsset(UUID uuid)
{
return m_assetService.Get(uuid.ToString());
}
/// <summary>
/// Record the asset uuids embedded within the given text (e.g. a script).
/// </summary>
/// <param name="textAsset"></param>
private void RecordTextEmbeddedAssetUuids(AssetBase textAsset)
{
// m_log.DebugFormat("[ASSET GATHERER]: Getting assets for uuid references in asset {0}", embeddingAssetId);
string text = Utils.BytesToString(textAsset.Data);
// m_log.DebugFormat("[UUID GATHERER]: Text {0}", text);
MatchCollection uuidMatches = Util.PermissiveUUIDPattern.Matches(text);
// m_log.DebugFormat("[UUID GATHERER]: Found {0} matches in text", uuidMatches.Count);
foreach (Match uuidMatch in uuidMatches)
{
UUID uuid = new UUID(uuidMatch.Value);
// m_log.DebugFormat("[UUID GATHERER]: Recording {0} in text", uuid);
AddForInspection(uuid);
}
}
/// <summary>
/// Record the uuids referenced by the given wearable asset
/// </summary>
/// <param name="assetBase"></param>
private void RecordWearableAssetUuids(AssetBase assetBase)
{
//m_log.Debug(new System.Text.ASCIIEncoding().GetString(bodypartAsset.Data));
AssetWearable wearableAsset = new AssetBodypart(assetBase.FullID, assetBase.Data);
wearableAsset.Decode();
//m_log.DebugFormat(
// "[ARCHIVER]: Wearable asset {0} references {1} assets", wearableAssetUuid, wearableAsset.Textures.Count);
foreach (UUID uuid in wearableAsset.Textures.Values)
GatheredUuids[uuid] = (sbyte)AssetType.Texture;
}
/// <summary>
/// Get all the asset uuids associated with a given object. This includes both those directly associated with
/// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
/// within this object).
/// </summary>
/// <param name="sceneObjectAsset"></param>
private void RecordSceneObjectAssetUuids(AssetBase sceneObjectAsset)
{
string xml = Utils.BytesToString(sceneObjectAsset.Data);
CoalescedSceneObjects coa;
if (CoalescedSceneObjectsSerializer.TryFromXml(xml, out coa))
{
foreach (SceneObjectGroup sog in coa.Objects)
AddForInspection(sog);
}
else
{
SceneObjectGroup sog = SceneObjectSerializer.FromOriginalXmlFormat(xml);
if (null != sog)
AddForInspection(sog);
}
}
/// <summary>
/// Get the asset uuid associated with a gesture
/// </summary>
/// <param name="gestureAsset"></param>
private void RecordGestureAssetUuids(AssetBase gestureAsset)
{
using (MemoryStream ms = new MemoryStream(gestureAsset.Data))
using (StreamReader sr = new StreamReader(ms))
{
sr.ReadLine(); // Unknown (Version?)
sr.ReadLine(); // Unknown
sr.ReadLine(); // Unknown
sr.ReadLine(); // Name
sr.ReadLine(); // Comment ?
int count = Convert.ToInt32(sr.ReadLine()); // Item count
for (int i = 0 ; i < count ; i++)
{
string type = sr.ReadLine();
if (type == null)
break;
string name = sr.ReadLine();
if (name == null)
break;
string id = sr.ReadLine();
if (id == null)
break;
string unknown = sr.ReadLine();
if (unknown == null)
break;
// If it can be parsed as a UUID, it is an asset ID
UUID uuid;
if (UUID.TryParse(id, out uuid))
GatheredUuids[uuid] = (sbyte)AssetType.Animation; // the asset is either an Animation or a Sound, but this distinction isn't important
}
}
}
/// <summary>
/// Get the asset uuid's referenced in a material.
/// </summary>
private void RecordMaterialAssetUuids(AssetBase materialAsset)
{
OSDMap mat = (OSDMap)OSDParser.DeserializeLLSDXml(materialAsset.Data);
UUID normMap = mat["NormMap"].AsUUID();
if (normMap != UUID.Zero)
GatheredUuids[normMap] = (sbyte)AssetType.Texture;
UUID specMap = mat["SpecMap"].AsUUID();
if (specMap != UUID.Zero)
GatheredUuids[specMap] = (sbyte)AssetType.Texture;
}
}
public class HGUuidGatherer : UuidGatherer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string m_assetServerURL;
public HGUuidGatherer(IAssetService assetService, string assetServerURL)
: this(assetService, assetServerURL, new Dictionary<UUID, sbyte>()) {}
public HGUuidGatherer(IAssetService assetService, string assetServerURL, IDictionary<UUID, sbyte> collector)
: base(assetService, collector)
{
m_assetServerURL = assetServerURL;
if (!m_assetServerURL.EndsWith("/") && !m_assetServerURL.EndsWith("="))
m_assetServerURL = m_assetServerURL + "/";
}
protected override AssetBase GetAsset(UUID uuid)
{
if (string.Empty == m_assetServerURL)
return base.GetAsset(uuid);
else
return FetchAsset(uuid);
}
public AssetBase FetchAsset(UUID assetID)
{
// Test if it's already here
AssetBase asset = m_assetService.Get(assetID.ToString());
if (asset == null)
{
// It's not, so fetch it from abroad
asset = m_assetService.Get(m_assetServerURL + assetID.ToString());
if (asset != null)
m_log.DebugFormat("[HGUUIDGatherer]: Copied asset {0} from {1} to local asset server", assetID, m_assetServerURL);
else
m_log.DebugFormat("[HGUUIDGatherer]: Failed to fetch asset {0} from {1}", assetID, m_assetServerURL);
}
//else
// m_log.DebugFormat("[HGUUIDGatherer]: Asset {0} from {1} was already here", assetID, m_assetServerURL);
return asset;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#pragma warning disable 0420
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// SlimManualResetEvent.cs
//
//
// An manual-reset event that mixes a little spinning with a true Win32 event.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Diagnostics;
using System.Security.Permissions;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
namespace System.Threading
{
// ManualResetEventSlim wraps a manual-reset event internally with a little bit of
// spinning. When an event will be set imminently, it is often advantageous to avoid
// a 4k+ cycle context switch in favor of briefly spinning. Therefore we layer on to
// a brief amount of spinning that should, on the average, make using the slim event
// cheaper than using Win32 events directly. This can be reset manually, much like
// a Win32 manual-reset would be.
//
// Notes:
// We lazily allocate the Win32 event internally. Therefore, the caller should
// always call Dispose to clean it up, just in case. This API is a no-op of the
// event wasn't allocated, but if it was, ensures that the event goes away
// eagerly, instead of waiting for finalization.
/// <summary>
/// Provides a slimmed down version of <see cref="T:System.Threading.ManualResetEvent"/>.
/// </summary>
/// <remarks>
/// All public and protected members of <see cref="ManualResetEventSlim"/> are thread-safe and may be used
/// concurrently from multiple threads, with the exception of Dispose, which
/// must only be used when all other operations on the <see cref="ManualResetEventSlim"/> have
/// completed, and Reset, which should only be used when no other threads are
/// accessing the event.
/// </remarks>
[ComVisible(false)]
[DebuggerDisplay("Set = {IsSet}")]
[HostProtection(Synchronization = true, ExternalThreading = true)]
public class ManualResetEventSlim : IDisposable
{
// These are the default spin counts we use on single-proc and MP machines.
private const int DEFAULT_SPIN_SP = 1;
private const int DEFAULT_SPIN_MP = SpinWait.YIELD_THRESHOLD;
private volatile object m_lock;
// A lock used for waiting and pulsing. Lazily initialized via EnsureLockObjectCreated()
private volatile ManualResetEvent m_eventObj; // A true Win32 event used for waiting.
// -- State -- //
//For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant.
private volatile int m_combinedState; //ie a UInt32. Used for the state items listed below.
//1-bit for signalled state
private const int SignalledState_BitMask = unchecked((int)0x80000000);//1000 0000 0000 0000 0000 0000 0000 0000
private const int SignalledState_ShiftCount = 31;
//1-bit for disposed state
private const int Dispose_BitMask = unchecked((int)0x40000000);//0100 0000 0000 0000 0000 0000 0000 0000
//11-bits for m_spinCount
private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); //0011 1111 1111 1000 0000 0000 0000 0000
private const int SpinCountState_ShiftCount = 19;
private const int SpinCountState_MaxValue = (1 << 11) - 1; //2047
//19-bits for m_waiters. This allows support of 512K threads waiting which should be ample
private const int NumWaitersState_BitMask = unchecked((int)0x0007FFFF); // 0000 0000 0000 0111 1111 1111 1111 1111
private const int NumWaitersState_ShiftCount = 0;
private const int NumWaitersState_MaxValue = (1 << 19) - 1; //512K-1
// ----------- //
#if DEBUG
private static int s_nextId; // The next id that will be given out.
private int m_id = Interlocked.Increment(ref s_nextId); // A unique id for debugging purposes only.
private long m_lastSetTime;
private long m_lastResetTime;
#endif
/// <summary>
/// Gets the underlying <see cref="T:System.Threading.WaitHandle"/> object for this <see
/// cref="ManualResetEventSlim"/>.
/// </summary>
/// <value>The underlying <see cref="T:System.Threading.WaitHandle"/> event object fore this <see
/// cref="ManualResetEventSlim"/>.</value>
/// <remarks>
/// Accessing this property forces initialization of an underlying event object if one hasn't
/// already been created. To simply wait on this <see cref="ManualResetEventSlim"/>,
/// the public Wait methods should be preferred.
/// </remarks>
public WaitHandle WaitHandle
{
get
{
ThrowIfDisposed();
if (m_eventObj == null)
{
// Lazily initialize the event object if needed.
LazyInitializeEvent();
}
return m_eventObj;
}
}
/// <summary>
/// Gets whether the event is set.
/// </summary>
/// <value>true if the event has is set; otherwise, false.</value>
public bool IsSet
{
get
{
return 0 != ExtractStatePortion(m_combinedState, SignalledState_BitMask);
}
private set
{
UpdateStateAtomically(((value) ? 1 : 0) << SignalledState_ShiftCount, SignalledState_BitMask);
}
}
/// <summary>
/// Gets the number of spin waits that will be occur before falling back to a true wait.
/// </summary>
public int SpinCount
{
get
{
return ExtractStatePortionAndShiftRight(m_combinedState, SpinCountState_BitMask, SpinCountState_ShiftCount);
}
private set
{
Contract.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
Contract.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
// Don't worry about thread safety because it's set one time from the constructor
m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount);
}
}
/// <summary>
/// How many threads are waiting.
/// </summary>
private int Waiters
{
get
{
return ExtractStatePortionAndShiftRight(m_combinedState, NumWaitersState_BitMask, NumWaitersState_ShiftCount);
}
set
{
//setting to <0 would indicate an internal flaw, hence Assert is appropriate.
Contract.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error.");
// it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here.
if (value >= NumWaitersState_MaxValue)
throw new InvalidOperationException(String.Format(Environment.GetResourceString("ManualResetEventSlim_ctor_TooManyWaiters"), NumWaitersState_MaxValue));
UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask);
}
}
//-----------------------------------------------------------------------------------
// Constructs a new event, optionally specifying the initial state and spin count.
// The defaults are that the event is unsignaled and some reasonable default spin.
//
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with an initial state of nonsignaled.
/// </summary>
public ManualResetEventSlim()
: this(false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with a Boolen value indicating whether to set the intial state to signaled.
/// </summary>
/// <param name="initialState">true to set the initial state signaled; false to set the initial state
/// to nonsignaled.</param>
public ManualResetEventSlim(bool initialState)
{
// Specify the defualt spin count, and use default spin if we're
// on a multi-processor machine. Otherwise, we won't.
Initialize(initialState, DEFAULT_SPIN_MP);
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with a Boolen value indicating whether to set the intial state to signaled and a specified
/// spin count.
/// </summary>
/// <param name="initialState">true to set the initial state to signaled; false to set the initial state
/// to nonsignaled.</param>
/// <param name="spinCount">The number of spin waits that will occur before falling back to a true
/// wait.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="spinCount"/> is less than
/// 0 or greater than the maximum allowed value.</exception>
public ManualResetEventSlim(bool initialState, int spinCount)
{
if (spinCount < 0)
{
throw new ArgumentOutOfRangeException("spinCount");
}
if (spinCount > SpinCountState_MaxValue)
{
throw new ArgumentOutOfRangeException(
"spinCount",
String.Format(Environment.GetResourceString("ManualResetEventSlim_ctor_SpinCountOutOfRange"), SpinCountState_MaxValue));
}
// We will suppress default spin because the user specified a count.
Initialize(initialState, spinCount);
}
/// <summary>
/// Initializes the internal state of the event.
/// </summary>
/// <param name="initialState">Whether the event is set initially or not.</param>
/// <param name="spinCount">The spin count that decides when the event will block.</param>
private void Initialize(bool initialState, int spinCount)
{
this.m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0;
//the spinCount argument has been validated by the ctors.
//but we now sanity check our predefined constants.
Contract.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
Contract.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount;
}
/// <summary>
/// Helper to ensure the lock object is created before first use.
/// </summary>
private void EnsureLockObjectCreated()
{
Contract.Ensures(m_lock != null);
if (m_lock != null)
return;
object newObj = new object();
Interlocked.CompareExchange(ref m_lock, newObj, null); // failure is benign. Someone else set the value.
}
/// <summary>
/// This method lazily initializes the event object. It uses CAS to guarantee that
/// many threads racing to call this at once don't result in more than one event
/// being stored and used. The event will be signaled or unsignaled depending on
/// the state of the thin-event itself, with synchronization taken into account.
/// </summary>
/// <returns>True if a new event was created and stored, false otherwise.</returns>
private bool LazyInitializeEvent()
{
bool preInitializeIsSet = IsSet;
ManualResetEvent newEventObj = new ManualResetEvent(preInitializeIsSet);
// We have to CAS this in case we are racing with another thread. We must
// guarantee only one event is actually stored in this field.
if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null)
{
// Someone else set the value due to a race condition. Destroy the garbage event.
newEventObj.Close();
return false;
}
else
{
// Now that the event is published, verify that the state hasn't changed since
// we snapped the preInitializeState. Another thread could have done that
// between our initial observation above and here. The barrier incurred from
// the CAS above (in addition to m_state being volatile) prevents this read
// from moving earlier and being collapsed with our original one.
bool currentIsSet = IsSet;
if (currentIsSet != preInitializeIsSet)
{
Contract.Assert(currentIsSet,
"The only safe concurrent transition is from unset->set: detected set->unset.");
// We saw it as unsignaled, but it has since become set.
lock (newEventObj)
{
// If our event hasn't already been disposed of, we must set it.
if (m_eventObj == newEventObj)
{
newEventObj.Set();
}
}
}
return true;
}
}
/// <summary>
/// Sets the state of the event to signaled, which allows one or more threads waiting on the event to
/// proceed.
/// </summary>
public void Set()
{
Set(false);
}
/// <summary>
/// Private helper to actually perform the Set.
/// </summary>
/// <param name="duringCancellation">Indicates whether we are calling Set() during cancellation.</param>
/// <exception cref="T:System.OperationCanceledException">The object has been canceled.</exception>
private void Set(bool duringCancellation)
{
// We need to ensure that IsSet=true does not get reordered past the read of m_eventObj
// This would be a legal movement according to the .NET memory model.
// The code is safe as IsSet involves an Interlocked.CompareExchange which provides a full memory barrier.
IsSet = true;
// If there are waiting threads, we need to pulse them.
if (Waiters > 0)
{
Contract.Assert(m_lock != null); //if waiters>0, then m_lock has already been created.
lock (m_lock)
{
Monitor.PulseAll(m_lock);
}
}
ManualResetEvent eventObj = m_eventObj;
//Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly
//It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic
if (eventObj != null && !duringCancellation)
{
// We must surround this call to Set in a lock. The reason is fairly subtle.
// Sometimes a thread will issue a Wait and wake up after we have set m_state,
// but before we have gotten around to setting m_eventObj (just below). That's
// because Wait first checks m_state and will only access the event if absolutely
// necessary. However, the coding pattern { event.Wait(); event.Dispose() } is
// quite common, and we must support it. If the waiter woke up and disposed of
// the event object before the setter has finished, however, we would try to set a
// now-disposed Win32 event. Crash! To deal with this race condition, we use a lock to
// protect access to the event object when setting and disposing of it. We also
// double-check that the event has not become null in the meantime when in the lock.
lock (eventObj)
{
if (m_eventObj != null)
{
// If somebody is waiting, we must set the event.
m_eventObj.Set();
}
}
}
#if DEBUG
m_lastSetTime = DateTime.Now.Ticks;
#endif
}
/// <summary>
/// Sets the state of the event to nonsignaled, which causes threads to block.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Reset()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
public void Reset()
{
ThrowIfDisposed();
// If there's an event, reset it.
if (m_eventObj != null)
{
m_eventObj.Reset();
}
// There is a race condition here. If another thread Sets the event, we will get into a state
// where m_state will be unsignaled, yet the Win32 event object will have been signaled.
// This could cause waiting threads to wake up even though the event is in an
// unsignaled state. This is fine -- those that are calling Reset concurrently are
// responsible for doing "the right thing" -- e.g. rechecking the condition and
// resetting the event manually.
// And finally set our state back to unsignaled.
IsSet = false;
#if DEBUG
m_lastResetTime = DateTime.Now.Ticks;
#endif
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state.
/// </remarks>
public void Wait()
{
Wait(Timeout.Infinite, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> receives a signal,
/// while observing a <see cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <exception cref="T:System.OperationCanceledExcepton"><paramref name="cancellationToken"/> was
/// canceled.</exception>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state.
/// </remarks>
public void Wait(CancellationToken cancellationToken)
{
Wait(Timeout.Infinite, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// <see cref="T:System.TimeSpan"/> to measure the time interval.
/// </summary>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds
/// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(TimeSpan timeout)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException("timeout");
}
return Wait((int)totalMilliseconds, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a <see
/// cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds
/// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.Threading.OperationCanceledException"><paramref
/// name="cancellationToken"/> was canceled.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(TimeSpan timeout, CancellationToken cancellationToken)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException("timeout");
}
return Wait((int)totalMilliseconds, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// 32-bit signed integer to measure the time interval.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(int millisecondsTimeout)
{
return Wait(millisecondsTimeout, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// 32-bit signed integer to measure the time interval, while observing a <see
/// cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <exception cref="T:System.Threading.OperationCanceledException"><paramref
/// name="cancellationToken"/> was canceled.</exception>
public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
{
ThrowIfDisposed();
cancellationToken.ThrowIfCancellationRequested(); // an early convenience check
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException("millisecondsTimeout");
}
if (!IsSet)
{
if (millisecondsTimeout == 0)
{
// For 0-timeouts, we just return immediately.
return false;
}
// We spin briefly before falling back to allocating and/or waiting on a true event.
uint startTime = 0;
bool bNeedTimeoutAdjustment = false;
int realMillisecondsTimeout = millisecondsTimeout; //this will be adjusted if necessary.
if (millisecondsTimeout != Timeout.Infinite)
{
// We will account for time spent spinning, so that we can decrement it from our
// timeout. In most cases the time spent in this section will be negligible. But
// we can't discount the possibility of our thread being switched out for a lengthy
// period of time. The timeout adjustments only take effect when and if we actually
// decide to block in the kernel below.
startTime = TimeoutHelper.GetTime();
bNeedTimeoutAdjustment = true;
}
//spin
int HOW_MANY_SPIN_BEFORE_YIELD = 10;
int HOW_MANY_YIELD_EVERY_SLEEP_0 = 5;
int HOW_MANY_YIELD_EVERY_SLEEP_1 = 20;
int spinCount = SpinCount;
for (int i = 0; i < spinCount; i++)
{
if (IsSet)
{
return true;
}
else if (i < HOW_MANY_SPIN_BEFORE_YIELD)
{
if (i == HOW_MANY_SPIN_BEFORE_YIELD / 2)
{
Thread.Yield();
}
else
{
Thread.SpinWait(PlatformHelper.ProcessorCount * (4 << i));
}
}
else if (i % HOW_MANY_YIELD_EVERY_SLEEP_1 == 0)
{
Thread.Sleep(1);
}
else if (i % HOW_MANY_YIELD_EVERY_SLEEP_0 == 0)
{
Thread.Sleep(0);
}
else
{
Thread.Yield();
}
if (i >= 100 && i % 10 == 0) // check the cancellation token if the user passed a very large spin count
cancellationToken.ThrowIfCancellationRequested();
}
// Now enter the lock and wait.
EnsureLockObjectCreated();
// We must register and deregister the token outside of the lock, to avoid deadlocks.
using (cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCallback, this))
{
lock (m_lock)
{
// Loop to cope with spurious wakeups from other waits being canceled
while (!IsSet)
{
// If our token was canceled, we must throw and exit.
cancellationToken.ThrowIfCancellationRequested();
//update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled)
if (bNeedTimeoutAdjustment)
{
realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout);
if (realMillisecondsTimeout <= 0)
return false;
}
// There is a race condition that Set will fail to see that there are waiters as Set does not take the lock,
// so after updating waiters, we must check IsSet again.
// Also, we must ensure there cannot be any reordering of the assignment to Waiters and the
// read from IsSet. This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange
// operation which provides a full memory barrier.
// If we see IsSet=false, then we are guaranteed that Set() will see that we are
// waiting and will pulse the monitor correctly.
Waiters = Waiters + 1;
if (IsSet) //This check must occur after updating Waiters.
{
Waiters--; //revert the increment.
return true;
}
// Now finally perform the wait.
try
{
// ** the actual wait **
if (!Monitor.Wait(m_lock, realMillisecondsTimeout))
return false; //return immediately if the timeout has expired.
}
finally
{
// Clean up: we're done waiting.
Waiters = Waiters - 1;
}
// Now just loop back around, and the right thing will happen. Either:
// 1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait)
// or 2. the wait was successful. (the loop will break)
}
}
}
} // automatically disposes (and deregisters) the callback
return true; //done. The wait was satisfied.
}
/// <summary>
/// Releases all resources used by the current instance of <see cref="ManualResetEventSlim"/>.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// When overridden in a derived class, releases the unmanaged resources used by the
/// <see cref="ManualResetEventSlim"/>, and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources;
/// false to release only unmanaged resources.</param>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose(Boolean)"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
if ((m_combinedState & Dispose_BitMask) != 0)
return; // already disposed
m_combinedState |= Dispose_BitMask; //set the dispose bit
if (disposing)
{
// We will dispose of the event object. We do this under a lock to protect
// against the race condition outlined in the Set method above.
ManualResetEvent eventObj = m_eventObj;
if (eventObj != null)
{
lock (eventObj)
{
eventObj.Close();
m_eventObj = null;
}
}
}
}
/// <summary>
/// Throw ObjectDisposedException if the MRES is disposed
/// </summary>
private void ThrowIfDisposed()
{
if ((m_combinedState & Dispose_BitMask) != 0)
throw new ObjectDisposedException(Environment.GetResourceString("ManualResetEventSlim_Disposed"));
}
/// <summary>
/// Private helper method to wake up waiters when a cancellationToken gets canceled.
/// </summary>
private static Action<object> s_cancellationTokenCallback = new Action<object>(CancellationTokenCallback);
private static void CancellationTokenCallback(object obj)
{
ManualResetEventSlim mre = obj as ManualResetEventSlim;
Contract.Assert(mre != null, "Expected a ManualResetEventSlim");
Contract.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use.
lock (mre.m_lock)
{
Monitor.PulseAll(mre.m_lock); // awaken all waiters
}
}
/// <summary>
/// Private helper method for updating parts of a bit-string state value.
/// Mainly called from the IsSet and Waiters properties setters
/// </summary>
/// <remarks>
/// Note: the parameter types must be int as CompareExchange cannot take a Uint
/// </remarks>
/// <param name="newBits">The new value</param>
/// <param name="updateBitsMask">The mask used to set the bits</param>
private void UpdateStateAtomically(int newBits, int updateBitsMask)
{
SpinWait sw = new SpinWait();
Contract.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask.");
do
{
int oldState = m_combinedState; // cache the old value for testing in CAS
// Procedure:(1) zero the updateBits. eg oldState = [11111111] flag= [00111000] newState = [11000111]
// then (2) map in the newBits. eg [11000111] newBits=00101000, newState=[11101111]
int newState = (oldState & ~updateBitsMask) | newBits;
if (Interlocked.CompareExchange(ref m_combinedState, newState, oldState) == oldState)
{
return;
}
sw.SpinOnce();
} while (true);
}
/// <summary>
/// Private helper method - performs Mask and shift, particular helpful to extract a field from a packed word.
/// eg ExtractStatePortionAndShiftRight(0x12345678, 0xFF000000, 24) => 0x12, ie extracting the top 8-bits as a simple integer
///
/// ?? is there a common place to put this rather than being private to MRES?
/// </summary>
/// <param name="state"></param>
/// <param name="mask"></param>
/// <param name="rightBitShiftCount"></param>
/// <returns></returns>
private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount)
{
//convert to uint before shifting so that right-shift does not replicate the sign-bit,
//then convert back to int.
return unchecked((int)(((uint)(state & mask)) >> rightBitShiftCount));
}
/// <summary>
/// Performs a Mask operation, but does not perform the shift.
/// This is acceptable for boolean values for which the shift is unnecessary
/// eg (val & Mask) != 0 is an appropriate way to extract a boolean rather than using
/// ((val & Mask) >> shiftAmount) == 1
///
/// ?? is there a common place to put this rather than being private to MRES?
/// </summary>
/// <param name="state"></param>
/// <param name="mask"></param>
private static int ExtractStatePortion(int state, int mask)
{
return state & mask;
}
}
}
| |
using Microsoft.Xna.Framework;
namespace Nez
{
/// <summary>
/// Note that this is not a full, multi-iteration physics system! This can be used for simple, arcade style physics.
/// Based on http://elancev.name/oliver/2D%20polygon.htm#tut5
/// </summary>
public class ArcadeRigidbody : Component, IUpdatable
{
/// <summary>
/// mass of this rigidbody. A 0 mass will make this an immovable object.
/// </summary>
/// <value>The mass.</value>
public float Mass
{
get => _mass;
set => SetMass(value);
}
/// <summary>
/// 0 - 1 range where 0 is no bounce and 1 is perfect reflection
/// </summary>
public float Elasticity
{
get => _elasticity;
set => SetElasticity(value);
}
/// <summary>
/// 0 - 1 range. 0 means no friction, 1 means the object will stop dead on
/// </summary>
public float Friction
{
get => _friction;
set => SetFriction(value);
}
/// <summary>
/// 0 - 9 range. When a collision occurs and it has risidual motion along the surface of collision if its square magnitude is less
/// than glue friction will be set to the maximum for the collision resolution.
/// </summary>
public float Glue
{
get => _glue;
set => SetGlue(value);
}
/// <summary>
/// if true, Physics.gravity will be taken into account each frame
/// </summary>
public bool ShouldUseGravity = true;
/// <summary>
/// velocity of this rigidbody
/// </summary>
public Vector2 Velocity;
/// <summary>
/// rigidbodies with a mass of 0 are considered immovable. Changing velocity and collisions will have no effect on them.
/// </summary>
/// <value><c>true</c> if is immovable; otherwise, <c>false</c>.</value>
public bool IsImmovable => _mass < 0.0001f;
float _mass = 10f;
float _elasticity = 0.5f;
float _friction = 0.5f;
float _glue = 0.01f;
float _inverseMass;
Collider _collider;
public ArcadeRigidbody()
{
_inverseMass = 1 / _mass;
}
#region Fluent setters
/// <summary>
/// mass of this rigidbody. A 0 mass will make this an immovable object.
/// </summary>
/// <returns>The mass.</returns>
/// <param name="mass">Mass.</param>
public ArcadeRigidbody SetMass(float mass)
{
_mass = Mathf.Clamp(mass, 0, float.MaxValue);
if (_mass > 0.0001f)
_inverseMass = 1 / _mass;
else
_inverseMass = 0f;
return this;
}
/// <summary>
/// 0 - 1 range where 0 is no bounce and 1 is perfect reflection
/// </summary>
/// <returns>The elasticity.</returns>
/// <param name="value">Value.</param>
public ArcadeRigidbody SetElasticity(float value)
{
_elasticity = Mathf.Clamp01(value);
return this;
}
/// <summary>
/// 0 - 1 range. 0 means no friction, 1 means the object will stop dead on
/// </summary>
/// <returns>The friction.</returns>
/// <param name="value">Value.</param>
public ArcadeRigidbody SetFriction(float value)
{
_friction = Mathf.Clamp01(value);
return this;
}
/// <summary>
/// 0 - 9 range. When a collision occurs and it has risidual motion along the surface of collision if its square magnitude is less
/// than glue friction will be set to the maximum for the collision resolution.
/// </summary>
/// <returns>The glue.</returns>
/// <param name="value">Value.</param>
public ArcadeRigidbody SetGlue(float value)
{
_glue = Mathf.Clamp(value, 0, 10);
return this;
}
/// <summary>
/// velocity of this rigidbody
/// </summary>
/// <returns>The velocity.</returns>
/// <param name="velocity">Velocity.</param>
public ArcadeRigidbody SetVelocity(Vector2 velocity)
{
Velocity = velocity;
return this;
}
#endregion
/// <summary>
/// add an instant force impulse to the rigidbody using its mass. force is an acceleration in pixels per second per second. The
/// force is multiplied by 100000 to make the values more reasonable to use.
/// </summary>
/// <param name="force">Force.</param>
public void AddImpulse(Vector2 force)
{
if (!IsImmovable)
Velocity += force * 100000 * (_inverseMass * Time.DeltaTime * Time.DeltaTime);
}
public override void OnAddedToEntity()
{
_collider = Entity.GetComponent<Collider>();
Debug.WarnIf(_collider == null, "ArcadeRigidbody has no Collider. ArcadeRigidbody requires a Collider!");
}
public virtual void Update()
{
if (IsImmovable || _collider == null)
{
Velocity = Vector2.Zero;
return;
}
if (ShouldUseGravity)
Velocity += Physics.Gravity * Time.DeltaTime;
Entity.Transform.Position += Velocity * Time.DeltaTime;
CollisionResult collisionResult;
// fetch anything that we might collide with at our new position
var neighbors = Physics.BoxcastBroadphaseExcludingSelf(_collider, _collider.CollidesWithLayers);
foreach (var neighbor in neighbors)
{
// if the neighbor collider is of the same entity, ignore it
if (neighbor.Entity == Entity)
{
continue;
}
if (_collider.CollidesWith(neighbor, out collisionResult))
{
// if the neighbor has an ArcadeRigidbody we handle full collision response. If not, we calculate things based on the
// neighbor being immovable.
var neighborRigidbody = neighbor.Entity.GetComponent<ArcadeRigidbody>();
if (neighborRigidbody != null)
{
ProcessOverlap(neighborRigidbody, ref collisionResult.MinimumTranslationVector);
ProcessCollision(neighborRigidbody, ref collisionResult.MinimumTranslationVector);
}
else
{
// neighbor has no ArcadeRigidbody so we assume its immovable and only move ourself
Entity.Transform.Position -= collisionResult.MinimumTranslationVector;
var relativeVelocity = Velocity;
CalculateResponseVelocity(ref relativeVelocity, ref collisionResult.MinimumTranslationVector,
out relativeVelocity);
Velocity += relativeVelocity;
}
}
}
}
/// <summary>
/// separates two overlapping rigidbodies. Handles the case of either being immovable as well.
/// </summary>
/// <param name="other">Other.</param>
/// <param name="minimumTranslationVector"></param>
void ProcessOverlap(ArcadeRigidbody other, ref Vector2 minimumTranslationVector)
{
if (IsImmovable)
{
other.Entity.Transform.Position += minimumTranslationVector;
}
else if (other.IsImmovable)
{
Entity.Transform.Position -= minimumTranslationVector;
}
else
{
Entity.Transform.Position -= minimumTranslationVector * 0.5f;
other.Entity.Transform.Position += minimumTranslationVector * 0.5f;
}
}
/// <summary>
/// handles the collision of two non-overlapping rigidbodies. New velocities will be assigned to each rigidbody as appropriate.
/// </summary>
/// <param name="other">Other.</param>
/// <param name="inverseMTV">Inverse MT.</param>
void ProcessCollision(ArcadeRigidbody other, ref Vector2 minimumTranslationVector)
{
// we compute a response for the two colliding objects. The calculations are based on the relative velocity of the objects
// which gets reflected along the collided surface normal. Then a part of the response gets added to each object based on mass.
var relativeVelocity = Velocity - other.Velocity;
CalculateResponseVelocity(ref relativeVelocity, ref minimumTranslationVector, out relativeVelocity);
// now we use the masses to linearly scale the response on both rigidbodies
var totalInverseMass = _inverseMass + other._inverseMass;
var ourResponseFraction = _inverseMass / totalInverseMass;
var otherResponseFraction = other._inverseMass / totalInverseMass;
Velocity += relativeVelocity * ourResponseFraction;
other.Velocity -= relativeVelocity * otherResponseFraction;
}
/// <summary>
/// given the relative velocity between the two objects and the MTV this method modifies the relativeVelocity to make it a collision
/// response.
/// </summary>
/// <param name="relativeVelocity">Relative velocity.</param>
/// <param name="minimumTranslationVector">Minimum translation vector.</param>
void CalculateResponseVelocity(ref Vector2 relativeVelocity, ref Vector2 minimumTranslationVector,
out Vector2 responseVelocity)
{
// first, we get the normalized MTV in the opposite direction: the surface normal
var inverseMTV = minimumTranslationVector * -1f;
Vector2 normal;
Vector2.Normalize(ref inverseMTV, out normal);
// the velocity is decomposed along the normal of the collision and the plane of collision.
// The elasticity will affect the response along the normal (normalVelocityComponent) and the friction will affect
// the tangential component of the velocity (tangentialVelocityComponent)
float n;
Vector2.Dot(ref relativeVelocity, ref normal, out n);
var normalVelocityComponent = normal * n;
var tangentialVelocityComponent = relativeVelocity - normalVelocityComponent;
if (n > 0.0f)
normalVelocityComponent = Vector2.Zero;
// if the squared magnitude of the tangential component is less than glue then we bump up the friction to the max
var coefficientOfFriction = _friction;
if (tangentialVelocityComponent.LengthSquared() < _glue)
coefficientOfFriction = 1.01f;
// elasticity affects the normal component of the velocity and friction affects the tangential component
responseVelocity = -(1.0f + _elasticity) * normalVelocityComponent -
coefficientOfFriction * tangentialVelocityComponent;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Authentication.Facebook;
using Microsoft.AspNet.Authentication.Google;
using Microsoft.AspNet.Authentication.MicrosoftAccount;
using Microsoft.AspNet.Authentication.Twitter;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Diagnostics.Entity;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Routing;
using Microsoft.Data.Entity;
using Microsoft.Framework.Configuration;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Microsoft.Framework.Logging.Console;
using Microsoft.Framework.Runtime;
using PrepOps.Models;
using PrepOps.Services;
using Microsoft.AspNet.Authorization;
namespace PrepOps
{
public class Startup
{
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
// Setup configuration sources.
var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// This reads the configuration keys from the secret store.
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add Application Insights data collection services to the services container.
services.AddApplicationInsightsTelemetry(Configuration);
// Add Entity Framework services to the services container.
if (Configuration["Data:DefaultConnection:UseInMemory"] == "true")
{
services.AddEntityFramework()
.AddInMemoryStore()
.AddDbContext<PrepOpsContext>();
}
else
{
//string connectionStringPath = "Data:DefaultConnection:LocalConnectionString";
string connectionStringPath = "Data:DefaultConnection:AzureConnectionString";
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<PrepOpsContext>(options =>
options.UseSqlServer(Configuration[connectionStringPath]));
}
// Add CORS support
services.AddCors();
//var policy = new Microsoft.AspNet.Cors.Core.CorsPolicy();
//policy.Headers.Add("*");
//policy.Methods.Add("*");
//policy.Origins.Add("*");
//policy.SupportsCredentials = true;
//services.ConfigureCors(x => x.AddPolicy("prepOps", policy));
services.ConfigureCors(options => {
options.AddPolicy("prepOps",
builder => builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
);
});
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<PrepOpsContext>()
.AddDefaultTokenProviders();
// Add Authorization rules for the app
services.Configure<AuthorizationOptions>(options =>
{
options.AddPolicy("TenantAdmin", new AuthorizationPolicyBuilder().RequireClaim("UserType", new string[] { "TenantAdmin", "SiteAdmin" }).Build());
options.AddPolicy("SiteAdmin", new AuthorizationPolicyBuilder().RequireClaim("UserType", "SiteAdmin").Build());
});
services.ConfigureCookieAuthentication(options =>
{
options.AccessDeniedPath = new PathString("/Home/AccessDenied");
});
// Configure the options for the authentication middleware.
// You can add options for Google, Twitter and other middleware as shown below.
// For more information see http://go.microsoft.com/fwlink/?LinkID=532715
if (Configuration["Authentication:Facebook:AppId"] != null)
{
services.Configure<FacebookAuthenticationOptions>(options =>
{
options.AppId = Configuration["Authentication:Facebook:AppId"];
options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
});
}
//Enable Twitter Auth, only id key set
if (Configuration["Authentication:Twitter:ConsumerKey"] != null)
{
services.Configure<TwitterAuthenticationOptions>(options =>
{
options.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];
options.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];
});
}
if (Configuration["Authentication:MicrosoftAccount:ClientId"] != null)
{
services.Configure<MicrosoftAccountAuthenticationOptions>(options =>
{
options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"];
options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"];
});
}
// Add MVC services to the services container.
services.AddMvc();
// Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
// You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
// services.AddWebApiConventions();
// Register application services.
services.AddSingleton((x) => this.Configuration);
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddSingleton<IClosestLocations, SqlClosestLocations>();
services.AddTransient<IPrepOpsDataAccess, PrepOpsDataAccessEF7>();
services.AddSingleton<IImageService, ImageService>();
//services.AddSingleton<GeoService>();
}
// Configure is called after ConfigureServices is called.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, PrepOpsContext dbContext, IServiceProvider serviceProvider)
{
loggerFactory.MinimumLevel = LogLevel.Information;
loggerFactory.AddConsole();
// CORS support
app.UseCors("prepOps");
// Configure the HTTP request pipeline.
// Add Application Insights to the request pipeline to track HTTP request telemetry data.
app.UseApplicationInsightsRequestTelemetry();
// Add the following to the request pipeline only in development environment.
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseErrorPage(ErrorPageOptions.ShowAll);
app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
}
else
{
// Add Error handling middleware which catches all application specific errors and
// sends the request to the following path or controller action.
app.UseErrorHandler("/Home/Error");
}
// Track data about exceptions from the application. Should be configured after all error handling middleware in the request pipeline.
app.UseApplicationInsightsExceptionTelemetry();
// Add static files to the request pipeline.
app.UseStaticFiles();
// Add cookie-based authentication to the request pipeline.
app.UseIdentity();
// Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method.
// For more information see http://go.microsoft.com/fwlink/?LinkID=532715
if (Configuration["Authentication:Facebook:AppId"] != null)
{
app.UseFacebookAuthentication();
}
// app.UseGoogleAuthentication();
if (Configuration["Authentication:MicrosoftAccount:ClientId"] != null)
{
app.UseMicrosoftAccountAuthentication();
}
if (Configuration["Authentication:Twitter:ConsumerKey"] != null)
{
app.UseTwitterAuthentication();
}
// Add MVC to the request pipeline.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areaRoute",
template: "{area:exists}/{controller}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
// Add sample data and test admin accounts if specified in Config.Json.
// for production applications, this should either be set to false or deleted.
if (Configuration["Data:InsertSampleData"] == "true")
{
SampleData.InsertTestData(dbContext);
}
if (Configuration["Data:InsertTestUsers"] == "true")
{
SampleData.CreateAdminUser(serviceProvider, dbContext).Wait();
}
}
}
}
| |
// 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.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
namespace System.Collections.Generic
{
[DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class SortedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
{
[NonSerialized]
private KeyCollection _keys;
[NonSerialized]
private ValueCollection _values;
private TreeSet<KeyValuePair<TKey, TValue>> _set; // Do not rename (binary serialization)
public SortedDictionary() : this((IComparer<TKey>)null)
{
}
public SortedDictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null)
{
}
public SortedDictionary(IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer)
{
if (dictionary == null)
{
throw new ArgumentNullException(nameof(dictionary));
}
_set = new TreeSet<KeyValuePair<TKey, TValue>>(new KeyValuePairComparer(comparer));
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
_set.Add(pair);
}
}
public SortedDictionary(IComparer<TKey> comparer)
{
_set = new TreeSet<KeyValuePair<TKey, TValue>>(new KeyValuePairComparer(comparer));
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
{
_set.Add(keyValuePair);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
{
TreeSet<KeyValuePair<TKey, TValue>>.Node node = _set.FindNode(keyValuePair);
if (node == null)
{
return false;
}
if (keyValuePair.Value == null)
{
return node.Item.Value == null;
}
else
{
return EqualityComparer<TValue>.Default.Equals(node.Item.Value, keyValuePair.Value);
}
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
TreeSet<KeyValuePair<TKey, TValue>>.Node node = _set.FindNode(keyValuePair);
if (node == null)
{
return false;
}
if (EqualityComparer<TValue>.Default.Equals(node.Item.Value, keyValuePair.Value))
{
_set.Remove(keyValuePair);
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get
{
return false;
}
}
public TValue this[TKey key]
{
get
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
TreeSet<KeyValuePair<TKey, TValue>>.Node node = _set.FindNode(new KeyValuePair<TKey, TValue>(key, default(TValue)));
if (node == null)
{
throw new KeyNotFoundException();
}
return node.Item.Value;
}
set
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
TreeSet<KeyValuePair<TKey, TValue>>.Node node = _set.FindNode(new KeyValuePair<TKey, TValue>(key, default(TValue)));
if (node == null)
{
_set.Add(new KeyValuePair<TKey, TValue>(key, value));
}
else
{
node.Item = new KeyValuePair<TKey, TValue>(node.Item.Key, value);
_set.UpdateVersion();
}
}
}
public int Count
{
get
{
return _set.Count;
}
}
public IComparer<TKey> Comparer
{
get
{
return ((KeyValuePairComparer)_set.Comparer).keyComparer;
}
}
public KeyCollection Keys
{
get
{
if (_keys == null) _keys = new KeyCollection(this);
return _keys;
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
return Keys;
}
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
{
get
{
return Keys;
}
}
public ValueCollection Values
{
get
{
if (_values == null) _values = new ValueCollection(this);
return _values;
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
return Values;
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
{
get
{
return Values;
}
}
public void Add(TKey key, TValue value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
_set.Add(new KeyValuePair<TKey, TValue>(key, value));
}
public void Clear()
{
_set.Clear();
}
public bool ContainsKey(TKey key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _set.Contains(new KeyValuePair<TKey, TValue>(key, default(TValue)));
}
public bool ContainsValue(TValue value)
{
bool found = false;
if (value == null)
{
_set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node)
{
if (node.Item.Value == null)
{
found = true;
return false; // stop the walk
}
return true;
});
}
else
{
EqualityComparer<TValue> valueComparer = EqualityComparer<TValue>.Default;
_set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node)
{
if (valueComparer.Equals(node.Item.Value, value))
{
found = true;
return false; // stop the walk
}
return true;
});
}
return found;
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
_set.CopyTo(array, index);
}
public Enumerator GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
public bool Remove(TKey key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _set.Remove(new KeyValuePair<TKey, TValue>(key, default(TValue)));
}
public bool TryGetValue(TKey key, out TValue value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
TreeSet<KeyValuePair<TKey, TValue>>.Node node = _set.FindNode(new KeyValuePair<TKey, TValue>(key, default(TValue)));
if (node == null)
{
value = default(TValue);
return false;
}
value = node.Item.Value;
return true;
}
void ICollection.CopyTo(Array array, int index)
{
((ICollection)_set).CopyTo(array, index);
}
bool IDictionary.IsFixedSize
{
get { return false; }
}
bool IDictionary.IsReadOnly
{
get { return false; }
}
ICollection IDictionary.Keys
{
get { return (ICollection)Keys; }
}
ICollection IDictionary.Values
{
get { return (ICollection)Values; }
}
object IDictionary.this[object key]
{
get
{
if (IsCompatibleKey(key))
{
TValue value;
if (TryGetValue((TKey)key, out value))
{
return value;
}
}
return null;
}
set
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null && !(default(TValue) == null))
throw new ArgumentNullException(nameof(value));
try
{
TKey tempKey = (TKey)key;
try
{
this[tempKey] = (TValue)value;
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value));
}
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key));
}
}
}
void IDictionary.Add(object key, object value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null && !(default(TValue) == null))
throw new ArgumentNullException(nameof(value));
try
{
TKey tempKey = (TKey)key;
try
{
Add(tempKey, (TValue)value);
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value));
}
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key));
}
}
bool IDictionary.Contains(object key)
{
if (IsCompatibleKey(key))
{
return ContainsKey((TKey)key);
}
return false;
}
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return (key is TKey);
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new Enumerator(this, Enumerator.DictEntry);
}
void IDictionary.Remove(object key)
{
if (IsCompatibleKey(key))
{
Remove((TKey)key);
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_set).SyncRoot; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator
{
private TreeSet<KeyValuePair<TKey, TValue>>.Enumerator _treeEnum;
private int _getEnumeratorRetType; // What should Enumerator.Current return?
internal const int KeyValuePair = 1;
internal const int DictEntry = 2;
internal Enumerator(SortedDictionary<TKey, TValue> dictionary, int getEnumeratorRetType)
{
_treeEnum = dictionary._set.GetEnumerator();
_getEnumeratorRetType = getEnumeratorRetType;
}
public bool MoveNext()
{
return _treeEnum.MoveNext();
}
public void Dispose()
{
_treeEnum.Dispose();
}
public KeyValuePair<TKey, TValue> Current
{
get
{
return _treeEnum.Current;
}
}
internal bool NotStartedOrEnded
{
get
{
return _treeEnum.NotStartedOrEnded;
}
}
internal void Reset()
{
_treeEnum.Reset();
}
void IEnumerator.Reset()
{
_treeEnum.Reset();
}
object IEnumerator.Current
{
get
{
if (NotStartedOrEnded)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
if (_getEnumeratorRetType == DictEntry)
{
return new DictionaryEntry(Current.Key, Current.Value);
}
else
{
return new KeyValuePair<TKey, TValue>(Current.Key, Current.Value);
}
}
}
object IDictionaryEnumerator.Key
{
get
{
if (NotStartedOrEnded)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return Current.Key;
}
}
object IDictionaryEnumerator.Value
{
get
{
if (NotStartedOrEnded)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return Current.Value;
}
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if (NotStartedOrEnded)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return new DictionaryEntry(Current.Key, Current.Value);
}
}
}
[DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private SortedDictionary<TKey, TValue> _dictionary;
public KeyCollection(SortedDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
throw new ArgumentNullException(nameof(dictionary));
}
_dictionary = dictionary;
}
public Enumerator GetEnumerator()
{
return new Enumerator(_dictionary);
}
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator()
{
return new Enumerator(_dictionary);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(_dictionary);
}
public void CopyTo(TKey[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
_dictionary._set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node) { array[index++] = node.Item.Key; return true; });
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < _dictionary.Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
TKey[] keys = array as TKey[];
if (keys != null)
{
CopyTo(keys, index);
}
else
{
try
{
object[] objects = (object[])array;
_dictionary._set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node) { objects[index++] = node.Item.Key; return true; });
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
}
public int Count
{
get { return _dictionary.Count; }
}
bool ICollection<TKey>.IsReadOnly
{
get { return true; }
}
void ICollection<TKey>.Add(TKey item)
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
void ICollection<TKey>.Clear()
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
bool ICollection<TKey>.Contains(TKey item)
{
return _dictionary.ContainsKey(item);
}
bool ICollection<TKey>.Remove(TKey item)
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_dictionary).SyncRoot; }
}
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<TKey>, IEnumerator
{
private SortedDictionary<TKey, TValue>.Enumerator _dictEnum;
internal Enumerator(SortedDictionary<TKey, TValue> dictionary)
{
_dictEnum = dictionary.GetEnumerator();
}
public void Dispose()
{
_dictEnum.Dispose();
}
public bool MoveNext()
{
return _dictEnum.MoveNext();
}
public TKey Current
{
get
{
return _dictEnum.Current.Key;
}
}
object IEnumerator.Current
{
get
{
if (_dictEnum.NotStartedOrEnded)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return Current;
}
}
void IEnumerator.Reset()
{
_dictEnum.Reset();
}
}
}
[DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private SortedDictionary<TKey, TValue> _dictionary;
public ValueCollection(SortedDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
throw new ArgumentNullException(nameof(dictionary));
}
_dictionary = dictionary;
}
public Enumerator GetEnumerator()
{
return new Enumerator(_dictionary);
}
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator()
{
return new Enumerator(_dictionary);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(_dictionary);
}
public void CopyTo(TValue[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
_dictionary._set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node) { array[index++] = node.Item.Value; return true; });
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < _dictionary.Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
TValue[] values = array as TValue[];
if (values != null)
{
CopyTo(values, index);
}
else
{
try
{
object[] objects = (object[])array;
_dictionary._set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node) { objects[index++] = node.Item.Value; return true; });
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
}
public int Count
{
get { return _dictionary.Count; }
}
bool ICollection<TValue>.IsReadOnly
{
get { return true; }
}
void ICollection<TValue>.Add(TValue item)
{
throw new NotSupportedException(SR.NotSupported_ValueCollectionSet);
}
void ICollection<TValue>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ValueCollectionSet);
}
bool ICollection<TValue>.Contains(TValue item)
{
return _dictionary.ContainsValue(item);
}
bool ICollection<TValue>.Remove(TValue item)
{
throw new NotSupportedException(SR.NotSupported_ValueCollectionSet);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_dictionary).SyncRoot; }
}
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<TValue>, IEnumerator
{
private SortedDictionary<TKey, TValue>.Enumerator _dictEnum;
internal Enumerator(SortedDictionary<TKey, TValue> dictionary)
{
_dictEnum = dictionary.GetEnumerator();
}
public void Dispose()
{
_dictEnum.Dispose();
}
public bool MoveNext()
{
return _dictEnum.MoveNext();
}
public TValue Current
{
get
{
return _dictEnum.Current.Value;
}
}
object IEnumerator.Current
{
get
{
if (_dictEnum.NotStartedOrEnded)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return Current;
}
}
void IEnumerator.Reset()
{
_dictEnum.Reset();
}
}
}
[Serializable]
public sealed class KeyValuePairComparer : Comparer<KeyValuePair<TKey, TValue>>
{
internal IComparer<TKey> keyComparer; // Do not rename (binary serialization)
public KeyValuePairComparer(IComparer<TKey> keyComparer)
{
if (keyComparer == null)
{
this.keyComparer = Comparer<TKey>.Default;
}
else
{
this.keyComparer = keyComparer;
}
}
public override int Compare(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y)
{
return keyComparer.Compare(x.Key, y.Key);
}
}
}
/// <summary>
/// This class is intended as a helper for backwards compatibility with existing SortedDictionaries.
/// TreeSet has been converted into SortedSet<T>, which will be exposed publicly. SortedDictionaries
/// have the problem where they have already been serialized to disk as having a backing class named
/// TreeSet. To ensure that we can read back anything that has already been written to disk, we need to
/// make sure that we have a class named TreeSet that does everything the way it used to.
///
/// The only thing that makes it different from SortedSet is that it throws on duplicates
/// </summary>
/// <typeparam name="T"></typeparam>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class TreeSet<T> : SortedSet<T>
{
public TreeSet()
: base()
{ }
public TreeSet(IComparer<T> comparer) : base(comparer) { }
private TreeSet(SerializationInfo siInfo, StreamingContext context) : base(siInfo, context) { }
internal override bool AddIfNotPresent(T item)
{
bool ret = base.AddIfNotPresent(item);
if (!ret)
{
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, item));
}
return ret;
}
}
}
| |
// Copyright 2021 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 gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.DataQnA.V1Alpha
{
/// <summary>Settings for <see cref="AutoSuggestionServiceClient"/> instances.</summary>
public sealed partial class AutoSuggestionServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AutoSuggestionServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AutoSuggestionServiceSettings"/>.</returns>
public static AutoSuggestionServiceSettings GetDefault() => new AutoSuggestionServiceSettings();
/// <summary>
/// Constructs a new <see cref="AutoSuggestionServiceSettings"/> object with default settings.
/// </summary>
public AutoSuggestionServiceSettings()
{
}
private AutoSuggestionServiceSettings(AutoSuggestionServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
SuggestQueriesSettings = existing.SuggestQueriesSettings;
OnCopy(existing);
}
partial void OnCopy(AutoSuggestionServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AutoSuggestionServiceClient.SuggestQueries</c> and <c>AutoSuggestionServiceClient.SuggestQueriesAsync</c>
/// .
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 2 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings SuggestQueriesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(2000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AutoSuggestionServiceSettings"/> object.</returns>
public AutoSuggestionServiceSettings Clone() => new AutoSuggestionServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AutoSuggestionServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
public sealed partial class AutoSuggestionServiceClientBuilder : gaxgrpc::ClientBuilderBase<AutoSuggestionServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AutoSuggestionServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AutoSuggestionServiceClientBuilder()
{
UseJwtAccessWithScopes = AutoSuggestionServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AutoSuggestionServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AutoSuggestionServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AutoSuggestionServiceClient Build()
{
AutoSuggestionServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AutoSuggestionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AutoSuggestionServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AutoSuggestionServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AutoSuggestionServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AutoSuggestionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AutoSuggestionServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AutoSuggestionServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AutoSuggestionServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AutoSuggestionServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AutoSuggestionService client wrapper, for convenient use.</summary>
/// <remarks>
/// This stateless API provides automatic suggestions for natural language
/// queries for the data sources in the provided project and location.
///
/// The service provides a resourceless operation `suggestQueries` that can be
/// called to get a list of suggestions for a given incomplete query and scope
/// (or list of scopes) under which the query is to be interpreted.
///
/// There are two types of suggestions, ENTITY for single entity suggestions
/// and TEMPLATE for full sentences. By default, both types are returned.
///
/// Example Request:
/// ```
/// GetSuggestions({
/// parent: "locations/us/projects/my-project"
/// scopes:
/// "//bigquery.googleapis.com/projects/my-project/datasets/my-dataset/tables/my-table"
/// query: "top it"
/// })
/// ```
///
/// The service will retrieve information based on the given scope(s) and give
/// suggestions based on that (e.g. "top item" for "top it" if "item" is a known
/// dimension for the provided scope).
/// ```
/// suggestions {
/// suggestion_info {
/// annotated_suggestion {
/// text_formatted: "top item by sum of usd_revenue_net"
/// markups {
/// type: DIMENSION
/// start_char_index: 4
/// length: 4
/// }
/// markups {
/// type: METRIC
/// start_char_index: 19
/// length: 15
/// }
/// }
/// query_matches {
/// start_char_index: 0
/// length: 6
/// }
/// }
/// suggestion_type: TEMPLATE
/// ranking_score: 0.9
/// }
/// suggestions {
/// suggestion_info {
/// annotated_suggestion {
/// text_formatted: "item"
/// markups {
/// type: DIMENSION
/// start_char_index: 4
/// length: 2
/// }
/// }
/// query_matches {
/// start_char_index: 0
/// length: 6
/// }
/// }
/// suggestion_type: ENTITY
/// ranking_score: 0.8
/// }
/// ```
/// </remarks>
public abstract partial class AutoSuggestionServiceClient
{
/// <summary>
/// The default endpoint for the AutoSuggestionService service, which is a host of "dataqna.googleapis.com" and
/// a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "dataqna.googleapis.com:443";
/// <summary>The default AutoSuggestionService scopes.</summary>
/// <remarks>
/// The default AutoSuggestionService scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AutoSuggestionServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="AutoSuggestionServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AutoSuggestionServiceClient"/>.</returns>
public static stt::Task<AutoSuggestionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AutoSuggestionServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AutoSuggestionServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="AutoSuggestionServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AutoSuggestionServiceClient"/>.</returns>
public static AutoSuggestionServiceClient Create() => new AutoSuggestionServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AutoSuggestionServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AutoSuggestionServiceSettings"/>.</param>
/// <returns>The created <see cref="AutoSuggestionServiceClient"/>.</returns>
internal static AutoSuggestionServiceClient Create(grpccore::CallInvoker callInvoker, AutoSuggestionServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AutoSuggestionService.AutoSuggestionServiceClient grpcClient = new AutoSuggestionService.AutoSuggestionServiceClient(callInvoker);
return new AutoSuggestionServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AutoSuggestionService client</summary>
public virtual AutoSuggestionService.AutoSuggestionServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Gets a list of suggestions based on a prefix string.
/// AutoSuggestion tolerance should be less than 1 second.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual SuggestQueriesResponse SuggestQueries(SuggestQueriesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets a list of suggestions based on a prefix string.
/// AutoSuggestion tolerance should be less than 1 second.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<SuggestQueriesResponse> SuggestQueriesAsync(SuggestQueriesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets a list of suggestions based on a prefix string.
/// AutoSuggestion tolerance should be less than 1 second.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<SuggestQueriesResponse> SuggestQueriesAsync(SuggestQueriesRequest request, st::CancellationToken cancellationToken) =>
SuggestQueriesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AutoSuggestionService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// This stateless API provides automatic suggestions for natural language
/// queries for the data sources in the provided project and location.
///
/// The service provides a resourceless operation `suggestQueries` that can be
/// called to get a list of suggestions for a given incomplete query and scope
/// (or list of scopes) under which the query is to be interpreted.
///
/// There are two types of suggestions, ENTITY for single entity suggestions
/// and TEMPLATE for full sentences. By default, both types are returned.
///
/// Example Request:
/// ```
/// GetSuggestions({
/// parent: "locations/us/projects/my-project"
/// scopes:
/// "//bigquery.googleapis.com/projects/my-project/datasets/my-dataset/tables/my-table"
/// query: "top it"
/// })
/// ```
///
/// The service will retrieve information based on the given scope(s) and give
/// suggestions based on that (e.g. "top item" for "top it" if "item" is a known
/// dimension for the provided scope).
/// ```
/// suggestions {
/// suggestion_info {
/// annotated_suggestion {
/// text_formatted: "top item by sum of usd_revenue_net"
/// markups {
/// type: DIMENSION
/// start_char_index: 4
/// length: 4
/// }
/// markups {
/// type: METRIC
/// start_char_index: 19
/// length: 15
/// }
/// }
/// query_matches {
/// start_char_index: 0
/// length: 6
/// }
/// }
/// suggestion_type: TEMPLATE
/// ranking_score: 0.9
/// }
/// suggestions {
/// suggestion_info {
/// annotated_suggestion {
/// text_formatted: "item"
/// markups {
/// type: DIMENSION
/// start_char_index: 4
/// length: 2
/// }
/// }
/// query_matches {
/// start_char_index: 0
/// length: 6
/// }
/// }
/// suggestion_type: ENTITY
/// ranking_score: 0.8
/// }
/// ```
/// </remarks>
public sealed partial class AutoSuggestionServiceClientImpl : AutoSuggestionServiceClient
{
private readonly gaxgrpc::ApiCall<SuggestQueriesRequest, SuggestQueriesResponse> _callSuggestQueries;
/// <summary>
/// Constructs a client wrapper for the AutoSuggestionService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="AutoSuggestionServiceSettings"/> used within this client.</param>
public AutoSuggestionServiceClientImpl(AutoSuggestionService.AutoSuggestionServiceClient grpcClient, AutoSuggestionServiceSettings settings)
{
GrpcClient = grpcClient;
AutoSuggestionServiceSettings effectiveSettings = settings ?? AutoSuggestionServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callSuggestQueries = clientHelper.BuildApiCall<SuggestQueriesRequest, SuggestQueriesResponse>(grpcClient.SuggestQueriesAsync, grpcClient.SuggestQueries, effectiveSettings.SuggestQueriesSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callSuggestQueries);
Modify_SuggestQueriesApiCall(ref _callSuggestQueries);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_SuggestQueriesApiCall(ref gaxgrpc::ApiCall<SuggestQueriesRequest, SuggestQueriesResponse> call);
partial void OnConstruction(AutoSuggestionService.AutoSuggestionServiceClient grpcClient, AutoSuggestionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AutoSuggestionService client</summary>
public override AutoSuggestionService.AutoSuggestionServiceClient GrpcClient { get; }
partial void Modify_SuggestQueriesRequest(ref SuggestQueriesRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Gets a list of suggestions based on a prefix string.
/// AutoSuggestion tolerance should be less than 1 second.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override SuggestQueriesResponse SuggestQueries(SuggestQueriesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SuggestQueriesRequest(ref request, ref callSettings);
return _callSuggestQueries.Sync(request, callSettings);
}
/// <summary>
/// Gets a list of suggestions based on a prefix string.
/// AutoSuggestion tolerance should be less than 1 second.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<SuggestQueriesResponse> SuggestQueriesAsync(SuggestQueriesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SuggestQueriesRequest(ref request, ref callSettings);
return _callSuggestQueries.Async(request, callSettings);
}
}
}
| |
using Bridge.Contract;
using Bridge.Contract.Constants;
using ICSharpCode.NRefactory.CSharp;
using Object.Net.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.Semantics;
namespace Bridge.Translator
{
public class TryCatchBlock : AbstractEmitterBlock
{
public TryCatchBlock(IEmitter emitter, TryCatchStatement tryCatchStatement)
: base(emitter, tryCatchStatement)
{
this.Emitter = emitter;
this.TryCatchStatement = tryCatchStatement;
}
public TryCatchStatement TryCatchStatement
{
get;
set;
}
protected override void DoEmit()
{
var awaiters = this.Emitter.IsAsync ? this.GetAwaiters(this.TryCatchStatement) : null;
if (awaiters != null && awaiters.Length > 0)
{
this.VisitAsyncTryCatchStatement();
}
else
{
this.VisitTryCatchStatement();
}
}
protected void VisitAsyncTryCatchStatement()
{
TryCatchStatement tryCatchStatement = this.TryCatchStatement;
this.Emitter.AsyncBlock.Steps.Last().JumpToStep = this.Emitter.AsyncBlock.Step;
var tryStep = this.Emitter.AsyncBlock.AddAsyncStep();
AsyncTryInfo tryInfo = new AsyncTryInfo();
tryInfo.StartStep = tryStep.Step;
this.Emitter.IgnoreBlock = tryCatchStatement.TryBlock;
tryCatchStatement.TryBlock.AcceptVisitor(this.Emitter);
tryStep = this.Emitter.AsyncBlock.Steps.Last();
tryInfo.EndStep = tryStep.Step;
List<IAsyncStep> catchSteps = new List<IAsyncStep>();
foreach (var clause in tryCatchStatement.CatchClauses)
{
var catchStep = this.Emitter.AsyncBlock.AddAsyncStep();
this.PushLocals();
var varName = clause.VariableName;
if (!String.IsNullOrEmpty(varName) && !this.Emitter.Locals.ContainsKey(varName))
{
varName = this.AddLocal(varName, clause.VariableNameToken, clause.Type);
}
this.Emitter.IgnoreBlock = clause.Body;
clause.Body.AcceptVisitor(this.Emitter);
Write(JS.Vars.ASYNC_E + " = null;");
this.PopLocals();
this.WriteNewLine();
tryInfo.CatchBlocks.Add(new Tuple<string, string, int, int>(varName, clause.Type.IsNull ? JS.Types.System.Exception.NAME : BridgeTypes.ToJsName(clause.Type, this.Emitter), catchStep.Step, Emitter.AsyncBlock.Steps.Last().Step));
catchSteps.Add(Emitter.AsyncBlock.Steps.Last());
}
if (!this.Emitter.Locals.ContainsKey(JS.Vars.ASYNC_E))
{
this.AddLocal(JS.Vars.ASYNC_E, null, AstType.Null);
}
IAsyncStep finalyStep = null;
if (!tryCatchStatement.FinallyBlock.IsNull)
{
finalyStep = this.Emitter.AsyncBlock.AddAsyncStep(tryCatchStatement.FinallyBlock);
this.Emitter.IgnoreBlock = tryCatchStatement.FinallyBlock;
tryCatchStatement.FinallyBlock.AcceptVisitor(this.Emitter);
var finallyNode = this.GetParentFinallyBlock(tryCatchStatement, false);
this.WriteNewLine();
this.WriteIf();
this.WriteOpenParentheses();
this.Write(JS.Vars.ASYNC_JUMP + " > -1");
this.WriteCloseParentheses();
this.WriteSpace();
this.BeginBlock();
if (finallyNode != null)
{
var hashcode = finallyNode.GetHashCode();
this.Emitter.AsyncBlock.JumpLabels.Add(new AsyncJumpLabel
{
Node = finallyNode,
Output = this.Emitter.Output
});
this.Write(JS.Vars.ASYNC_STEP + " = " + Helpers.PrefixDollar("{", hashcode, "};"));
this.WriteNewLine();
this.Write("continue;");
}
else
{
this.Write(JS.Vars.ASYNC_STEP + " = " + JS.Vars.ASYNC_JUMP + ";");
this.WriteNewLine();
this.Write(JS.Vars.ASYNC_JUMP + " = null;");
}
this.WriteNewLine();
this.EndBlock();
this.WriteSpace();
this.WriteElse();
this.WriteIf();
this.WriteOpenParentheses();
this.Write(JS.Vars.ASYNC_E);
this.WriteCloseParentheses();
this.WriteSpace();
this.BeginBlock();
if (this.Emitter.AsyncBlock.IsTaskReturn)
{
this.Write(JS.Vars.ASYNC_TCS + "." + JS.Funcs.SET_EXCEPTION + "(" + JS.Vars.ASYNC_E + ");");
}
else
{
this.Write("throw " + JS.Vars.ASYNC_E + ";");
}
this.WriteNewLine();
this.WriteReturn(false);
this.WriteSemiColon();
this.WriteNewLine();
this.EndBlock();
this.WriteSpace();
this.WriteElse();
this.WriteIf();
this.WriteOpenParentheses();
this.Write(JS.Funcs.BRIDGE_IS_DEFINED);
this.WriteOpenParentheses();
this.Write(JS.Vars.ASYNC_RETURN_VALUE);
this.WriteCloseParentheses();
this.WriteCloseParentheses();
this.WriteSpace();
this.BeginBlock();
if (finallyNode != null)
{
var hashcode = finallyNode.GetHashCode();
this.Emitter.AsyncBlock.JumpLabels.Add(new AsyncJumpLabel
{
Node = finallyNode,
Output = this.Emitter.Output
});
this.Write(JS.Vars.ASYNC_STEP + " = " + Helpers.PrefixDollar("{", hashcode, "};"));
this.WriteNewLine();
this.Write("continue;");
}
else
{
this.Write(JS.Vars.ASYNC_TCS + "." + JS.Funcs.SET_RESULT + "(" + JS.Vars.ASYNC_RETURN_VALUE + ");");
this.WriteNewLine();
this.WriteReturn(false);
this.WriteSemiColon();
}
this.WriteNewLine();
this.EndBlock();
if (!this.Emitter.Locals.ContainsKey(JS.Vars.ASYNC_E))
{
this.AddLocal(JS.Vars.ASYNC_E, null, AstType.Null);
}
}
var lastFinallyStep = Emitter.AsyncBlock.Steps.Last();
var nextStep = this.Emitter.AsyncBlock.AddAsyncStep();
if (finalyStep != null)
{
tryInfo.FinallyStep = finalyStep.Step;
lastFinallyStep.JumpToStep = nextStep.Step;
}
tryStep.JumpToStep = finalyStep != null ? finalyStep.Step : nextStep.Step;
foreach (var step in catchSteps)
{
step.JumpToStep = finalyStep != null ? finalyStep.Step : nextStep.Step;
}
this.Emitter.AsyncBlock.TryInfos.Add(tryInfo);
}
protected void VisitTryCatchStatement()
{
this.EmitTryBlock();
var count = this.TryCatchStatement.CatchClauses.Count;
if (count > 0)
{
var firstClause = this.TryCatchStatement.CatchClauses.Count == 1 ? this.TryCatchStatement.CatchClauses.First() : null;
var exceptionType = (firstClause == null || firstClause.Type.IsNull) ? null : BridgeTypes.ToJsName(firstClause.Type, this.Emitter);
var isBaseException = exceptionType == null || exceptionType == JS.Types.System.Exception.NAME;
if (count == 1 && isBaseException)
{
this.EmitSingleCatchBlock();
}
else
{
this.EmitMultipleCatchBlock();
}
}
this.EmitFinallyBlock();
}
protected virtual void EmitTryBlock()
{
TryCatchStatement tryCatchStatement = this.TryCatchStatement;
this.WriteTry();
tryCatchStatement.TryBlock.AcceptVisitor(this.Emitter);
}
protected virtual void EmitFinallyBlock()
{
TryCatchStatement tryCatchStatement = this.TryCatchStatement;
if (!tryCatchStatement.FinallyBlock.IsNull)
{
this.WriteSpace();
this.WriteFinally();
tryCatchStatement.FinallyBlock.AcceptVisitor(this.Emitter);
}
}
protected virtual void EmitSingleCatchBlock()
{
TryCatchStatement tryCatchStatement = this.TryCatchStatement;
foreach (var clause in tryCatchStatement.CatchClauses)
{
this.PushLocals();
var varName = clause.VariableName;
if (String.IsNullOrEmpty(varName))
{
varName = this.AddLocal(this.GetUniqueName(JS.Vars.E), null, AstType.Null);
}
else
{
varName = this.AddLocal(varName, clause.VariableNameToken, clause.Type);
}
var oldVar = this.Emitter.CatchBlockVariable;
this.Emitter.CatchBlockVariable = varName;
this.WriteSpace();
this.WriteCatch();
this.WriteOpenParentheses();
this.Write(varName);
this.WriteCloseParentheses();
this.WriteSpace();
this.BeginBlock();
this.Write(string.Format("{0} = " + JS.Types.System.Exception.CREATE + "({0});", varName));
this.WriteNewLine();
this.Emitter.NoBraceBlock = clause.Body;
clause.Body.AcceptVisitor(this.Emitter);
if (!this.Emitter.IsNewLine)
{
this.WriteNewLine();
}
this.EndBlock();
if (tryCatchStatement.FinallyBlock.IsNull)
{
this.WriteNewLine();
}
this.PopLocals();
this.Emitter.CatchBlockVariable = oldVar;
}
}
protected virtual void EmitMultipleCatchBlock()
{
TryCatchStatement tryCatchStatement = this.TryCatchStatement;
this.WriteSpace();
this.WriteCatch();
this.WriteOpenParentheses();
var varName = this.AddLocal(this.GetUniqueName(JS.Vars.E), null, AstType.Null);
var oldVar = this.Emitter.CatchBlockVariable;
this.Emitter.CatchBlockVariable = varName;
this.Write(varName);
this.WriteCloseParentheses();
this.WriteSpace();
this.BeginBlock();
this.Write(string.Format("{0} = " + JS.Types.System.Exception.CREATE + "({0});", varName));
this.WriteNewLine();
var catchVars = new Dictionary<string, string>();
var writeVar = false;
foreach (var clause in tryCatchStatement.CatchClauses)
{
if (clause.VariableName.IsNotEmpty() && !catchVars.ContainsKey(clause.VariableName))
{
if (!writeVar)
{
writeVar = true;
this.WriteVar(true);
}
this.EnsureComma(false);
catchVars.Add(clause.VariableName, clause.VariableName);
this.Write(clause.VariableName);
this.Emitter.Comma = true;
}
}
this.Emitter.Comma = false;
if (writeVar)
{
this.WriteSemiColon(true);
}
var firstClause = true;
var writeElse = true;
var needNewLine = false;
foreach (var clause in tryCatchStatement.CatchClauses)
{
var exceptionType = clause.Type.IsNull ? null : BridgeTypes.ToJsName(clause.Type, this.Emitter);
var isBaseException = exceptionType == null || exceptionType == JS.Types.System.Exception.NAME;
if (!firstClause)
{
this.WriteSpace();
this.WriteElse();
}
if (isBaseException)
{
writeElse = false;
}
else
{
this.WriteIf();
this.WriteOpenParentheses();
this.Write(string.Format(JS.Types.Bridge.IS + "({0}, {1})", varName, exceptionType));
this.WriteCloseParentheses();
this.WriteSpace();
}
firstClause = false;
this.PushLocals();
this.BeginBlock();
if (clause.VariableName.IsNotEmpty())
{
this.Write(clause.VariableName + " = " + varName);
this.WriteSemiColon();
this.WriteNewLine();
}
this.Emitter.NoBraceBlock = clause.Body;
clause.Body.AcceptVisitor(this.Emitter);
this.Emitter.NoBraceBlock = null;
this.EndBlock();
needNewLine = true;
this.PopLocals();
}
if (writeElse)
{
this.WriteSpace();
this.WriteElse();
this.BeginBlock();
this.Write("throw " + varName);
this.WriteSemiColon();
this.WriteNewLine();
this.EndBlock();
needNewLine = true;
}
if (needNewLine)
{
this.WriteNewLine();
needNewLine = false;
}
this.EndBlock();
if (tryCatchStatement.FinallyBlock.IsNull)
{
this.WriteNewLine();
}
this.Emitter.CatchBlockVariable = oldVar;
}
}
public class AsyncTryInfo : IAsyncTryInfo
{
public int StartStep
{
get;
set;
}
public int EndStep
{
get;
set;
}
public int FinallyStep
{
get;
set;
}
private List<Tuple<string, string, int, int>> catchBlocks;
public List<Tuple<string, string, int, int>> CatchBlocks
{
get
{
if (this.catchBlocks == null)
{
this.catchBlocks = new List<Tuple<string, string, int, int>>();
}
return this.catchBlocks;
}
}
}
}
| |
// 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.Text;
namespace System.Net.Http.Headers
{
public class ViaHeaderValue : ICloneable
{
private string _protocolName;
private string _protocolVersion;
private string _receivedBy;
private string _comment;
public string ProtocolName
{
get { return _protocolName; }
}
public string ProtocolVersion
{
get { return _protocolVersion; }
}
public string ReceivedBy
{
get { return _receivedBy; }
}
public string Comment
{
get { return _comment; }
}
public ViaHeaderValue(string protocolVersion, string receivedBy)
: this(protocolVersion, receivedBy, null, null)
{
}
public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName)
: this(protocolVersion, receivedBy, protocolName, null)
{
}
public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName, string comment)
{
HeaderUtilities.CheckValidToken(protocolVersion, nameof(protocolVersion));
CheckReceivedBy(receivedBy);
if (!string.IsNullOrEmpty(protocolName))
{
HeaderUtilities.CheckValidToken(protocolName, nameof(protocolName));
_protocolName = protocolName;
}
if (!string.IsNullOrEmpty(comment))
{
HeaderUtilities.CheckValidComment(comment, nameof(comment));
_comment = comment;
}
_protocolVersion = protocolVersion;
_receivedBy = receivedBy;
}
private ViaHeaderValue()
{
}
private ViaHeaderValue(ViaHeaderValue source)
{
Debug.Assert(source != null);
_protocolName = source._protocolName;
_protocolVersion = source._protocolVersion;
_receivedBy = source._receivedBy;
_comment = source._comment;
}
public override string ToString()
{
StringBuilder sb = StringBuilderCache.Acquire();
if (!string.IsNullOrEmpty(_protocolName))
{
sb.Append(_protocolName);
sb.Append('/');
}
sb.Append(_protocolVersion);
sb.Append(' ');
sb.Append(_receivedBy);
if (!string.IsNullOrEmpty(_comment))
{
sb.Append(' ');
sb.Append(_comment);
}
return StringBuilderCache.GetStringAndRelease(sb);
}
public override bool Equals(object obj)
{
ViaHeaderValue other = obj as ViaHeaderValue;
if (other == null)
{
return false;
}
// Note that for token and host case-insensitive comparison is used. Comments are compared using case-
// sensitive comparison.
return string.Equals(_protocolVersion, other._protocolVersion, StringComparison.OrdinalIgnoreCase) &&
string.Equals(_receivedBy, other._receivedBy, StringComparison.OrdinalIgnoreCase) &&
string.Equals(_protocolName, other._protocolName, StringComparison.OrdinalIgnoreCase) &&
string.Equals(_comment, other._comment, StringComparison.Ordinal);
}
public override int GetHashCode()
{
int result = StringComparer.OrdinalIgnoreCase.GetHashCode(_protocolVersion) ^
StringComparer.OrdinalIgnoreCase.GetHashCode(_receivedBy);
if (!string.IsNullOrEmpty(_protocolName))
{
result = result ^ StringComparer.OrdinalIgnoreCase.GetHashCode(_protocolName);
}
if (!string.IsNullOrEmpty(_comment))
{
result = result ^ _comment.GetHashCode();
}
return result;
}
public static ViaHeaderValue Parse(string input)
{
int index = 0;
return (ViaHeaderValue)GenericHeaderParser.SingleValueViaParser.ParseValue(input, null, ref index);
}
public static bool TryParse(string input, out ViaHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (GenericHeaderParser.SingleValueViaParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (ViaHeaderValue)output;
return true;
}
return false;
}
internal static int GetViaLength(string input, int startIndex, out object parsedValue)
{
Debug.Assert(startIndex >= 0);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Read <protocolName> and <protocolVersion> in '[<protocolName>/]<protocolVersion> <receivedBy> [<comment>]'
string protocolName = null;
string protocolVersion = null;
int current = GetProtocolEndIndex(input, startIndex, out protocolName, out protocolVersion);
// If we reached the end of the string after reading protocolName/Version we return (we expect at least
// <receivedBy> to follow). If reading protocolName/Version read 0 bytes, we return.
if ((current == startIndex) || (current == input.Length))
{
return 0;
}
Debug.Assert(protocolVersion != null);
// Read <receivedBy> in '[<protocolName>/]<protocolVersion> <receivedBy> [<comment>]'
string receivedBy = null;
int receivedByLength = HttpRuleParser.GetHostLength(input, current, true, out receivedBy);
if (receivedByLength == 0)
{
return 0;
}
current = current + receivedByLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
string comment = null;
if ((current < input.Length) && (input[current] == '('))
{
// We have a <comment> in '[<protocolName>/]<protocolVersion> <receivedBy> [<comment>]'
int commentLength = 0;
if (HttpRuleParser.GetCommentLength(input, current, out commentLength) != HttpParseResult.Parsed)
{
return 0; // We found a '(' character but it wasn't a valid comment. Abort.
}
comment = input.Substring(current, commentLength);
current = current + commentLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
ViaHeaderValue result = new ViaHeaderValue();
result._protocolVersion = protocolVersion;
result._protocolName = protocolName;
result._receivedBy = receivedBy;
result._comment = comment;
parsedValue = result;
return current - startIndex;
}
private static int GetProtocolEndIndex(string input, int startIndex, out string protocolName,
out string protocolVersion)
{
// We have a string of the form '[<protocolName>/]<protocolVersion> <receivedBy> [<comment>]'. The first
// token may either be the protocol name or protocol version. We'll only find out after reading the token
// and by looking at the following character: If it is a '/' we just parsed the protocol name, otherwise
// the protocol version.
protocolName = null;
protocolVersion = null;
int current = startIndex;
int protocolVersionOrNameLength = HttpRuleParser.GetTokenLength(input, current);
if (protocolVersionOrNameLength == 0)
{
return 0;
}
current = startIndex + protocolVersionOrNameLength;
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
if (current == input.Length)
{
return 0;
}
if (input[current] == '/')
{
// We parsed the protocol name
protocolName = input.Substring(startIndex, protocolVersionOrNameLength);
current++; // skip the '/' delimiter
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
protocolVersionOrNameLength = HttpRuleParser.GetTokenLength(input, current);
if (protocolVersionOrNameLength == 0)
{
return 0; // We have a string "<token>/" followed by non-token chars. This is invalid.
}
protocolVersion = input.Substring(current, protocolVersionOrNameLength);
current = current + protocolVersionOrNameLength;
whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
}
else
{
protocolVersion = input.Substring(startIndex, protocolVersionOrNameLength);
}
if (whitespaceLength == 0)
{
return 0; // We were able to parse [<protocolName>/]<protocolVersion> but it wasn't followed by a WS
}
return current;
}
object ICloneable.Clone()
{
return new ViaHeaderValue(this);
}
private static void CheckReceivedBy(string receivedBy)
{
if (string.IsNullOrEmpty(receivedBy))
{
throw new ArgumentException(SR.net_http_argument_empty_string, nameof(receivedBy));
}
// 'receivedBy' can either be a host or a token. Since a token is a valid host, we only verify if the value
// is a valid host.
string host = null;
if (HttpRuleParser.GetHostLength(receivedBy, 0, true, out host) != receivedBy.Length)
{
throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, receivedBy));
}
}
}
}
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com)
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// 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.IO;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using PdfSharp.Drawing;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using MigraDoc.Rendering;
using MigraDoc.RtfRendering.Resources;
namespace MigraDoc.RtfRendering
{
/// <summary>
/// Summary description for ChartRenderer.
/// </summary>
internal class ChartRenderer : ShapeRenderer
{
internal ChartRenderer(DocumentObject domObj, RtfDocumentRenderer docRenderer)
: base(domObj, docRenderer)
{
this.chart = (Chart)domObj;
this.isInline = DocumentRelations.HasParentOfType(this.chart, typeof(Paragraph)) ||
RenderInParagraph();
}
/// <summary>
/// Renders an image to RTF.
/// </summary>
internal override void Render()
{
string fileName = System.IO.Path.GetTempFileName();
if (!StoreTempImage(fileName))
return;
bool renderInParagraph = RenderInParagraph();
DocumentElements elms = DocumentRelations.GetParent(this.chart) as DocumentElements;
if (elms != null && !renderInParagraph && !(DocumentRelations.GetParent(elms) is Section || DocumentRelations.GetParent(elms) is HeaderFooter))
{
Trace.WriteLine(Messages.ChartFreelyPlacedInWrongContext, "warning");
return;
}
if (renderInParagraph)
StartDummyParagraph();
if (!this.isInline)
StartShapeArea();
RenderImage(fileName);
if (!this.isInline)
EndShapeArea();
if (renderInParagraph)
EndDummyParagraph();
if (File.Exists(fileName))
File.Delete(fileName);
}
/// <summary>
/// Renders image specific attributes and the image byte series to RTF.
/// </summary>
void RenderImage(string fileName)
{
StartImageDescription();
RenderImageAttributes();
RenderByteSeries(fileName);
EndImageDescription();
}
void StartImageDescription()
{
if (isInline)
{
this.rtfWriter.StartContent();
this.rtfWriter.WriteControlWithStar("shppict");
this.rtfWriter.StartContent();
this.rtfWriter.WriteControl("pict");
}
else
{
RenderNameValuePair("shapeType", "75");//75 entspr. Bildrahmen.
StartNameValuePair("pib");
this.rtfWriter.StartContent();
this.rtfWriter.WriteControl("pict");
}
}
void EndImageDescription()
{
if (isInline)
{
this.rtfWriter.EndContent();
this.rtfWriter.EndContent();
}
else
{
this.rtfWriter.EndContent();
EndNameValuePair();
}
}
void RenderImageAttributes()
{
if (this.isInline)
{
this.rtfWriter.StartContent();
this.rtfWriter.WriteControlWithStar("picprop");
RenderNameValuePair("shapeType", "75");
RenderFillFormat();
//REM: LineFormat is not completely supported in word.
//RenderLineFormat();
this.rtfWriter.EndContent();
}
RenderDimensionSettings();
RenderSourceType();
}
private void RenderSourceType()
{
this.rtfWriter.WriteControl("pngblip");
}
/// <summary>
/// Renders scaling, width and height for the image.
/// </summary>
private void RenderDimensionSettings()
{
this.rtfWriter.WriteControl("picscalex", 100);
this.rtfWriter.WriteControl("picscaley", 100);
RenderUnit("pichgoal", GetShapeHeight());
RenderUnit("picwgoal", GetShapeWidth());
//A bit obscure, but necessary for Word 2000:
this.rtfWriter.WriteControl("pich", (int)(GetShapeHeight().Millimeter * 100));
this.rtfWriter.WriteControl("picw", (int)(GetShapeWidth().Millimeter * 100));
}
bool StoreTempImage(string fileName)
{
try
{
float resolution = 96;
int horzPixels = (int)(GetShapeWidth().Inch * resolution);
int vertPixels = (int)(GetShapeHeight().Inch * resolution);
Bitmap bmp = new Bitmap(horzPixels, vertPixels);
#if true
XGraphics gfx = XGraphics.CreateMeasureContext(new XSize(horzPixels, vertPixels), XGraphicsUnit.Point, XPageDirection.Downwards);
#else
#if GDI
XGraphics gfx = XGraphics.FromGraphics(Graphics.FromImage(bmp), new XSize(horzPixels, vertPixels));
#endif
#if WPF
// TODOWPF
XGraphics gfx = null; //XGraphics.FromGraphics(Graphics.FromImage(bmp), new XSize(horzPixels, vertPixels));
#endif
#endif
//REM: Should not be necessary:
gfx.ScaleTransform(resolution / 72);
//gfx.PageUnit = XGraphicsUnit.Point;
DocumentRenderer renderer = new DocumentRenderer(this.chart.Document);
renderer.RenderObject(gfx, 0, 0, GetShapeWidth().Point, this.chart);
bmp.SetResolution(resolution, resolution);
bmp.Save(fileName, ImageFormat.Png);
}
catch (Exception)
{
return false;
}
return true;
}
/*private void CalculateImageDimensions()
{
try
{
this.imageFile = File.OpenRead(this.filePath);
System.Drawing.Bitmap bip = new System.Drawing.Bitmap(imageFile);
float horzResolution;
float vertResolution;
string ext = Path.GetExtension(this.filePath).ToLower();
float origHorzRes = bip.HorizontalResolution;
float origVertRes = bip.VerticalResolution;
this.originalHeight = bip.Height * 72 / origVertRes;
this.originalWidth = bip.Width * 72 / origHorzRes;
horzResolution = bip.HorizontalResolution;
vertResolution = bip.VerticalResolution;
}
else
{
horzResolution= (float)GetValueAsIntended("Resolution");
vertResolution= horzResolution;
}
Unit origHeight = bip.Size.Height * 72 / vertResolution;
Unit origWidth = bip.Size.Width * 72 / horzResolution;
this.imageHeight = origHeight;
this.imageWidth = origWidth;
bool scaleWidthIsNull = this.image.IsNull("ScaleWidth");
bool scaleHeightIsNull = this.image.IsNull("ScaleHeight");
float sclHeight = scaleHeightIsNull ? 1 : (float)GetValueAsIntended("ScaleHeight");
this.scaleHeight= sclHeight;
float sclWidth = scaleWidthIsNull ? 1 : (float)GetValueAsIntended("ScaleWidth");
this.scaleWidth = sclWidth;
bool doLockAspectRatio = this.image.IsNull("LockAspectRatio") || this.image.LockAspectRatio;
if (doLockAspectRatio && (scaleHeightIsNull || scaleWidthIsNull))
{
if (!this.image.IsNull("Width") && this.image.IsNull("Height"))
{
imageWidth = this.image.Width;
imageHeight = origHeight * imageWidth / origWidth;
}
else if (!this.image.IsNull("Height") && this.image.IsNull("Width"))
{
imageHeight = this.image.Height;
imageWidth = origWidth * imageHeight / origHeight;
}
else if (!this.image.IsNull("Height") && !this.image.IsNull("Width"))
{
imageWidth = this.image.Width;
imageHeight = this.image.Height;
}
if (scaleWidthIsNull && !scaleHeightIsNull)
scaleWidth = scaleHeight;
else if (scaleHeightIsNull && ! scaleWidthIsNull)
scaleHeight = scaleWidth;
}
else
{
if (!this.image.IsNull("Width"))
imageWidth = this.image.Width;
if (!this.image.IsNull("Height"))
imageHeight = this.image.Height;
}
return;
}
catch(FileNotFoundException)
{
Trace.WriteLine(Messages.ImageNotFound(this.image.Name), "warning");
}
catch(Exception exc)
{
Trace.WriteLine(Messages.ImageNotReadable(this.image.Name, exc.Message), "warning");
}
//Setting defaults in case an error occured.
this.imageFile = null;
this.imageHeight = (Unit)GetValueOrDefault("Height", Unit.FromInch(1));
this.imageWidth = (Unit)GetValueOrDefault("Width", Unit.FromInch(1));
this.scaleHeight = (double)GetValueOrDefault("ScaleHeight", 1.0);
this.scaleWidth = (double)GetValueOrDefault("ScaleWidth", 1.0);
}*/
/// <summary>
/// Renders the image file as byte series.
/// </summary>
private void RenderByteSeries(string fileName)
{
FileStream imageFile = null;
try
{
imageFile = new FileStream(fileName, FileMode.Open);
imageFile.Seek(0, SeekOrigin.Begin);
int byteVal;
while ((byteVal = imageFile.ReadByte()) != -1)
{
string strVal = byteVal.ToString("x");
if (strVal.Length == 1)
this.rtfWriter.WriteText("0");
this.rtfWriter.WriteText(strVal);
}
}
catch
{
Trace.WriteLine("Chart image file not read", "warning");
}
finally
{
if (imageFile != null)
imageFile.Close();
}
}
protected override Unit GetShapeHeight()
{
return base.GetShapeHeight() + base.GetLineWidth();
}
protected override Unit GetShapeWidth()
{
return base.GetShapeWidth() + base.GetLineWidth(); ;
}
private Chart chart;
bool isInline;
}
}
| |
#pragma warning disable
using System.Collections.Generic;
using XPT.Games.Generic.Entities;
using XPT.Games.Generic.Maps;
using XPT.Games.Yserbius;
using XPT.Games.Yserbius.Entities;
namespace XPT.Games.Yserbius.Maps {
class YserMap07 : YsMap {
public override int MapIndex => 7;
protected override int RandomEncounterChance => 10;
protected override int RandomEncounterExtraCount => 0;
public YserMap07() {
MapEvent01 = FnSTRSTELE_01;
MapEvent02 = FnSTRSTELE_02;
MapEvent03 = FnLKPKDOOR_03;
MapEvent04 = FnLKPKDOOR_04;
MapEvent05 = FnRUNESIGN_05;
MapEvent06 = FnTOPALACA_06;
MapEvent07 = FnLOWMNSTR_07;
MapEvent08 = FnMEDMNSTR_08;
MapEvent09 = FnSTRMNSTR_09;
MapEvent0A = FnSTRSMESA_0A;
MapEvent0B = FnSTRSMESB_0B;
MapEvent0C = FnSTRSMESC_0C;
MapEvent0D = FnSTRSMESD_0D;
MapEvent0E = FnGATEMESS_0E;
MapEvent0F = FnTOPALACB_0F;
MapEvent10 = FnNPCCHATA_10;
MapEvent11 = FnNPCCHATB_11;
MapEvent12 = FnNPCCHATC_12;
MapEvent13 = FnNPCCHATD_13;
MapEvent14 = FnSTRSTELE_14;
MapEvent15 = FnSTRSTELE_15;
MapEvent16 = FnNPCCHATE_16;
}
// === Strings ================================================
private const string String03FC = "You succeeded at opening the locked door.";
private const string String0426 = "The door is locked.";
private const string String043A = "Your attempt to open the door springs a trap. Dozens of darts attack you.";
private const string String0484 = "The key unlocked the massive door, bypassing a well hidden trap.";
private const string String04C5 = "The Palace doors are locked. Only the Palace key will open these doors.";
private const string String050E = "Runes can be seen on the tapestry...";
private const string String0533 = "None shall pass save one who holds the Key to the Palace.";
private const string String056D = "The stairs through the west gateway lead up a level.";
private const string String05A2 = "Through the north gateway are stairs going up to the next level.";
private const string String05E3 = "The stairs to the east lead downstairs.";
private const string String060B = "The stairs past the north gateway go down a level.";
private const string String063E = "The gateway leads to THE PALACE OF KING CLEOWYN.";
private const string String066F = "You encounter a Dwarf Thief.";
private const string String068C = "The palace doors are locked. Somewhere on the first level is the object that will open these doors.";
private const string String06F0 = "The Dwarf Thief is too busy removing darts from his leather shield to answer you.";
private const string String0742 = "You encounter a Halfling Ranger.";
private const string String0763 = "I know there are three secret areas on this level, but they cannot be entered from this corridor.";
private const string String07C5 = "The Halfling Ranger waves you away in annoyance.";
private const string String07F6 = "You encounter a Dwarf Wizard.";
private const string String0814 = "Not all traps should be by-passed. I fell through one and, after some nosing around and polishing off some bothersome rogues and monsters, found a most useful key.";
private const string String08B8 = "The Dwarf Wizard disappears in a puff of smoke.";
private const string String08E8 = "You encounter an Orc Knight.";
private const string String0905 = "King Cleowyn's Palace is an evil place, filled with the spirits of the tormented dead. A cleric told me to look for an asymmetry in the Palace if I wished to learn the truth about the dead king.";
private const string String09C9 = "The Orc Knight pretends not to hear you.";
private const string String09F2 = "You encounter a Halfling Cleric.";
private const string String0A13 = "On the next level down you will find a dwarf by the name of Deldwinn. He guards the entrance to King Cleowyn's Apartments.";
private const string String0A8F = "Do not try to fight Deldwinn, for he is enchanted and cannot be killed by mortals.";
private const string String0AE2 = "The Halfling Cleric mumbles his prayers.";
// === Functions ================================================
private void FnSTRSTELE_01(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: TeleportParty(player, 0x01, 0x03, 0x97, 0x02, type);
L001E: return; // RETURN;
}
private void FnSTRSTELE_02(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: TeleportParty(player, 0x03, 0x01, 0x1F, 0x01, type);
L001E: return; // RETURN;
}
private void FnLKPKDOOR_03(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ax = HasUsedItem(player, type, ref doMsgs, 0xC1, 0xC4);
L0016: if (JumpNotEqual) goto L0029;
L0018: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0E), 0x0006);
L0027: if (JumpBelow) goto L0074;
L0029: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x01);
L0047: SetWallItem(player, 0x01, GetCurrentTile(player), GetFacing(player));
L0065: ShowMessage(player, doMsgs, String03FC); // You succeeded at opening the locked door.
L0072: goto L009E;
L0074: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00);
L0091: ShowMessage(player, doMsgs, String0426); // The door is locked.
L009E: return; // RETURN;
}
private void FnLKPKDOOR_04(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ax = HasUsedItem(player, type, ref doMsgs, 0xBF, 0xC4);
L0016: if (JumpNotEqual) goto L0029;
L0018: Compare(HasUsedSkill(player, type, ref doMsgs, 0x0E), 0x0001);
L0027: if (JumpBelow) goto L0046;
L0029: DamagePlayer(player, 0x0096);
L0036: ShowMessage(player, doMsgs, String043A); // Your attempt to open the door springs a trap. Dozens of darts attack you.
L0043: goto L00D0;
L0046: ax = HasUsedItem(player, type, ref doMsgs, YsIndexes.ItemKeyToCleowynsPalace, YsIndexes.ItemKeyToCleowynsPalace);
L0059: if (JumpEqual) goto L00A6;
L005B: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x01);
L0079: SetWallItem(player, 0x01, GetCurrentTile(player), GetFacing(player));
L0097: ShowMessage(player, doMsgs, String0484); // The key unlocked the massive door, bypassing a well hidden trap.
L00A4: goto L00D0;
L00A6: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00);
L00C3: ShowMessage(player, doMsgs, String04C5); // The Palace doors are locked. Only the Palace key will open these doors.
L00D0: return; // RETURN;
}
private void FnRUNESIGN_05(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String050E); // Runes can be seen on the tapestry...
L0010: ShowRunes(player, doMsgs, String0533); // None shall pass save one who holds the Key to the Palace.
L001D: return; // RETURN;
}
private void FnTOPALACA_06(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: TeleportParty(player, 0x02, 0x06, 0x03, 0x01, type);
L001E: return; // RETURN;
}
private void FnLOWMNSTR_07(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: Compare(PartyCount(player), 0x0001);
L000E: if (JumpNotEqual) goto L0025;
L0010: AddEncounter(player, 0x01, 0x19);
L0022: goto L00E6;
L0025: Compare(PartyCount(player), 0x0002);
L0030: if (JumpNotEqual) goto L0059;
L0032: AddEncounter(player, 0x01, 0x1A);
L0044: AddEncounter(player, 0x02, 0x1C);
L0056: goto L00E6;
L0059: Compare(PartyCount(player), 0x0003);
L0064: if (JumpNotEqual) goto L009E;
L0066: AddEncounter(player, 0x01, 0x1A);
L0078: AddEncounter(player, 0x02, 0x1A);
L008A: AddEncounter(player, 0x03, 0x1B);
L009C: goto L00E6;
L009E: AddEncounter(player, 0x01, 0x19);
L00B0: AddEncounter(player, 0x02, 0x1C);
L00C2: AddEncounter(player, 0x03, 0x1B);
L00D4: AddEncounter(player, 0x04, 0x1A);
L00E6: return; // RETURN;
}
private void FnMEDMNSTR_08(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: Compare(PartyCount(player), 0x0001);
L000E: if (JumpNotEqual) goto L0037;
L0010: AddEncounter(player, 0x01, 0x1E);
L0022: AddEncounter(player, 0x02, 0x20);
L0034: goto L0176;
L0037: Compare(PartyCount(player), 0x0002);
L0042: if (JumpNotEqual) goto L008F;
L0044: AddEncounter(player, 0x01, 0x1F);
L0056: AddEncounter(player, 0x02, 0x1F);
L0068: AddEncounter(player, 0x03, 0x1E);
L007A: AddEncounter(player, 0x04, 0x21);
L008C: goto L0176;
L008F: Compare(PartyCount(player), 0x0003);
L009A: if (JumpNotEqual) goto L010A;
L009C: AddEncounter(player, 0x01, 0x1E);
L00AE: AddEncounter(player, 0x02, 0x1F);
L00C0: AddEncounter(player, 0x03, 0x1E);
L00D2: AddEncounter(player, 0x04, 0x1F);
L00E4: AddEncounter(player, 0x05, 0x20);
L00F6: AddEncounter(player, 0x06, 0x20);
L0108: goto L0176;
L010A: AddEncounter(player, 0x01, 0x22);
L011C: AddEncounter(player, 0x02, 0x22);
L012E: AddEncounter(player, 0x03, 0x22);
L0140: AddEncounter(player, 0x04, 0x22);
L0152: AddEncounter(player, 0x05, 0x22);
L0164: AddEncounter(player, 0x06, 0x22);
L0176: return; // RETURN;
}
private void FnSTRMNSTR_09(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: Compare(PartyCount(player), 0x0001);
L000E: if (JumpNotEqual) goto L0025;
L0010: AddEncounter(player, 0x01, 0x23);
L0022: goto L012E;
L0025: Compare(PartyCount(player), 0x0002);
L0030: if (JumpNotEqual) goto L0059;
L0032: AddEncounter(player, 0x01, 0x24);
L0044: AddEncounter(player, 0x02, 0x24);
L0056: goto L012E;
L0059: Compare(PartyCount(player), 0x0003);
L0064: if (JumpNotEqual) goto L00C2;
L0066: AddEncounter(player, 0x01, 0x24);
L0078: AddEncounter(player, 0x02, 0x24);
L008A: AddEncounter(player, 0x03, 0x23);
L009C: AddEncounter(player, 0x04, 0x23);
L00AE: AddEncounter(player, 0x05, 0x26);
L00C0: goto L012E;
L00C2: AddEncounter(player, 0x01, 0x28);
L00D4: AddEncounter(player, 0x02, 0x25);
L00E6: AddEncounter(player, 0x03, 0x23);
L00F8: AddEncounter(player, 0x04, 0x27);
L010A: AddEncounter(player, 0x05, 0x24);
L011C: AddEncounter(player, 0x06, 0x28);
L012E: return; // RETURN;
}
private void FnSTRSMESA_0A(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String056D); // The stairs through the west gateway lead up a level.
L0010: return; // RETURN;
}
private void FnSTRSMESB_0B(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String05A2); // Through the north gateway are stairs going up to the next level.
L0010: return; // RETURN;
}
private void FnSTRSMESC_0C(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String05E3); // The stairs to the east lead downstairs.
L0010: return; // RETURN;
}
private void FnSTRSMESD_0D(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String060B); // The stairs past the north gateway go down a level.
L0010: return; // RETURN;
}
private void FnGATEMESS_0E(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String063E); // The gateway leads to THE PALACE OF KING CLEOWYN.
L0010: return; // RETURN;
}
private void FnTOPALACB_0F(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: TeleportParty(player, 0x02, 0x06, 0x04, 0x01, type);
L001E: return; // RETURN;
}
private void FnNPCCHATA_10(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String066F); // You encounter a Dwarf Thief.
L0010: ShowPortrait(player, 0x0023);
L001D: Compare(GetRandom(0x000F), 0x000B);
L002D: if (JumpAbove) goto L003E;
L002F: ShowMessage(player, doMsgs, String068C); // The palace doors are locked. Somewhere on the first level is the object that will open these doors.
L003C: goto L004B;
L003E: ShowMessage(player, doMsgs, String06F0); // The Dwarf Thief is too busy removing darts from his leather shield to answer you.
L004B: return; // RETURN;
}
private void FnNPCCHATB_11(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String0742); // You encounter a Halfling Ranger.
L0010: ShowPortrait(player, 0x0021);
L001D: Compare(GetRandom(0x000F), 0x0008);
L002D: if (JumpAbove) goto L003E;
L002F: ShowMessage(player, doMsgs, String0763); // I know there are three secret areas on this level, but they cannot be entered from this corridor.
L003C: goto L004B;
L003E: ShowMessage(player, doMsgs, String07C5); // The Halfling Ranger waves you away in annoyance.
L004B: return; // RETURN;
}
private void FnNPCCHATC_12(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String07F6); // You encounter a Dwarf Wizard.
L0010: ShowPortrait(player, 0x002C);
L001D: Compare(GetRandom(0x000F), 0x000C);
L002D: if (JumpAbove) goto L003E;
L002F: ShowMessage(player, doMsgs, String0814); // Not all traps should be by-passed. I fell through one and, after some nosing around and polishing off some bothersome rogues and monsters, found a most useful key.
L003C: goto L004B;
L003E: ShowMessage(player, doMsgs, String08B8); // The Dwarf Wizard disappears in a puff of smoke.
L004B: return; // RETURN;
}
private void FnNPCCHATD_13(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String08E8); // You encounter an Orc Knight.
L0010: ShowPortrait(player, 0x001A);
L001D: Compare(GetRandom(0x000F), 0x0007);
L002D: if (JumpAbove) goto L003E;
L002F: ShowMessage(player, doMsgs, String0905); // King Cleowyn's Palace is an evil place, filled with the spirits of the tormented dead. A cleric told me to look for an asymmetry in the Palace if I wished to learn the truth about the dead king.
L003C: goto L004B;
L003E: ShowMessage(player, doMsgs, String09C9); // The Orc Knight pretends not to hear you.
L004B: return; // RETURN;
}
private void FnSTRSTELE_14(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: TeleportParty(player, 0x01, 0x03, 0x97, 0x02, type);
L001E: return; // RETURN;
}
private void FnSTRSTELE_15(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: TeleportParty(player, 0x03, 0x01, 0x1F, 0x01, type);
L001E: return; // RETURN;
}
private void FnNPCCHATE_16(YsPlayerServer player, MapEventType type, bool doMsgs) {
int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0;
L0000: // BEGIN;
L0003: ShowMessage(player, doMsgs, String09F2); // You encounter a Halfling Cleric.
L0010: ShowPortrait(player, 0x0029);
L001D: Compare(GetRandom(0x000F), 0x000D);
L002D: if (JumpAbove) goto L004B;
L002F: ShowMessage(player, doMsgs, String0A13); // On the next level down you will find a dwarf by the name of Deldwinn. He guards the entrance to King Cleowyn's Apartments.
L003C: ShowMessage(player, doMsgs, String0A8F); // Do not try to fight Deldwinn, for he is enchanted and cannot be killed by mortals.
L0049: goto L0058;
L004B: ShowMessage(player, doMsgs, String0AE2); // The Halfling Cleric mumbles his prayers.
L0058: return; // RETURN;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class UnsafeKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCompilationUnit()
{
await VerifyKeywordAsync(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern()
{
await VerifyKeywordAsync(
@"extern alias Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(
@"using Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNamespace()
{
await VerifyKeywordAsync(
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterTypeDeclaration()
{
await VerifyKeywordAsync(
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration()
{
await VerifyKeywordAsync(
@"delegate void Foo();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Foo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
using Foo;");
}
[WpfFact(Skip = "528041"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
using Foo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAssemblyAttribute()
{
await VerifyKeywordAsync(
@"[assembly: foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRootAttribute()
{
await VerifyKeywordAsync(
@"[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[foo]
$$");
}
// This will be fixed once we have accessibility for members
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
{
await VerifyAbsenceAsync(@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAbstract()
{
await VerifyKeywordAsync(
@"abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInternal()
{
await VerifyKeywordAsync(
@"internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterUnsafe()
{
await VerifyAbsenceAsync(@"unsafe $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStaticUnsafe()
{
await VerifyAbsenceAsync(@"static unsafe $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterUnsafeStatic()
{
await VerifyAbsenceAsync(@"unsafe static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPrivate()
{
await VerifyKeywordAsync(
@"private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProtected()
{
await VerifyKeywordAsync(
@"protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSealed()
{
await VerifyKeywordAsync(
@"sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStatic()
{
await VerifyKeywordAsync(
@"static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStaticInUsingDirective()
{
await VerifyAbsenceAsync(
@"using static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass()
{
await VerifyAbsenceAsync(@"class $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegate()
{
await VerifyAbsenceAsync(@"delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedVirtual()
{
await VerifyKeywordAsync(
@"class C {
virtual $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedOverride()
{
await VerifyKeywordAsync(
@"class C {
override $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$
return true;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"return true;
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"if (true) {
}
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideSwitchBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (E) {
case 0:
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterUnsafe_InMethod()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"unsafe $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInterfaceModifiers()
{
await VerifyKeywordAsync(
@"public $$ interface IBinaryDocumentMemoryBlock {");
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using NLog.Common;
using NLog.Config;
using Xunit.Extensions;
namespace NLog.UnitTests.Config
{
using System.IO;
using MyExtensionNamespace;
using NLog.Filters;
using NLog.Layouts;
using NLog.Targets;
using Xunit;
public class ExtensionTests : NLogTestBase
{
private string extensionAssemblyName1 = "SampleExtensions";
private string extensionAssemblyFullPath1 = Path.GetFullPath("SampleExtensions.dll");
private string GetExtensionAssemblyFullPath()
{
#if NETSTANDARD
Assert.NotNull(typeof(FooLayout));
return typeof(FooLayout).GetTypeInfo().Assembly.Location;
#else
return extensionAssemblyFullPath1;
#endif
}
[Fact]
public void ExtensionTest1()
{
ConfigurationItemFactory.Default = null; //build new factory next time
Assert.NotNull(typeof(FooLayout));
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<extensions>
<add assemblyFile='" + GetExtensionAssemblyFullPath() + @"' />
</extensions>
<targets>
<target name='t' type='MyTarget' />
<target name='d1' type='Debug' layout='${foo}' />
<target name='d2' type='Debug'>
<layout type='FooLayout' x='1'>
</layout>
</target>
</targets>
<rules>
<logger name='*' writeTo='t'>
<filters>
<whenFoo x='44' action='Ignore' />
</filters>
</logger>
</rules>
</nlog>");
Target myTarget = configuration.FindTargetByName("t");
Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName);
var d1Target = (DebugTarget)configuration.FindTargetByName("d1");
var layout = d1Target.Layout as SimpleLayout;
Assert.NotNull(layout);
Assert.Single(layout.Renderers);
Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName);
var d2Target = (DebugTarget)configuration.FindTargetByName("d2");
Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName);
Assert.Equal(1, configuration.LoggingRules[0].Filters.Count);
Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName);
}
[Fact]
public void ExtensionTest2()
{
ConfigurationItemFactory.Default = null; //build new factory next time
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<extensions>
<add assembly='" + extensionAssemblyName1 + @"' />
</extensions>
<targets>
<target name='t' type='MyTarget' />
<target name='d1' type='Debug' layout='${foo}' />
<target name='d2' type='Debug'>
<layout type='FooLayout' x='1'>
</layout>
</target>
</targets>
<rules>
<logger name='*' writeTo='t'>
<filters>
<whenFoo x='44' action='Ignore' />
<when condition='myrandom(10)==3' action='Log' />
</filters>
</logger>
</rules>
</nlog>");
Target myTarget = configuration.FindTargetByName("t");
Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName);
var d1Target = (DebugTarget)configuration.FindTargetByName("d1");
var layout = d1Target.Layout as SimpleLayout;
Assert.NotNull(layout);
Assert.Single(layout.Renderers);
Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName);
var d2Target = (DebugTarget)configuration.FindTargetByName("d2");
Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName);
Assert.Equal(2, configuration.LoggingRules[0].Filters.Count);
Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName);
var cbf = configuration.LoggingRules[0].Filters[1] as ConditionBasedFilter;
Assert.NotNull(cbf);
Assert.Equal("(myrandom(10) == 3)", cbf.Condition.ToString());
}
[Fact]
public void ExtensionWithPrefixTest()
{
ConfigurationItemFactory.Default = null; //build new factory next time
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<extensions>
<add prefix='myprefix' assemblyFile='" + GetExtensionAssemblyFullPath() + @"' />
</extensions>
<targets>
<target name='t' type='myprefix.MyTarget' />
<target name='d1' type='Debug' layout='${myprefix.foo}' />
<target name='d2' type='Debug'>
<layout type='myprefix.FooLayout' x='1'>
</layout>
</target>
</targets>
<rules>
<logger name='*' writeTo='t'>
<filters>
<myprefix.whenFoo x='44' action='Ignore' />
</filters>
</logger>
</rules>
</nlog>");
Target myTarget = configuration.FindTargetByName("t");
Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName);
var d1Target = (DebugTarget)configuration.FindTargetByName("d1");
var layout = d1Target.Layout as SimpleLayout;
Assert.NotNull(layout);
Assert.Single(layout.Renderers);
Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName);
var d2Target = (DebugTarget)configuration.FindTargetByName("d2");
Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName);
Assert.Equal(1, configuration.LoggingRules[0].Filters.Count);
Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName);
}
[Fact]
public void ExtensionTest4()
{
Assert.NotNull(typeof(FooLayout));
ConfigurationItemFactory.Default = null; //build new factory next time
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<extensions>
<add type='" + typeof(MyTarget).AssemblyQualifiedName + @"' />
<add type='" + typeof(FooLayout).AssemblyQualifiedName + @"' />
<add type='" + typeof(FooLayoutRenderer).AssemblyQualifiedName + @"' />
<add type='" + typeof(WhenFooFilter).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target name='t' type='MyTarget' />
<target name='d1' type='Debug' layout='${foo}' />
<target name='d2' type='Debug'>
<layout type='FooLayout' x='1'>
</layout>
</target>
</targets>
<rules>
<logger name='*' writeTo='t'>
<filters>
<whenFoo x='44' action='Ignore' />
</filters>
</logger>
</rules>
</nlog>");
Target myTarget = configuration.FindTargetByName("t");
Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName);
var d1Target = (DebugTarget)configuration.FindTargetByName("d1");
var layout = d1Target.Layout as SimpleLayout;
Assert.NotNull(layout);
Assert.Single(layout.Renderers);
Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName);
var d2Target = (DebugTarget)configuration.FindTargetByName("d2");
Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName);
Assert.Equal(1, configuration.LoggingRules[0].Filters.Count);
Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName);
}
[Fact]
public void ExtensionTest_extensions_not_top_and_used()
{
Assert.NotNull(typeof(FooLayout));
ConfigurationItemFactory.Default = null; //build new factory next time
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<targets>
<target name='t' type='MyTarget' />
<target name='d1' type='Debug' layout='${foo}' />
<target name='d2' type='Debug'>
<layout type='FooLayout' x='1'>
</layout>
</target>
</targets>
<rules>
<logger name='*' writeTo='t'>
<filters>
<whenFoo x='44' action='Ignore' />
</filters>
</logger>
</rules>
<extensions>
<add assemblyFile='" + GetExtensionAssemblyFullPath() + @"' />
</extensions>
</nlog>");
Target myTarget = configuration.FindTargetByName("t");
Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName);
var d1Target = (DebugTarget)configuration.FindTargetByName("d1");
var layout = d1Target.Layout as SimpleLayout;
Assert.NotNull(layout);
Assert.Single(layout.Renderers);
Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName);
var d2Target = (DebugTarget)configuration.FindTargetByName("d2");
Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName);
Assert.Equal(1, configuration.LoggingRules[0].Filters.Count);
Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName);
}
[Fact]
public void ExtensionShouldThrowNLogConfiguratonExceptionWhenRegisteringInvalidType()
{
var configXml = @"
<nlog throwConfigExceptions='true'>
<extensions>
<add type='some_type_that_doesnt_exist'/>
</extensions>
</nlog>";
Assert.Throws<NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(configXml));
}
[Fact]
public void ExtensionShouldThrowNLogConfiguratonExceptionWhenRegisteringInvalidAssembly()
{
var configXml = @"
<nlog throwConfigExceptions='true'>
<extensions>
<add assembly='some_assembly_that_doesnt_exist'/>
</extensions>
</nlog>";
Assert.Throws<NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(configXml));
}
[Fact]
public void ExtensionShouldThrowNLogConfiguratonExceptionWhenRegisteringInvalidAssemblyFile()
{
var configXml = @"
<nlog throwConfigExceptions='true'>
<extensions>
<add assemblyfile='some_file_that_doesnt_exist'/>
</extensions>
</nlog>";
Assert.Throws<NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(configXml));
}
[Fact]
public void ExtensionShouldNotThrowWhenRegisteringInvalidTypeIfThrowConfigExceptionsFalse()
{
var configXml = @"
<nlog throwConfigExceptions='false'>
<extensions>
<add type='some_type_that_doesnt_exist'/>
<add assembly='NLog'/>
</extensions>
</nlog>";
XmlLoggingConfiguration.CreateFromXmlString(configXml);
}
[Fact]
public void ExtensionShouldNotThrowWhenRegisteringInvalidAssemblyIfThrowConfigExceptionsFalse()
{
var configXml = @"
<nlog throwConfigExceptions='false'>
<extensions>
<add assembly='some_assembly_that_doesnt_exist'/>
</extensions>
</nlog>";
XmlLoggingConfiguration.CreateFromXmlString(configXml);
}
[Fact]
public void ExtensionShouldNotThrowWhenRegisteringInvalidAssemblyFileIfThrowConfigExceptionsFalse()
{
var configXml = @"
<nlog throwConfigExceptions='false'>
<extensions>
<add assemblyfile='some_file_that_doesnt_exist'/>
</extensions>
</nlog>";
XmlLoggingConfiguration.CreateFromXmlString(configXml);
}
[Fact]
public void CustomXmlNamespaceTest()
{
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true' xmlns:foo='http://bar'>
<targets>
<target name='d' type='foo:Debug' />
</targets>
</nlog>");
var d1Target = (DebugTarget)configuration.FindTargetByName("d");
Assert.NotNull(d1Target);
}
[Fact]
public void Extension_should_be_auto_loaded_when_following_NLog_dll_format()
{
try
{
var fileLocations = ConfigurationItemFactory.GetAutoLoadingFileLocations().ToArray();
Assert.NotEmpty(fileLocations);
Assert.NotNull(fileLocations[0].Key);
Assert.NotNull(fileLocations[0].Value); // Primary search location is NLog-assembly
Assert.Equal(fileLocations.Length, fileLocations.Select(f => f.Key).Distinct().Count());
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<targets>
<target name='t' type='AutoLoadTarget' />
</targets>
<rules>
<logger name='*' writeTo='t'>
</logger>
</rules>
</nlog>");
var autoLoadedTarget = configuration.FindTargetByName("t");
Assert.Equal("NLogAutloadExtension.AutoLoadTarget", autoLoadedTarget.GetType().FullName);
}
finally
{
ConfigurationItemFactory.Default.Clear();
ConfigurationItemFactory.Default = null; //build new factory next time
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Extension_loading_could_be_canceled(bool cancel)
{
EventHandler<AssemblyLoadingEventArgs> onAssemblyLoading = (sender, e) =>
{
if (e.Assembly.FullName.Contains("NLogAutoLoadExtension"))
{
e.Cancel = cancel;
}
};
try
{
ConfigurationItemFactory.Default = null; //build new factory next time
ConfigurationItemFactory.AssemblyLoading += onAssemblyLoading;
using(new NoThrowNLogExceptions())
{
LogManager.ThrowExceptions = true;
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='false'>
<targets>
<target name='t' type='AutoLoadTarget' />
</targets>
<rules>
<logger name='*' writeTo='t'>
</logger>
</rules>
</nlog>");
var autoLoadedTarget = configuration.FindTargetByName("t");
if (cancel)
{
Assert.Null(autoLoadedTarget);
}
else
{
Assert.Equal("NLogAutloadExtension.AutoLoadTarget", autoLoadedTarget.GetType().FullName);
}
}
}
finally
{
//cleanup
ConfigurationItemFactory.AssemblyLoading -= onAssemblyLoading;
ConfigurationItemFactory.Default.Clear();
ConfigurationItemFactory.Default = null; //build new factory next time
}
}
[Fact]
public void Extensions_NLogPackageLoader_should_beCalled()
{
try
{
var writer = new StringWriter();
InternalLogger.LogWriter = writer;
InternalLogger.LogLevel = LogLevel.Debug;
//reload ConfigurationItemFactory
ConfigurationItemFactory.Default = null;
var fact = ConfigurationItemFactory.Default;
//also throw exceptions
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<extensions>
<add assembly='PackageLoaderTestAssembly' />
</extensions>
</nlog>");
var logs = writer.ToString();
Assert.Contains("Preload successfully invoked for 'LoaderTestInternal.NLogPackageLoader'", logs);
Assert.Contains("Preload successfully invoked for 'LoaderTestPublic.NLogPackageLoader'", logs);
Assert.Contains("Preload successfully invoked for 'LoaderTestPrivateNestedStatic.SomeType+NLogPackageLoader'", logs);
Assert.Contains("Preload successfully invoked for 'LoaderTestPrivateNested.SomeType+NLogPackageLoader'", logs);
//4 times successful
Assert.Equal(4, Regex.Matches(logs, Regex.Escape("Preload successfully invoked for '")).Count);
}
finally
{
InternalLogger.Reset();
}
}
[Fact]
public void ImplicitConversionOperatorTest()
{
var config = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<extensions>
<add assemblyFile='" + GetExtensionAssemblyFullPath() + @"' />
</extensions>
<targets>
<target name='myTarget' type='MyTarget' layout='123' />
</targets>
<rules>
<logger name='*' level='Debug' writeTo='myTarget' />
</rules>
</nlog>");
var target = config.FindTargetByName<MyTarget>("myTarget");
Assert.NotNull(target);
Assert.Equal(123, target.Layout.X);
}
[Fact]
public void LoadExtensionFromAppDomain()
{
try
{
// ...\NLog\tests\NLog.UnitTests\bin\Debug\netcoreapp2.0\nlog.dll
var nlogDirectory = new DirectoryInfo(ConfigurationItemFactory.GetAutoLoadingFileLocations().First().Key);
var configurationDirectory = nlogDirectory.Parent;
var testsDirectory = configurationDirectory.Parent.Parent.Parent;
var manuallyLoadedAssemblyPath = Path.Combine(testsDirectory.FullName, "ManuallyLoadedExtension", "bin", configurationDirectory.Name,
#if NETSTANDARD
"netstandard2.0",
#else
nlogDirectory.Name,
#endif
"ManuallyLoadedExtension.dll");
Assembly.LoadFrom(manuallyLoadedAssemblyPath);
InternalLogger.LogLevel = LogLevel.Trace;
var writer = new StringWriter();
InternalLogger.LogWriter = writer;
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<extensions>
<add assembly='ManuallyLoadedExtension' />
</extensions>
<targets>
<target name='t' type='ManuallyLoadedTarget' />
</targets>
</nlog>");
// We get Exception for normal Assembly-Load only in net452.
#if !NETSTANDARD && !MONO
var logs = writer.ToString();
Assert.Contains("Try find 'ManuallyLoadedExtension' in current domain", logs);
#endif
// Was AssemblyLoad successful?
var autoLoadedTarget = configuration.FindTargetByName("t");
Assert.Equal("ManuallyLoadedExtension.ManuallyLoadedTarget", autoLoadedTarget.GetType().FullName);
}
finally
{
InternalLogger.Reset();
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//==========================================================================
// File: CombinedHttpChannel.cs
//
// Summary: Merges the client and server HTTP channels
//
// Classes: public HttpChannel
//
//==========================================================================
using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Globalization;
using System.Security.Permissions;
namespace System.Runtime.Remoting.Channels.Http
{
public class HttpChannel : BaseChannelWithProperties,
IChannelReceiver, IChannelSender, IChannelReceiverHook, ISecurableChannel
{
// Cached key set value
private static ICollection s_keySet = null;
private HttpClientChannel _clientChannel; // client channel
private HttpServerChannel _serverChannel; // server channel
private int _channelPriority = 1; // channel priority
private String _channelName = "http"; // channel name
private bool _secure = false;
public HttpChannel()
{
_clientChannel = new HttpClientChannel();
_serverChannel = new HttpServerChannel();
} // HttpChannel
public HttpChannel(int port)
{
_clientChannel = new HttpClientChannel();
_serverChannel = new HttpServerChannel(port);
} // HttpChannel
public HttpChannel(IDictionary properties,
IClientChannelSinkProvider clientSinkProvider,
IServerChannelSinkProvider serverSinkProvider)
{
Hashtable clientData = new Hashtable();
Hashtable serverData = new Hashtable();
// divide properties up for respective channels
if (properties != null)
{
foreach (DictionaryEntry entry in properties)
{
switch ((String)entry.Key)
{
// general channel properties
case "name": _channelName = (String)entry.Value; break;
case "priority": _channelPriority = Convert.ToInt32((String)entry.Value, CultureInfo.InvariantCulture); break;
case "secure": _secure = Convert.ToBoolean(entry.Value, CultureInfo.InvariantCulture);
clientData["secure"] = entry.Value;
serverData["secure"] = entry.Value;
break;
default:
clientData[entry.Key] = entry.Value;
serverData[entry.Key] = entry.Value;
break;
}
}
}
_clientChannel = new HttpClientChannel(clientData, clientSinkProvider);
_serverChannel = new HttpServerChannel(serverData, serverSinkProvider);
} // HttpChannel
//
// ISecurableChannel implementation
//
public bool IsSecured
{
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
get {
if (_clientChannel != null)
return _clientChannel.IsSecured;
if (_serverChannel != null)
return _serverChannel.IsSecured;
return false;
}
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
set {
if (((IList)ChannelServices.RegisteredChannels).Contains(this))
throw new InvalidOperationException(CoreChannel.GetResourceString("Remoting_InvalidOperation_IsSecuredCannotBeChangedOnRegisteredChannels"));
if (_clientChannel != null)
_clientChannel.IsSecured = value;
if (_serverChannel != null)
_serverChannel.IsSecured = value;
}
}
//
// IChannel implementation
//
public int ChannelPriority
{
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
get { return _channelPriority; }
} // ChannelPriority
public String ChannelName
{
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
get { return _channelName; }
} // ChannelName
// returns channelURI and places object uri into out parameter
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
public String Parse(String url, out String objectURI)
{
return HttpChannelHelper.ParseURL(url, out objectURI);
} // Parse
//
// end of IChannel implementation
//
//
// IChannelSender implementation
//
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
public IMessageSink CreateMessageSink(String url, Object remoteChannelData,
out String objectURI)
{
return _clientChannel.CreateMessageSink(url, remoteChannelData, out objectURI);
} // CreateMessageSink
//
// end of IChannelSender implementation
//
//
// IChannelReceiver implementation
//
public Object ChannelData
{
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
get { return _serverChannel.ChannelData; }
} // ChannelData
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
public String[] GetUrlsForUri(String objectURI)
{
return _serverChannel.GetUrlsForUri(objectURI);
} // GetUrlsForUri
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
public void StartListening(Object data)
{
_serverChannel.StartListening(data);
} // StartListening
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
public void StopListening(Object data)
{
_serverChannel.StopListening(data);
} // StopListening
//
// IChannelReceiver implementation
//
//
// IChannelReceiverHook implementation
//
public String ChannelScheme {
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
get { return "http"; }
}
public bool WantsToListen
{
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
get { return _serverChannel.WantsToListen; }
set { _serverChannel.WantsToListen = value; }
} // WantsToListen
public IServerChannelSink ChannelSinkChain
{
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
get { return _serverChannel.ChannelSinkChain; }
} // ChannelSinkChain
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
public void AddHookChannelUri(String channelUri)
{
_serverChannel.AddHookChannelUri(channelUri);
} // AddHookChannelUri
//
// IChannelReceiverHook implementation
//
//
// Support for properties (through BaseChannelWithProperties)
//
public override IDictionary Properties
{
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)]
get
{
ArrayList dictionaries = new ArrayList(2);
dictionaries.Add(_clientChannel.Properties);
dictionaries.Add(_serverChannel.Properties);
// return a dictionary that spans all dictionaries provided
return new AggregateDictionary(dictionaries);
}
} // Properties
public override Object this[Object key]
{
get
{
if (_clientChannel.Contains(key))
return _clientChannel[key];
else
if (_serverChannel.Contains(key))
return _serverChannel[key];
return null;
}
set
{
if (_clientChannel.Contains(key))
_clientChannel[key] = value;
else
if (_serverChannel.Contains(key))
_serverChannel[key] = value;
}
} // this[]
public override ICollection Keys
{
get
{
if (s_keySet == null)
{
// Don't need to synchronize. Doesn't matter if the list gets
// generated twice.
ICollection clientKeys = _clientChannel.Keys;
ICollection serverKeys = _serverChannel.Keys;
int count = clientKeys.Count + serverKeys.Count;
ArrayList keys = new ArrayList(count);
foreach (Object key in clientKeys)
{
keys.Add(key);
}
foreach (Object key in serverKeys)
{
keys.Add(key);
}
s_keySet = keys;
}
return s_keySet;
}
} // KeySet
//
// end of Support for properties
//
} // class HttpChannel
// an enumerator based off of a key set
// This is a duplicate of the class in mscorlib.
internal class DictionaryEnumeratorByKeys : IDictionaryEnumerator
{
IDictionary _properties;
IEnumerator _keyEnum;
public DictionaryEnumeratorByKeys(IDictionary properties)
{
_properties = properties;
_keyEnum = properties.Keys.GetEnumerator();
} // PropertyEnumeratorByKeys
public bool MoveNext() { return _keyEnum.MoveNext(); }
public void Reset() { _keyEnum.Reset(); }
public Object Current { get { return Entry; } }
public DictionaryEntry Entry { get { return new DictionaryEntry(Key, Value); } }
public Object Key { get { return _keyEnum.Current; } }
public Object Value { get { return _properties[Key]; } }
} // DictionaryEnumeratorByKeys
// combines multiple dictionaries into one
// (used for channel sink properties
// This is a duplicate of the class in mscorlib.
internal class AggregateDictionary : IDictionary
{
private ICollection _dictionaries;
public AggregateDictionary(ICollection dictionaries)
{
_dictionaries = dictionaries;
} // AggregateDictionary
//
// IDictionary implementation
//
public virtual Object this[Object key]
{
get
{
foreach (IDictionary dict in _dictionaries)
{
if (dict.Contains(key))
return dict[key];
}
return null;
}
set
{
foreach (IDictionary dict in _dictionaries)
{
if (dict.Contains(key))
dict[key] = value;
}
}
} // Object this[Object key]
public virtual ICollection Keys
{
get
{
ArrayList keys = new ArrayList();
// add keys from every dictionary
foreach (IDictionary dict in _dictionaries)
{
ICollection dictKeys = dict.Keys;
if (dictKeys != null)
{
foreach (Object key in dictKeys)
{
keys.Add(key);
}
}
}
return keys;
}
} // Keys
public virtual ICollection Values
{
get
{
ArrayList values = new ArrayList();
// add values from every dictionary
foreach (IDictionary dict in _dictionaries)
{
ICollection dictValues = dict.Values;
if (dictValues != null)
{
foreach (Object value in dictValues)
{
values.Add(value);
}
}
}
return values;
}
} // Values
public virtual bool Contains(Object key)
{
foreach (IDictionary dict in _dictionaries)
{
if (dict.Contains(key))
return true;
}
return false;
} // Contains
public virtual bool IsReadOnly { get { return false; } }
public virtual bool IsFixedSize { get { return true; } }
// The following three methods should never be implemented because
// they don't apply to the way IDictionary is being used in this case
// (plus, IsFixedSize returns true.)
public virtual void Add(Object key, Object value) { throw new NotSupportedException(); }
public virtual void Clear() { throw new NotSupportedException(); }
public virtual void Remove(Object key) { throw new NotSupportedException(); }
public virtual IDictionaryEnumerator GetEnumerator()
{
return new DictionaryEnumeratorByKeys(this);
} // GetEnumerator
//
// end of IDictionary implementation
//
//
// ICollection implementation
//
//ICollection
public virtual void CopyTo(Array array, int index) { throw new NotSupportedException(); }
public virtual int Count
{
get
{
int count = 0;
foreach (IDictionary dict in _dictionaries)
{
count += dict.Count;
}
return count;
}
} // Count
public virtual Object SyncRoot { get { return this; } }
public virtual bool IsSynchronized { get { return false; } }
//
// end of ICollection implementation
//
//IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return new DictionaryEnumeratorByKeys(this);
}
} // class AggregateDictionary
} // namespace System.Runtime.Remoting.Channels.Http
| |
#region License
/* Copyright (c) 2003-2015 Llewellyn Pritchard
* All rights reserved.
* This source code is subject to terms and conditions of the BSD License.
* See license.txt. */
#endregion
#region Includes
using System;
using System.Collections;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using IronScheme.Editor.ComponentModel;
#endregion
[assembly: PluginProvider(typeof(DefaultPluginProvider))]
namespace IronScheme.Editor.ComponentModel
{
/// <summary>
/// Provides services to load plugin assemblies
/// </summary>
[Name("Plugin manager", "Provides services for loading assembly plugins")]
public interface IPluginManagerService : IService
{
/// <summary>
/// Load an assembly
/// </summary>
/// <param name="assembly">the assembly to load</param>
void LoadAssembly(Assembly assembly);
void LoadFile(string filename);
}
/// <summary>
/// Define the type of the PluginProvider class
/// </summary>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)]
public class PluginProviderAttribute : Attribute
{
Type type;
/// <summary>
/// Creates an instance of PluginProviderAttribute
/// </summary>
/// <param name="asspluginprvimpl">the plugin provider type</param>
public PluginProviderAttribute(Type asspluginprvimpl)
{
type = asspluginprvimpl;
}
/// <summary>
/// The type
/// </summary>
public Type Type
{
get {return type;}
}
}
/// <summary>
/// Base class for PluginProviders
/// </summary>
public abstract class AssemblyPluginProvider
{
/// <summary>
/// Loads all
/// </summary>
/// <param name="svc">the calling service</param>
public abstract void LoadAll(IPluginManagerService svc);
}
class DefaultPluginProvider : AssemblyPluginProvider
{
public override void LoadAll(IPluginManagerService svc)
{
Configuration.IdeSupport.about.progressBar1.Value = 10;
new LanguageService();
Configuration.IdeSupport.about.progressBar1.Value += 20;
new ImageListProvider();
if (SettingsService.idemode)
{
new ToolBarService();
new MenuService();
new StatusBarService();
}
Configuration.IdeSupport.about.progressBar1.Value += 10;
new DiscoveryService();
new CodeModelManager();
new ErrorService();
// figure some way out to order these for toolbar/menu
new FileManager();
new EditService();
new ProjectManager();
new BuildService();
new DebugService();
new ToolsService();
new HelpService();
new UpdaterService();
Configuration.IdeSupport.about.progressBar1.Value += 10;
new ScriptingService();
new StandardConsole();
new SettingsService();
new PropertyService();
Configuration.IdeSupport.about.progressBar1.Value = 55;
}
}
sealed class PluginManager : ServiceBase, IPluginManagerService
{
static readonly Hashtable loaded = new Hashtable();
readonly FileSystemWatcher fsw ;
public PluginManager()
{
/*
if (SettingsService.idemode)
{
if (!Directory.Exists(Application.StartupPath + "/Plugins"))
{
Directory.CreateDirectory(Application.StartupPath + "/Plugins");
}
fsw = new FileSystemWatcher(Application.StartupPath + "/Plugins", "Plugin.*.dll");
fsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
fsw.EnableRaisingEvents = true;
fsw.Changed += new FileSystemEventHandler(fsw_Changed);
fsw.Created +=new FileSystemEventHandler(fsw_Created);
fsw.Deleted +=new FileSystemEventHandler(fsw_Deleted);
fsw.Renamed +=new RenamedEventHandler(fsw_Renamed);
}*/
}
public void LoadFile(string filename)
{
try
{
Assembly ass = Assembly.LoadFile(Path.Combine(Application.StartupPath, filename));
LoadAssembly(ass);
}
catch (FileNotFoundException)
{
Trace.WriteLine("{0} could not be found", Path.Combine(Application.StartupPath, filename));
}
}
public void LoadAssembly(Assembly ass)
{
if (!loaded.ContainsKey(ass))
{
Trace.WriteLine("Loading assembly: {0}", ass.FullName);
try
{
foreach (PluginProviderAttribute ppa in
ass.GetCustomAttributes(typeof(PluginProviderAttribute), false))
{
AssemblyPluginProvider app = Activator.CreateInstance(ppa.Type) as AssemblyPluginProvider;
if (app == null)
{
throw new Exception(string.Format("default constructor expected on {0}", ppa.Type));
}
else
{
app.LoadAll(this);
loaded.Add(ass,null);
Trace.WriteLine("Loaded assembly: {0}", ass.FullName);
}
break;
}
}
catch (TypeLoadException)
{
Trace.WriteLine("Failed to load assembly: {0}", ass.FullName);
}
catch (FileLoadException)
{
Trace.WriteLine("Failed to load assembly: {0}", ass.FullName);
}
if (ass == typeof(PluginManager).Assembly && SettingsService.idemode)
{
if (Directory.Exists("Plugins"))
{
foreach (string file in Directory.GetFiles("Plugins", "Plugin.*.dll"))
{
byte[] data = null;
byte[] dbgdata = null;
using (Stream s = File.OpenRead(file))
{
data = new byte[s.Length];
s.Read(data, 0, data.Length);
}
if (File.Exists(Path.ChangeExtension(file, "pdb")))
{
using (Stream s = File.OpenRead(Path.ChangeExtension(file, "pdb")))
{
dbgdata = new byte[s.Length];
s.Read(dbgdata, 0, dbgdata.Length);
}
}
Assembly pass = Assembly.Load(data, dbgdata);
LoadAssembly(pass);
}
}
}
}
}
private void fsw_Changed(object sender, FileSystemEventArgs e)
{
;
//renamed...
}
private void fsw_Created(object sender, FileSystemEventArgs e)
{
byte[] data = null;
byte[] dbgdata = null;
using (Stream s = File.OpenRead(e.FullPath))
{
data = new byte[s.Length];
s.Read(data, 0, data.Length);
}
if (File.Exists(Path.ChangeExtension(e.FullPath, "pdb")))
{
using (Stream s = File.OpenRead(Path.ChangeExtension(e.FullPath, "pdb")))
{
dbgdata = new byte[s.Length];
s.Read(dbgdata, 0, dbgdata.Length);
}
}
Assembly pass = Assembly.Load(data, dbgdata);
LoadAssembly(pass);
}
private void fsw_Deleted(object sender, FileSystemEventArgs e)
{
;
}
private void fsw_Renamed(object sender, RenamedEventArgs e)
{
;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management.Automation;
using EnvDTE;
using NuGet.VisualStudio;
namespace NuGet.PowerShell.Commands
{
/// <summary>
/// This command lists the available packages which are either from a package source or installed in the current solution.
/// </summary>
[Cmdlet(VerbsCommon.Get, "Package", DefaultParameterSetName = ParameterAttribute.AllParameterSets)]
[OutputType(typeof(IPackage))]
public class GetPackageCommand : NuGetBaseCommand
{
private readonly IPackageRepositoryFactory _repositoryFactory;
private readonly IVsPackageSourceProvider _packageSourceProvider;
private readonly IPackageRepository _recentPackagesRepository;
private readonly IProductUpdateService _productUpdateService;
private int _firstValue;
private bool _firstValueSpecified;
private bool _hasConnectedToHttpSource;
public GetPackageCommand()
: this(ServiceLocator.GetInstance<IPackageRepositoryFactory>(),
ServiceLocator.GetInstance<IVsPackageSourceProvider>(),
ServiceLocator.GetInstance<ISolutionManager>(),
ServiceLocator.GetInstance<IVsPackageManagerFactory>(),
ServiceLocator.GetInstance<IRecentPackageRepository>(),
ServiceLocator.GetInstance<IHttpClientEvents>(),
ServiceLocator.GetInstance<IProductUpdateService>())
{
}
public GetPackageCommand(IPackageRepositoryFactory repositoryFactory,
IVsPackageSourceProvider packageSourceProvider,
ISolutionManager solutionManager,
IVsPackageManagerFactory packageManagerFactory,
IPackageRepository recentPackagesRepository,
IHttpClientEvents httpClientEvents,
IProductUpdateService productUpdateService)
: base(solutionManager, packageManagerFactory, httpClientEvents)
{
if (repositoryFactory == null)
{
throw new ArgumentNullException("repositoryFactory");
}
if (packageSourceProvider == null)
{
throw new ArgumentNullException("packageSourceProvider");
}
if (recentPackagesRepository == null)
{
throw new ArgumentNullException("recentPackagesRepository");
}
_repositoryFactory = repositoryFactory;
_packageSourceProvider = packageSourceProvider;
_recentPackagesRepository = recentPackagesRepository;
_productUpdateService = productUpdateService;
}
[Parameter(Position = 0)]
[ValidateNotNullOrEmpty]
public string Filter { get; set; }
[Parameter(Position = 1, ParameterSetName = "Remote")]
[Parameter(Position = 1, ParameterSetName = "Updates")]
[ValidateNotNullOrEmpty]
public string Source { get; set; }
[Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "Project")]
[ValidateNotNullOrEmpty]
public string ProjectName { get; set; }
[Parameter(Mandatory = true, ParameterSetName = "Remote")]
[Alias("Online", "Remote")]
public SwitchParameter ListAvailable { get; set; }
[Parameter(Mandatory = true, ParameterSetName = "Updates")]
public SwitchParameter Updates { get; set; }
[Parameter(Mandatory = true, ParameterSetName = "Recent")]
public SwitchParameter Recent { get; set; }
[Parameter(ParameterSetName = "Remote")]
[Parameter(ParameterSetName = "Recent")]
[Parameter(ParameterSetName = "Updates")]
public SwitchParameter AllVersions { get; set; }
[Parameter(ParameterSetName = "Remote")]
[Parameter(ParameterSetName = "Updates")]
[Alias("Prerelease")]
public SwitchParameter IncludePrerelease { get; set; }
[Parameter]
[ValidateRange(0, Int32.MaxValue)]
public int First
{
get
{
return _firstValue;
}
set
{
_firstValue = value;
_firstValueSpecified = true;
}
}
[Parameter]
[ValidateRange(0, Int32.MaxValue)]
public int Skip { get; set; }
/// <summary>
/// Determines if local repository are not needed to process this command
/// </summary>
private bool UseRemoteSourceOnly
{
get
{
return ListAvailable.IsPresent || (!String.IsNullOrEmpty(Source) && !Updates.IsPresent) || Recent.IsPresent;
}
}
/// <summary>
/// Determines if a remote repository will be used to process this command.
/// </summary>
private bool UseRemoteSource
{
get
{
return ListAvailable.IsPresent || Updates.IsPresent || !String.IsNullOrEmpty(Source) || Recent.IsPresent;
}
}
protected virtual bool CollapseVersions
{
get
{
return !AllVersions.IsPresent && (ListAvailable || Recent);
}
}
private IProjectManager GetProjectManager(string projectName)
{
Project project = SolutionManager.GetProject(projectName);
if (project == null)
{
ErrorHandler.ThrowNoCompatibleProjectsTerminatingError();
}
IProjectManager projectManager = PackageManager.GetProjectManager(project);
Debug.Assert(projectManager != null);
return projectManager;
}
protected override void ProcessRecordCore()
{
if (!UseRemoteSourceOnly && !SolutionManager.IsSolutionOpen)
{
ErrorHandler.ThrowSolutionNotOpenTerminatingError();
}
IPackageRepository repository;
if (UseRemoteSource)
{
repository = GetRemoteRepository();
}
else if (!String.IsNullOrEmpty(ProjectName))
{
// use project repository when ProjectName is specified
repository = GetProjectManager(ProjectName).LocalRepository;
}
else
{
repository = PackageManager.LocalRepository;
}
IQueryable<IPackage> packages = Updates.IsPresent
? GetPackagesForUpdate(repository)
: GetPackages(repository);
// Apply VersionCollapsing, Skip and Take, in that order.
var packagesToDisplay = FilterPackages(repository, packages);
WritePackages(packagesToDisplay);
}
protected virtual IEnumerable<IPackage> FilterPackages(IPackageRepository sourceRepository, IQueryable<IPackage> packages)
{
if (CollapseVersions)
{
// In the event the client is going up against a v1 feed, do not try to fetch pre release packages since this flag does not exist.
if (Recent || (IncludePrerelease && sourceRepository.SupportsPrereleasePackages))
{
// For Recent packages, we want to show the highest package even if it is a recent.
// Review: We should change this to show both the absolute latest and the latest versions but that requires changes to our collapsing behavior.
packages = packages.Where(p => p.IsAbsoluteLatestVersion);
}
else
{
packages = packages.Where(p => p.IsLatestVersion);
}
}
if (UseRemoteSourceOnly && _firstValueSpecified)
{
// Optimization: If First parameter is specified, we'll wrap the IQueryable in a BufferedEnumerable to prevent consuming the entire result set.
packages = packages.AsBufferedEnumerable(First * 3).AsQueryable();
}
IEnumerable<IPackage> packagesToDisplay = packages.AsEnumerable()
.Where(PackageExtensions.IsListed);
// When querying a remote source, collapse versions unless AllVersions is specified.
// We need to do this as the last step of the Queryable as the filtering occurs on the client.
if (CollapseVersions)
{
// Review: We should perform the Listed check over OData for better perf
packagesToDisplay = packagesToDisplay.AsCollapsed();
}
if (ListAvailable && !IncludePrerelease)
{
// If we aren't collapsing versions, and the pre-release flag is not set, only display release versions when displaying from a remote source.
// We don't need to filter packages when showing recent packages or installed packages.
packagesToDisplay = packagesToDisplay.Where(p => p.IsReleaseVersion());
}
packagesToDisplay = packagesToDisplay.Skip(Skip);
if (_firstValueSpecified)
{
packagesToDisplay = packagesToDisplay.Take(First);
}
return packagesToDisplay;
}
/// <summary>
/// Determines the remote repository to be used based on the state of the solution and the Source parameter
/// </summary>
private IPackageRepository GetRemoteRepository()
{
if (!String.IsNullOrEmpty(Source))
{
_hasConnectedToHttpSource |= UriHelper.IsHttpSource(Source);
// If a Source parameter is explicitly specified, use it
return CreateRepositoryFromSource(_repositoryFactory, _packageSourceProvider, Source);
}
else if (Recent.IsPresent)
{
return _recentPackagesRepository;
}
else if (SolutionManager.IsSolutionOpen)
{
_hasConnectedToHttpSource |= UriHelper.IsHttpSource(_packageSourceProvider);
// If the solution is open, retrieve the cached repository instance
return PackageManager.SourceRepository;
}
else if (_packageSourceProvider.ActivePackageSource != null)
{
_hasConnectedToHttpSource |= UriHelper.IsHttpSource(_packageSourceProvider);
// No solution available. Use the repository Url to create a new repository
return _repositoryFactory.CreateRepository(_packageSourceProvider.ActivePackageSource.Source);
}
else
{
// No active source has been specified.
throw new InvalidOperationException(Resources.Cmdlet_NoActivePackageSource);
}
}
protected virtual IQueryable<IPackage> GetPackages(IPackageRepository sourceRepository)
{
IQueryable<IPackage> packages = String.IsNullOrEmpty(Filter)
? sourceRepository.GetPackages()
: sourceRepository.Search(Filter, IncludePrerelease);
// for recent packages, we want to order by last installed first instead of Id
if (!Recent.IsPresent)
{
packages = packages.OrderBy(p => p.Id);
}
return packages;
}
protected virtual IQueryable<IPackage> GetPackagesForUpdate(IPackageRepository sourceRepository)
{
IPackageRepository localRepository = PackageManager.LocalRepository;
var packagesToUpdate = localRepository.GetPackages();
if (!String.IsNullOrEmpty(Filter))
{
packagesToUpdate = packagesToUpdate.Find(Filter);
}
return sourceRepository.GetUpdates(packagesToUpdate, IncludePrerelease, AllVersions).AsQueryable();
}
private void WritePackages(IEnumerable<IPackage> packages)
{
bool hasPackage = false;
foreach (var package in packages)
{
// exit early if ctrl+c pressed
if (Stopping)
{
break;
}
hasPackage = true;
var pso = new PSObject(package);
if (!pso.Properties.Any(p => p.Name == "IsUpdate"))
{
pso.Properties.Add(new PSNoteProperty("IsUpdate", Updates.IsPresent));
}
WriteObject(pso);
}
if (!hasPackage)
{
if (!UseRemoteSource)
{
LogCore(MessageLevel.Info, Resources.Cmdlet_NoPackagesInstalled);
}
else if (Updates.IsPresent)
{
LogCore(MessageLevel.Info, Resources.Cmdlet_NoPackageUpdates);
}
else if (Recent.IsPresent)
{
LogCore(MessageLevel.Info, Resources.Cmdlet_NoRecentPackages);
}
}
}
protected override void EndProcessing()
{
base.EndProcessing();
CheckForNuGetUpdate();
}
private void CheckForNuGetUpdate()
{
if (_productUpdateService != null && _hasConnectedToHttpSource)
{
_productUpdateService.CheckForAvailableUpdateAsync();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using BTDB.Buffer;
using BTDB.FieldHandler;
using BTDB.KVDBLayer;
using BTDB.StreamLayer;
namespace BTDB.ODBLayer
{
class RelationEnumerator<T> : IEnumerator<T>, IEnumerable<T>
{
protected readonly IInternalObjectDBTransaction Transaction;
protected readonly RelationInfo RelationInfo;
protected readonly RelationInfo.ItemLoaderInfo ItemLoader;
readonly IRelationModificationCounter _modificationCounter;
readonly KeyValueDBTransactionProtector _keyValueTrProtector;
readonly IKeyValueDBTransaction _keyValueTr;
long _prevProtectionCounter;
uint _pos;
bool _seekNeeded;
protected ByteBuffer KeyBytes;
int _prevModificationCounter;
public RelationEnumerator(IInternalObjectDBTransaction tr, RelationInfo relationInfo, ByteBuffer keyBytes,
IRelationModificationCounter modificationCounter, int loaderIndex)
{
RelationInfo = relationInfo;
Transaction = tr;
ItemLoader = relationInfo.ItemLoaderInfos[loaderIndex];
_keyValueTr = Transaction.KeyValueDBTransaction;
_keyValueTrProtector = Transaction.TransactionProtector;
_prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
KeyBytes = keyBytes;
_modificationCounter = modificationCounter;
_keyValueTrProtector.Start();
_keyValueTr.SetKeyPrefix(KeyBytes);
_pos = 0;
_seekNeeded = true;
_prevModificationCounter = _modificationCounter.ModificationCounter;
}
public bool MoveNext()
{
if (!_seekNeeded)
_pos++;
_keyValueTrProtector.Start();
if (_keyValueTrProtector.WasInterupted(_prevProtectionCounter))
{
_modificationCounter.CheckModifiedDuringEnum(_prevModificationCounter);
_keyValueTr.SetKeyPrefix(KeyBytes);
}
var ret = Seek();
_prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
return ret;
}
bool Seek()
{
if (!_keyValueTr.SetKeyIndex(_pos))
return false;
_seekNeeded = false;
return true;
}
public T Current
{
get
{
SeekCurrent();
var keyBytes = _keyValueTr.GetKey();
var valueBytes = _keyValueTr.GetValue();
return CreateInstance(keyBytes, valueBytes);
}
}
public virtual ByteBuffer GetKeyBytes()
{
SeekCurrent();
return _keyValueTr.GetKey();
}
void SeekCurrent()
{
if (_seekNeeded) throw new BTDBException("Invalid access to uninitialized Current.");
_keyValueTrProtector.Start();
if (_keyValueTrProtector.WasInterupted(_prevProtectionCounter))
{
_modificationCounter.CheckModifiedDuringEnum(_prevModificationCounter);
_keyValueTr.SetKeyPrefix(KeyBytes);
Seek();
}
_prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
}
protected virtual T CreateInstance(ByteBuffer keyBytes, ByteBuffer valueBytes)
{
return (T) ItemLoader.CreateInstance(Transaction, keyBytes, valueBytes);
}
object IEnumerator.Current => Current;
public void Reset()
{
_pos = 0;
_seekNeeded = true;
}
public void Dispose()
{
}
public IEnumerator<T> GetEnumerator()
{
if (_pos > 0)
{
Reset();
}
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
class RelationPrimaryKeyEnumerator<T> : RelationEnumerator<T>
{
readonly int _skipBytes;
public RelationPrimaryKeyEnumerator(IInternalObjectDBTransaction tr, RelationInfo relationInfo,
ByteBuffer keyBytes, IRelationModificationCounter modificationCounter, int loaderIndex)
: base(tr, relationInfo, keyBytes, modificationCounter, loaderIndex)
{
_skipBytes = relationInfo.Prefix.Length;
}
protected override T CreateInstance(ByteBuffer keyBytes, ByteBuffer valueBytes)
{
var keyData = new byte[KeyBytes.Length - _skipBytes + keyBytes.Length];
Array.Copy(KeyBytes.Buffer, KeyBytes.Offset + _skipBytes, keyData, 0, KeyBytes.Length - _skipBytes);
Array.Copy(keyBytes.Buffer, keyBytes.Offset, keyData, KeyBytes.Length - _skipBytes, keyBytes.Length);
return (T) ItemLoader.CreateInstance(Transaction, ByteBuffer.NewAsync(keyData), valueBytes);
}
public override ByteBuffer GetKeyBytes()
{
var keyBytes = base.GetKeyBytes();
var keyData = new byte[KeyBytes.Length + keyBytes.Length];
Array.Copy(KeyBytes.Buffer, KeyBytes.Offset, keyData, 0, KeyBytes.Length);
Array.Copy(keyBytes.Buffer, keyBytes.Offset, keyData, KeyBytes.Length, keyBytes.Length);
return ByteBuffer.NewAsync(keyData);
}
}
class RelationSecondaryKeyEnumerator<T> : RelationEnumerator<T>
{
readonly uint _secondaryKeyIndex;
readonly uint _fieldCountInKey;
readonly IRelationDbManipulator _manipulator;
public RelationSecondaryKeyEnumerator(IInternalObjectDBTransaction tr, RelationInfo relationInfo,
ByteBuffer keyBytes, uint secondaryKeyIndex, uint fieldCountInKey, IRelationDbManipulator manipulator,
int loaderIndex)
: base(tr, relationInfo, keyBytes, manipulator.ModificationCounter, loaderIndex)
{
_secondaryKeyIndex = secondaryKeyIndex;
_fieldCountInKey = fieldCountInKey;
_manipulator = manipulator;
}
protected override T CreateInstance(ByteBuffer keyBytes, ByteBuffer valueBytes)
{
return (T) _manipulator.CreateInstanceFromSecondaryKey(ItemLoader, _secondaryKeyIndex, _fieldCountInKey,
KeyBytes, keyBytes);
}
}
public class RelationAdvancedEnumerator<T> : IEnumerator<T>, IEnumerable<T>
{
protected readonly uint _prefixFieldCount;
protected readonly IRelationDbManipulator _manipulator;
protected readonly RelationInfo.ItemLoaderInfo ItemLoader;
readonly KeyValueDBTransactionProtector _keyValueTrProtector;
readonly IInternalObjectDBTransaction _tr;
readonly IKeyValueDBTransaction _keyValueTr;
long _prevProtectionCounter;
readonly uint _startPos;
readonly uint _count;
uint _pos;
bool _seekNeeded;
readonly bool _ascending;
protected readonly ByteBuffer _keyBytes;
readonly int _lengthOfNonDataPrefix;
readonly int _prevModificationCounter;
public RelationAdvancedEnumerator(
IRelationDbManipulator manipulator,
ByteBuffer prefixBytes, uint prefixFieldCount,
EnumerationOrder order,
KeyProposition startKeyProposition, ByteBuffer startKeyBytes,
KeyProposition endKeyProposition, ByteBuffer endKeyBytes, int loaderIndex)
{
_prefixFieldCount = prefixFieldCount;
_manipulator = manipulator;
ItemLoader = _manipulator.RelationInfo.ItemLoaderInfos[loaderIndex];
_ascending = order == EnumerationOrder.Ascending;
_tr = manipulator.Transaction;
_keyValueTr = _tr.KeyValueDBTransaction;
_keyValueTrProtector = _tr.TransactionProtector;
_prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
_keyBytes = prefixBytes;
if (endKeyProposition == KeyProposition.Included)
endKeyBytes = FindLastKeyWithPrefix(_keyBytes, endKeyBytes, _keyValueTr, _keyValueTrProtector);
_keyValueTrProtector.Start();
_keyValueTr.SetKeyPrefix(_keyBytes);
_prevModificationCounter = manipulator.ModificationCounter.ModificationCounter;
long startIndex;
long endIndex;
if (endKeyProposition == KeyProposition.Ignored)
{
endIndex = _keyValueTr.GetKeyValueCount() - 1;
}
else
{
switch (_keyValueTr.Find(endKeyBytes))
{
case FindResult.Exact:
endIndex = _keyValueTr.GetKeyIndex();
if (endKeyProposition == KeyProposition.Excluded)
{
endIndex--;
}
break;
case FindResult.Previous:
endIndex = _keyValueTr.GetKeyIndex();
break;
case FindResult.Next:
endIndex = _keyValueTr.GetKeyIndex() - 1;
break;
case FindResult.NotFound:
endIndex = -1;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
if (startKeyProposition == KeyProposition.Ignored)
{
startIndex = 0;
}
else
{
switch (_keyValueTr.Find(startKeyBytes))
{
case FindResult.Exact:
startIndex = _keyValueTr.GetKeyIndex();
if (startKeyProposition == KeyProposition.Excluded)
{
startIndex++;
}
break;
case FindResult.Previous:
startIndex = _keyValueTr.GetKeyIndex() + 1;
break;
case FindResult.Next:
startIndex = _keyValueTr.GetKeyIndex();
break;
case FindResult.NotFound:
startIndex = 0;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
_count = (uint) Math.Max(0, endIndex - startIndex + 1);
_startPos = (uint) (_ascending ? startIndex : endIndex);
_pos = 0;
_seekNeeded = true;
_lengthOfNonDataPrefix = manipulator.RelationInfo.Prefix.Length;
}
public RelationAdvancedEnumerator(
IRelationDbManipulator manipulator, ByteBuffer prefixBytes, uint prefixFieldCount, int loaderIndex)
{
_prefixFieldCount = prefixFieldCount;
_manipulator = manipulator;
ItemLoader = _manipulator.RelationInfo.ItemLoaderInfos[loaderIndex];
_ascending = true;
_tr = manipulator.Transaction;
_keyValueTr = _tr.KeyValueDBTransaction;
_keyValueTrProtector = _tr.TransactionProtector;
_prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
_keyBytes = prefixBytes;
_keyValueTrProtector.Start();
_keyValueTr.SetKeyPrefix(_keyBytes);
_prevModificationCounter = manipulator.ModificationCounter.ModificationCounter;
_count = (uint) _keyValueTr.GetKeyValueCount();
_startPos = _ascending ? 0 : _count - 1;
_pos = 0;
_seekNeeded = true;
_lengthOfNonDataPrefix = manipulator.RelationInfo.Prefix.Length;
}
internal static ByteBuffer FindLastKeyWithPrefix(ByteBuffer keyBytes, ByteBuffer endKeyBytes,
IKeyValueDBTransaction keyValueTr, KeyValueDBTransactionProtector keyValueTrProtector)
{
var buffer = ByteBuffer.NewEmpty();
buffer = buffer.ResizingAppend(keyBytes).ResizingAppend(endKeyBytes);
keyValueTrProtector.Start();
keyValueTr.SetKeyPrefix(buffer);
if (!keyValueTr.FindLastKey())
return endKeyBytes;
var key = keyValueTr.GetKeyIncludingPrefix();
return key.Slice(keyBytes.Length);
}
public bool MoveNext()
{
if (!_seekNeeded)
_pos++;
if (_pos >= _count)
return false;
_keyValueTrProtector.Start();
if (_keyValueTrProtector.WasInterupted(_prevProtectionCounter))
{
_manipulator.ModificationCounter.CheckModifiedDuringEnum(_prevModificationCounter);
_keyValueTr.SetKeyPrefix(_keyBytes);
Seek();
}
else if (_seekNeeded)
{
Seek();
}
else
{
if (_ascending)
{
_keyValueTr.FindNextKey();
}
else
{
_keyValueTr.FindPreviousKey();
}
}
_prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
return true;
}
public void Reset()
{
_pos = 0;
_seekNeeded = true;
}
public T Current
{
get
{
if (_pos >= _count) throw new IndexOutOfRangeException();
if (_seekNeeded) throw new BTDBException("Invalid access to uninitialized Current.");
_keyValueTrProtector.Start();
if (_keyValueTrProtector.WasInterupted(_prevProtectionCounter))
{
_manipulator.ModificationCounter.CheckModifiedDuringEnum(_prevModificationCounter);
_keyValueTr.SetKeyPrefix(_keyBytes);
Seek();
}
_prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
var keyBytes = _keyValueTr.GetKey();
return CreateInstance(keyBytes);
}
}
protected virtual T CreateInstance(ByteBuffer keyBytes)
{
var data = new byte[_keyBytes.Length - _lengthOfNonDataPrefix + keyBytes.Length];
Array.Copy(_keyBytes.Buffer, _keyBytes.Offset + _lengthOfNonDataPrefix, data, 0,
_keyBytes.Length - _lengthOfNonDataPrefix);
Array.Copy(keyBytes.Buffer, keyBytes.Offset, data, _keyBytes.Length - _lengthOfNonDataPrefix,
keyBytes.Length);
return (T) ItemLoader.CreateInstance(_tr, ByteBuffer.NewAsync(data), _keyValueTr.GetValue());
}
public ByteBuffer GetKeyBytes()
{
return _keyValueTr.GetKeyIncludingPrefix();
}
void Seek()
{
if (_ascending)
_keyValueTr.SetKeyIndex(_startPos + _pos);
else
_keyValueTr.SetKeyIndex(_startPos - _pos);
_seekNeeded = false;
}
object IEnumerator.Current => Current;
public void Dispose()
{
}
public IEnumerator<T> GetEnumerator()
{
if (_pos > 0)
{
Reset();
}
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class RelationAdvancedSecondaryKeyEnumerator<T> : RelationAdvancedEnumerator<T>
{
readonly uint _secondaryKeyIndex;
public RelationAdvancedSecondaryKeyEnumerator(
IRelationDbManipulator manipulator,
ByteBuffer prefixBytes, uint prefixFieldCount,
EnumerationOrder order,
KeyProposition startKeyProposition, ByteBuffer startKeyBytes,
KeyProposition endKeyProposition, ByteBuffer endKeyBytes,
uint secondaryKeyIndex, int loaderIndex)
: base(manipulator, prefixBytes, prefixFieldCount, order,
startKeyProposition, startKeyBytes,
endKeyProposition, endKeyBytes, loaderIndex)
{
_secondaryKeyIndex = secondaryKeyIndex;
}
public RelationAdvancedSecondaryKeyEnumerator(
IRelationDbManipulator manipulator,
ByteBuffer prefixBytes, uint prefixFieldCount,
uint secondaryKeyIndex, int loaderIndex)
: base(manipulator, prefixBytes, prefixFieldCount, loaderIndex)
{
_secondaryKeyIndex = secondaryKeyIndex;
}
protected override T CreateInstance(ByteBuffer keyBytes)
{
return (T) _manipulator.CreateInstanceFromSecondaryKey(ItemLoader, _secondaryKeyIndex, _prefixFieldCount,
_keyBytes, keyBytes);
}
}
public class RelationAdvancedOrderedEnumerator<TKey, TValue> : IOrderedDictionaryEnumerator<TKey, TValue>
{
protected readonly uint _prefixFieldCount;
protected readonly IRelationDbManipulator _manipulator;
protected readonly RelationInfo.ItemLoaderInfo ItemLoader;
readonly IInternalObjectDBTransaction _tr;
readonly KeyValueDBTransactionProtector _keyValueTrProtector;
readonly IKeyValueDBTransaction _keyValueTr;
long _prevProtectionCounter;
readonly uint _startPos;
readonly uint _count;
uint _pos;
SeekState _seekState;
readonly bool _ascending;
protected readonly ByteBuffer _keyBytes;
protected Func<AbstractBufferedReader, IReaderCtx, TKey> _keyReader;
readonly int _lengthOfNonDataPrefix;
public RelationAdvancedOrderedEnumerator(IRelationDbManipulator manipulator,
ByteBuffer prefixBytes, uint prefixFieldCount,
EnumerationOrder order,
KeyProposition startKeyProposition, ByteBuffer startKeyBytes,
KeyProposition endKeyProposition, ByteBuffer endKeyBytes, bool initKeyReader, int loaderIndex)
{
_prefixFieldCount = prefixFieldCount;
_manipulator = manipulator;
ItemLoader = _manipulator.RelationInfo.ItemLoaderInfos[loaderIndex];
_tr = manipulator.Transaction;
_ascending = order == EnumerationOrder.Ascending;
_keyValueTr = _tr.KeyValueDBTransaction;
_keyValueTrProtector = _tr.TransactionProtector;
_prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
_keyBytes = prefixBytes;
if (endKeyProposition == KeyProposition.Included)
endKeyBytes = RelationAdvancedEnumerator<TValue>.FindLastKeyWithPrefix(_keyBytes, endKeyBytes,
_keyValueTr, _keyValueTrProtector);
_keyValueTrProtector.Start();
_keyValueTr.SetKeyPrefix(_keyBytes);
long startIndex;
long endIndex;
if (endKeyProposition == KeyProposition.Ignored)
{
endIndex = _keyValueTr.GetKeyValueCount() - 1;
}
else
{
switch (_keyValueTr.Find(endKeyBytes))
{
case FindResult.Exact:
endIndex = _keyValueTr.GetKeyIndex();
if (endKeyProposition == KeyProposition.Excluded)
{
endIndex--;
}
break;
case FindResult.Previous:
endIndex = _keyValueTr.GetKeyIndex();
break;
case FindResult.Next:
endIndex = _keyValueTr.GetKeyIndex() - 1;
break;
case FindResult.NotFound:
endIndex = -1;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
if (startKeyProposition == KeyProposition.Ignored)
{
startIndex = 0;
}
else
{
switch (_keyValueTr.Find(startKeyBytes))
{
case FindResult.Exact:
startIndex = _keyValueTr.GetKeyIndex();
if (startKeyProposition == KeyProposition.Excluded)
{
startIndex++;
}
break;
case FindResult.Previous:
startIndex = _keyValueTr.GetKeyIndex() + 1;
break;
case FindResult.Next:
startIndex = _keyValueTr.GetKeyIndex();
break;
case FindResult.NotFound:
startIndex = 0;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
_count = (uint) Math.Max(0, endIndex - startIndex + 1);
_startPos = (uint) (_ascending ? startIndex : endIndex);
_pos = 0;
_seekState = SeekState.Undefined;
if (initKeyReader)
{
var primaryKeyFields = manipulator.RelationInfo.ClientRelationVersionInfo.PrimaryKeyFields;
var advancedEnumParamField = primaryKeyFields.Span[(int) _prefixFieldCount];
if (advancedEnumParamField.Handler!.NeedsCtx())
throw new BTDBException("Not supported.");
_keyReader = (Func<AbstractBufferedReader, IReaderCtx, TKey>) manipulator.RelationInfo
.GetSimpleLoader(new RelationInfo.SimpleLoaderType(advancedEnumParamField.Handler, typeof(TKey)));
_lengthOfNonDataPrefix = manipulator.RelationInfo.Prefix.Length;
}
}
public uint Count => _count;
protected virtual TValue CreateInstance(ByteBuffer prefixKeyBytes, ByteBuffer keyBytes)
{
var data = new byte[_keyBytes.Length - _lengthOfNonDataPrefix + keyBytes.Length];
Array.Copy(_keyBytes.Buffer, _keyBytes.Offset + _lengthOfNonDataPrefix, data, 0,
_keyBytes.Length - _lengthOfNonDataPrefix);
Array.Copy(keyBytes.Buffer, keyBytes.Offset, data, _keyBytes.Length - _lengthOfNonDataPrefix,
keyBytes.Length);
return (TValue) ItemLoader.CreateInstance(_tr, ByteBuffer.NewAsync(data),
_keyValueTr.GetValue());
}
public TValue CurrentValue
{
get
{
if (_pos >= _count) throw new IndexOutOfRangeException();
if (_seekState == SeekState.Undefined)
throw new BTDBException("Invalid access to uninitialized CurrentValue.");
_keyValueTrProtector.Start();
if (_keyValueTrProtector.WasInterupted(_prevProtectionCounter))
{
_keyValueTr.SetKeyPrefix(_keyBytes);
Seek();
}
else if (_seekState != SeekState.Ready)
{
Seek();
}
_prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
var keyBytes = _keyValueTr.GetKey();
return CreateInstance(_keyBytes, keyBytes);
}
set { throw new NotSupportedException(); }
}
void Seek()
{
if (_ascending)
_keyValueTr.SetKeyIndex(_startPos + _pos);
else
_keyValueTr.SetKeyIndex(_startPos - _pos);
_seekState = SeekState.Ready;
}
public uint Position
{
get { return _pos; }
set
{
_pos = value > _count ? _count : value;
_seekState = SeekState.SeekNeeded;
}
}
public bool NextKey(out TKey key)
{
if (_seekState == SeekState.Ready)
_pos++;
if (_pos >= _count)
{
key = default(TKey);
return false;
}
_keyValueTrProtector.Start();
if (_keyValueTrProtector.WasInterupted(_prevProtectionCounter))
{
_keyValueTr.SetKeyPrefix(_keyBytes);
Seek();
}
else if (_seekState != SeekState.Ready)
{
Seek();
}
else
{
if (_ascending)
{
_keyValueTr.FindNextKey();
}
else
{
_keyValueTr.FindPreviousKey();
}
}
_prevProtectionCounter = _keyValueTrProtector.ProtectionCounter;
//read key
var keyData = _keyValueTr.GetKeyAsByteArray();
var reader = new ByteArrayReader(keyData);
key = _keyReader(reader, null);
return true;
}
}
public class RelationAdvancedOrderedSecondaryKeyEnumerator<TKey, TValue> :
RelationAdvancedOrderedEnumerator<TKey, TValue>
{
readonly uint _secondaryKeyIndex;
public RelationAdvancedOrderedSecondaryKeyEnumerator(IRelationDbManipulator manipulator,
ByteBuffer prefixBytes, uint prefixFieldCount, EnumerationOrder order,
KeyProposition startKeyProposition, ByteBuffer startKeyBytes,
KeyProposition endKeyProposition, ByteBuffer endKeyBytes,
uint secondaryKeyIndex, int loaderIndex)
: base(manipulator, prefixBytes, prefixFieldCount, order,
startKeyProposition, startKeyBytes,
endKeyProposition, endKeyBytes, false, loaderIndex)
{
_secondaryKeyIndex = secondaryKeyIndex;
var secKeyFields =
manipulator.RelationInfo.ClientRelationVersionInfo.GetSecondaryKeyFields(secondaryKeyIndex);
var advancedEnumParamField = secKeyFields[(int) _prefixFieldCount];
if (advancedEnumParamField.Handler!.NeedsCtx())
throw new BTDBException("Not supported.");
_keyReader = (Func<AbstractBufferedReader, IReaderCtx, TKey>) manipulator.RelationInfo
.GetSimpleLoader(new RelationInfo.SimpleLoaderType(advancedEnumParamField.Handler, typeof(TKey)));
}
protected override TValue CreateInstance(ByteBuffer prefixKeyBytes, ByteBuffer keyBytes)
{
return (TValue) _manipulator.CreateInstanceFromSecondaryKey(ItemLoader, _secondaryKeyIndex,
_prefixFieldCount, _keyBytes, keyBytes);
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace UMA
{
/// <summary>
/// Overlay color data.
/// </summary>
[System.Serializable]
public class OverlayColorData : System.IEquatable<OverlayColorData>
{
public static int currentinstance = 0;
[NonSerialized]
public int instance;
public static Color EmptyAdditive = new Color(0, 0, 0, 0);
public const string UNSHARED = "-";
public string name;
[ColorUsage(true, true)]
public Color[] channelMask = new Color[0];
public Color[] channelAdditiveMask = new Color[0];
public UMAMaterialPropertyBlock PropertyBlock; // may be null.
#if UNITY_EDITOR
public bool foldout;
#endif
public Color color
{
get
{
if (channelMask.Length < 1)
return Color.white;
return channelMask[0];
}
set
{
if (channelMask.Length > 0)
channelMask[0] = value;
}
}
public int channelCount { get { return channelMask.Length; } }
public bool isDefault(int Channel)
{
if (Channel <= channelCount)
{
if (channelMask[Channel] == Color.white)
{
if (channelAdditiveMask[Channel] == EmptyAdditive)
{
return true;
}
}
}
return false;
}
/// <summary>
/// Default constructor
/// </summary>
public OverlayColorData()
{
instance = currentinstance++;
}
/// <summary>
/// Constructor for a given number of channels.
/// </summary>
/// <param name="channels">Channels.</param>
public OverlayColorData(int channels)
{
channelMask = new Color[channels];
channelAdditiveMask = new Color[channels];
for(int i= 0; i < channels; i++ )
{
channelMask[i] = Color.white;
channelAdditiveMask[i] = new Color(0,0,0,0);
}
}
/// <summary>
/// Deep copy of the OverlayColorData.
/// </summary>
public OverlayColorData Duplicate()
{
var res = new OverlayColorData();
res.name = name;
res.channelMask = new Color[channelMask.Length];
for (int i = 0; i < channelMask.Length; i++)
{
res.channelMask[i] = channelMask[i];
}
res.channelAdditiveMask = new Color[channelAdditiveMask.Length];
for (int i = 0; i < channelAdditiveMask.Length; i++)
{
res.channelAdditiveMask[i] = channelAdditiveMask[i];
}
if (PropertyBlock != null)
{
res.PropertyBlock = new UMAMaterialPropertyBlock();
res.PropertyBlock.alwaysUpdate = PropertyBlock.alwaysUpdate;
res.PropertyBlock.shaderProperties = new List<UMAProperty>(PropertyBlock.shaderProperties.Count);
for(int i=0;i<PropertyBlock.shaderProperties.Count;i++)
{
UMAProperty up = PropertyBlock.shaderProperties[i];
if (up != null)
{
res.PropertyBlock.shaderProperties.Add(up.Clone());
}
}
}
return res;
}
/// <summary>
/// This needs to be better
/// </summary>
/// <returns><c>true</c> if this instance is A shared color; otherwise, <c>false</c>.</returns>
public bool IsASharedColor
{
get
{
if (HasName() && name != UNSHARED) return true;
return false;
}
}
public bool isValid
{
get
{
return PropertyBlock == null && channelMask.Length == 0;
}
}
public bool HasColors
{
get
{
return channelMask.Length > 0;
}
}
public bool HasPropertyBlock
{
get
{
return PropertyBlock != null;
}
}
public bool HasProperties
{
get
{
if (PropertyBlock == null) return false;
return PropertyBlock.shaderProperties.Count > 0;
}
}
public bool isOnlyColors
{
get
{
return PropertyBlock == null && channelMask.Length > 0;
}
}
public bool isOnlyProperties
{
get
{
return PropertyBlock != null && channelMask.Length > 0;
}
}
/// <summary>
/// Does the OverlayColorData have a valid name?
/// </summary>
/// <returns><c>true</c> if this instance has a valid name; otherwise, <c>false</c>.</returns>
public bool HasName()
{
return ((name != null) && (name.Length > 0));
}
/// <summary>
/// Are two Unity Colors the same?
/// </summary>
/// <returns><c>true</c>, if colors are identical, <c>false</c> otherwise.</returns>
/// <param name="color1">Color1.</param>
/// <param name="color2">Color2.</param>
public static bool SameColor(Color color1, Color color2)
{
return (Mathf.Approximately(color1.r, color2.r) &&
Mathf.Approximately(color1.g, color2.g) &&
Mathf.Approximately(color1.b, color2.b) &&
Mathf.Approximately(color1.a, color2.a));
}
/// <summary>
/// Are two Unity Colors different?
/// </summary>
/// <returns><c>true</c>, if colors are different, <c>false</c> otherwise.</returns>
/// <param name="color1">Color1.</param>
/// <param name="color2">Color2.</param>
public static bool DifferentColor(Color color1, Color color2)
{
return (!Mathf.Approximately(color1.r, color2.r) ||
!Mathf.Approximately(color1.g, color2.g) ||
!Mathf.Approximately(color1.b, color2.b) ||
!Mathf.Approximately(color1.a, color2.a));
}
public static implicit operator bool(OverlayColorData obj)
{
return ((System.Object)obj) != null;
}
public bool Equals(OverlayColorData other)
{
return (this == other);
}
public override bool Equals(object other)
{
return Equals(other as OverlayColorData);
}
public static bool operator == (OverlayColorData cd1, OverlayColorData cd2)
{
if (cd1)
{
if (cd2)
{
if (cd2.channelMask.Length != cd1.channelMask.Length) return false;
for (int i = 0; i < cd1.channelMask.Length; i++)
{
if (DifferentColor(cd1.channelMask[i], cd2.channelMask[i]))
return false;
}
for (int i = 0; i < cd1.channelAdditiveMask.Length; i++)
{
if (DifferentColor(cd1.channelAdditiveMask[i], cd2.channelAdditiveMask[i]))
return false;
}
return true;
}
return false;
}
return (!(bool)cd2);
}
public static bool operator != (OverlayColorData cd1, OverlayColorData cd2)
{
if (cd1)
{
if (cd2)
{
if (cd2.channelMask.Length != cd1.channelMask.Length) return true;
for (int i = 0; i < cd1.channelMask.Length; i++)
{
if (DifferentColor(cd1.channelMask[i], cd2.channelMask[i]))
return true;
}
for (int i = 0; i < cd1.channelAdditiveMask.Length; i++)
{
if (DifferentColor(cd1.channelAdditiveMask[i], cd2.channelAdditiveMask[i]))
return true;
}
return false;
}
return true;
}
return ((bool)cd2);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public void SetChannels(int channels)
{
EnsureChannels(channels);
if (channelMask.Length > channels)
{
Array.Resize(ref channelMask, channels);
Array.Resize(ref channelAdditiveMask, channels);
}
}
public void EnsureChannels(int channels)
{
if (channelMask == null)
{
channelMask = new Color[channels];
channelAdditiveMask = new Color[channels];
for (int i = 0; i < channels; i++)
{
channelMask[i] = Color.white;
channelAdditiveMask[i] = new Color(0, 0, 0, 0);
}
}
else
{
if (channelMask.Length < channels)
{
var newMask = new Color[channels];
System.Array.Copy(channelMask, newMask, channelMask.Length);
for (int i = channelMask.Length; i < channels; i++)
{
newMask[i] = Color.white;
}
channelMask = newMask;
}
if (channelAdditiveMask.Length < channels)
{
var newAdditiveMask = new Color[channels];
System.Array.Copy(channelAdditiveMask, newAdditiveMask, channelAdditiveMask.Length);
for (int i = channelAdditiveMask.Length; i < channels; i++)
{
newAdditiveMask[i] = new Color(0,0,0,0);
}
channelAdditiveMask = newAdditiveMask;
}
}
}
public void AssignTo(OverlayColorData dest)
{
if (name != null)
{
dest.name = String.Copy(name);
}
dest.channelMask = new Color[channelMask.Length];
for (int i = 0; i < channelMask.Length; i++)
{
dest.channelMask[i] = channelMask[i];
}
dest.channelAdditiveMask = new Color[channelAdditiveMask.Length];
for (int i = 0; i < channelAdditiveMask.Length; i++)
{
dest.channelAdditiveMask[i] = channelAdditiveMask[i];
}
}
public void AssignFrom(OverlayColorData src)
{
if (src.name != null)
{
name = String.Copy(src.name);
}
EnsureChannels(src.channelMask.Length);
for (int i = 0; i < src.channelMask.Length; i++)
{
channelMask[i] = src.channelMask[i];
}
for (int i = 0; i < src.channelAdditiveMask.Length; i++)
{
channelAdditiveMask[i] = src.channelAdditiveMask[i];
}
PropertyBlock = new UMAMaterialPropertyBlock();
if (src.PropertyBlock != null)
{
PropertyBlock.alwaysUpdate = src.PropertyBlock.alwaysUpdate;
PropertyBlock.shaderProperties = new List<UMAProperty>(src.PropertyBlock.shaderProperties.Count);
for (int i = 0; i < src.PropertyBlock.shaderProperties.Count; i++)
{
UMAProperty up = src.PropertyBlock.shaderProperties[i];
PropertyBlock.shaderProperties.Add(up.Clone());
}
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
using System.Runtime.InteropServices;
namespace System.Security
{
// DynamicSecurityMethodAttribute:
// Indicates that calling the target method requires space for a security
// object to be allocated on the callers stack. This attribute is only ever
// set on certain security methods defined within mscorlib.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false )]
sealed internal class DynamicSecurityMethodAttribute : System.Attribute
{
}
// SuppressUnmanagedCodeSecurityAttribute:
// Indicates that the target P/Invoke method(s) should skip the per-call
// security checked for unmanaged code permission.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class SuppressUnmanagedCodeSecurityAttribute : System.Attribute
{
}
// UnverifiableCodeAttribute:
// Indicates that the target module contains unverifiable code.
[AttributeUsage(AttributeTargets.Module, AllowMultiple = true, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class UnverifiableCodeAttribute : System.Attribute
{
}
// AllowPartiallyTrustedCallersAttribute:
// Indicates that the Assembly is secure and can be used by untrusted
// and semitrusted clients
// For v.1, this is valid only on Assemblies, but could be expanded to
// include Module, Method, class
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class AllowPartiallyTrustedCallersAttribute : System.Attribute
{
private PartialTrustVisibilityLevel _visibilityLevel;
public AllowPartiallyTrustedCallersAttribute () { }
public PartialTrustVisibilityLevel PartialTrustVisibilityLevel
{
get { return _visibilityLevel; }
set { _visibilityLevel = value; }
}
}
public enum PartialTrustVisibilityLevel
{
VisibleToAllHosts = 0,
NotVisibleByDefault = 1
}
#if !FEATURE_CORECLR
[Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")]
public enum SecurityCriticalScope
{
Explicit = 0,
Everything = 0x1
}
#endif // FEATURE_CORECLR
// SecurityCriticalAttribute
// Indicates that the decorated code or assembly performs security critical operations (e.g. Assert, "unsafe", LinkDemand, etc.)
// The attribute can be placed on most targets, except on arguments/return values.
[AttributeUsage(AttributeTargets.Assembly |
AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Field |
AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
Inherited = false )]
sealed public class SecurityCriticalAttribute : System.Attribute
{
#pragma warning disable 618 // We still use SecurityCriticalScope for v2 compat
#if !FEATURE_CORECLR && !MOBILE
private SecurityCriticalScope _val;
#endif // FEATURE_CORECLR
public SecurityCriticalAttribute () {}
#if !FEATURE_CORECLR && !MOBILE
public SecurityCriticalAttribute(SecurityCriticalScope scope)
{
_val = scope;
}
[Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")]
public SecurityCriticalScope Scope {
get {
return _val;
}
}
#endif // FEATURE_CORECLR
#pragma warning restore 618
}
// SecurityTreatAsSafeAttribute:
// Indicates that the code may contain violations to the security critical rules (e.g. transitions from
// critical to non-public transparent, transparent to non-public critical, etc.), has been audited for
// security concerns and is considered security clean.
// At assembly-scope, all rule checks will be suppressed within the assembly and for calls made against the assembly.
// At type-scope, all rule checks will be suppressed for members within the type and for calls made against the type.
// At member level (e.g. field and method) the code will be treated as public - i.e. no rule checks for the members.
[AttributeUsage(AttributeTargets.Assembly |
AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Field |
AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
Inherited = false )]
[Obsolete("SecurityTreatAsSafe is only used for .NET 2.0 transparency compatibility. Please use the SecuritySafeCriticalAttribute instead.")]
sealed public class SecurityTreatAsSafeAttribute : System.Attribute
{
public SecurityTreatAsSafeAttribute () { }
}
// SecuritySafeCriticalAttribute:
// Indicates that the code may contain violations to the security critical rules (e.g. transitions from
// critical to non-public transparent, transparent to non-public critical, etc.), has been audited for
// security concerns and is considered security clean. Also indicates that the code is considered SecurityCritical.
// The effect of this attribute is as if the code was marked [SecurityCritical][SecurityTreatAsSafe].
// At assembly-scope, all rule checks will be suppressed within the assembly and for calls made against the assembly.
// At type-scope, all rule checks will be suppressed for members within the type and for calls made against the type.
// At member level (e.g. field and method) the code will be treated as public - i.e. no rule checks for the members.
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Field |
AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
Inherited = false )]
sealed public class SecuritySafeCriticalAttribute : System.Attribute
{
public SecuritySafeCriticalAttribute () { }
}
// SecurityTransparentAttribute:
// Indicates the assembly contains only transparent code.
// Security critical actions will be restricted or converted into less critical actions. For example,
// Assert will be restricted, SuppressUnmanagedCode, LinkDemand, unsafe, and unverifiable code will be converted
// into Full-Demands.
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false )]
sealed public class SecurityTransparentAttribute : System.Attribute
{
public SecurityTransparentAttribute () {}
}
#if !FEATURE_CORECLR
public enum SecurityRuleSet : byte
{
None = 0,
Level1 = 1, // v2.0 transparency model
Level2 = 2, // v4.0 transparency model
}
// SecurityRulesAttribute
//
// Indicates which set of security rules an assembly was authored against, and therefore which set of
// rules the runtime should enforce on the assembly. For instance, an assembly marked with
// [SecurityRules(SecurityRuleSet.Level1)] will follow the v2.0 transparency rules, where transparent code
// can call a LinkDemand by converting it to a full demand, public critical methods are implicitly
// treat as safe, and the remainder of the v2.0 rules apply.
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class SecurityRulesAttribute : Attribute
{
private SecurityRuleSet m_ruleSet;
private bool m_skipVerificationInFullTrust = false;
public SecurityRulesAttribute(SecurityRuleSet ruleSet)
{
m_ruleSet = ruleSet;
}
// Should fully trusted transparent code skip IL verification
public bool SkipVerificationInFullTrust
{
get { return m_skipVerificationInFullTrust; }
set { m_skipVerificationInFullTrust = value; }
}
public SecurityRuleSet RuleSet
{
get { return m_ruleSet; }
}
}
#endif // !FEATURE_CORECLR
}
| |
// Copyright 2021 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 gcwcv = Google.Cloud.Workflows.Common.V1Beta;
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.Workflows.V1Beta.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedWorkflowsClientTest
{
[xunit::FactAttribute]
public void GetWorkflowRequestObject()
{
moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowRequest request = new GetWorkflowRequest
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
Workflow expectedResponse = new Workflow
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Description = "description2cf9da67",
State = Workflow.Types.State.Unspecified,
RevisionId = "revision_id8d9ae05d",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RevisionCreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ServiceAccount = "service_accounta3c1b923",
SourceContents = "source_contentscf4464d3",
};
mockGrpcClient.Setup(x => x.GetWorkflow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null);
Workflow response = client.GetWorkflow(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkflowRequestObjectAsync()
{
moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowRequest request = new GetWorkflowRequest
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
Workflow expectedResponse = new Workflow
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Description = "description2cf9da67",
State = Workflow.Types.State.Unspecified,
RevisionId = "revision_id8d9ae05d",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RevisionCreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ServiceAccount = "service_accounta3c1b923",
SourceContents = "source_contentscf4464d3",
};
mockGrpcClient.Setup(x => x.GetWorkflowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workflow>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null);
Workflow responseCallSettings = await client.GetWorkflowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Workflow responseCancellationToken = await client.GetWorkflowAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetWorkflow()
{
moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowRequest request = new GetWorkflowRequest
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
Workflow expectedResponse = new Workflow
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Description = "description2cf9da67",
State = Workflow.Types.State.Unspecified,
RevisionId = "revision_id8d9ae05d",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RevisionCreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ServiceAccount = "service_accounta3c1b923",
SourceContents = "source_contentscf4464d3",
};
mockGrpcClient.Setup(x => x.GetWorkflow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null);
Workflow response = client.GetWorkflow(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkflowAsync()
{
moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowRequest request = new GetWorkflowRequest
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
Workflow expectedResponse = new Workflow
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Description = "description2cf9da67",
State = Workflow.Types.State.Unspecified,
RevisionId = "revision_id8d9ae05d",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RevisionCreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ServiceAccount = "service_accounta3c1b923",
SourceContents = "source_contentscf4464d3",
};
mockGrpcClient.Setup(x => x.GetWorkflowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workflow>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null);
Workflow responseCallSettings = await client.GetWorkflowAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Workflow responseCancellationToken = await client.GetWorkflowAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetWorkflowResourceNames()
{
moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowRequest request = new GetWorkflowRequest
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
Workflow expectedResponse = new Workflow
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Description = "description2cf9da67",
State = Workflow.Types.State.Unspecified,
RevisionId = "revision_id8d9ae05d",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RevisionCreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ServiceAccount = "service_accounta3c1b923",
SourceContents = "source_contentscf4464d3",
};
mockGrpcClient.Setup(x => x.GetWorkflow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null);
Workflow response = client.GetWorkflow(request.WorkflowName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkflowResourceNamesAsync()
{
moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowRequest request = new GetWorkflowRequest
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
Workflow expectedResponse = new Workflow
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Description = "description2cf9da67",
State = Workflow.Types.State.Unspecified,
RevisionId = "revision_id8d9ae05d",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RevisionCreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ServiceAccount = "service_accounta3c1b923",
SourceContents = "source_contentscf4464d3",
};
mockGrpcClient.Setup(x => x.GetWorkflowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workflow>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null);
Workflow responseCallSettings = await client.GetWorkflowAsync(request.WorkflowName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Workflow responseCancellationToken = await client.GetWorkflowAsync(request.WorkflowName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
//Licensed to the Apache Software Foundation(ASF) under one
//or more contributor license agreements.See the NOTICE file
//distributed with this work for additional information
//regarding copyright ownership.The ASF licenses this file
//to you under the Apache License, Version 2.0 (the
//"License"); you may not use this file except in compliance
//with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing,
//software distributed under the License is distributed on an
//"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
//KIND, either express or implied. See the License for the
//specific language governing permissions and limitations
//under the License.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using System.Windows;
using Paragon.Plugins;
using Paragon.Properties;
using Paragon.Runtime;
using Paragon.Runtime.Kernel.Applications;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.IO.Packaging;
using System.Text;
using Paragon.Runtime.Win32;
using Paragon.Runtime.Desktop;
namespace Paragon
{
static class Program
{
private static ApplicationManager _appManager;
private static readonly ILogger Logger = ParagonLogManager.GetLogger();
private static readonly object Lock = new object();
[STAThread]
public static void Main()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
// Create command line args parser.
var cmdLine = new ParagonCommandLineParser(Environment.GetCommandLineArgs());
/*
* Following statement is due to the Chromium bug: https://code.google.com/p/chromium/issues/detail?id=125614
* This statement can be removed once we know for sure that the issue has been fixed by Chrome.
* For now, we are disabling any system setting/command line setting for the TZ variable.
*/
Environment.SetEnvironmentVariable("TZ", null);
// Launch a debugger if a --debug flag was passed.
if (cmdLine.HasFlag("debug"))
{
Debugger.Launch();
}
// Extract app package.
ApplicationMetadata appMetadata;
IApplicationPackage appPackage;
if (!ApplicationManager.ResolveMetadataAndPackage(cmdLine, out appMetadata, out appPackage))
{
Environment.ExitCode = 1;
return;
}
try
{
_appManager = ApplicationManager.GetInstance();
//initialize logger earlier in the start up sequence
_appManager.InitializeLogger(Environment.ExpandEnvironmentVariables(Settings.Default.CacheDirectory), appPackage);
// Bail if the app is a singleton and an instance is already running. Cmd line args from
// this instance will be sent to the singleton isntance by the SingleInstance utility.
if (_appManager.RedirectApplicationLaunchIfNeeded(appPackage, appMetadata.Environment))
{
return;
}
// Initialize the app.
App app;
using (AutoStopwatch.TimeIt("Initializing Paragon.App"))
{
app = new App();
app.InitializeComponent();
app.Startup += delegate
{
_appManager.Initialize(
(name, version, iconStream) => new ParagonSplashScreen(name, version, iconStream),
(package, metadata, args) =>
{
var bootstrapper = new Bootstrapper();
var appFactory = bootstrapper.Resolve<ApplicationFactory>();
return appFactory.CreateApplication(metadata, package, args);
},
(args) =>
{
var query = HttpUtility.ParseQueryString(args);
return query.Keys.Cast<string>().ToDictionary<string, string, object>(key => key, key => query[key]);
},
Environment.ExpandEnvironmentVariables(Settings.Default.CacheDirectory),
true,
appPackage.Manifest.DisableSpellChecking
);
_appManager.AllApplicationsClosed += delegate
{
_appManager.Shutdown("All applications closed");
_appManager.ShutdownLogger();
app.Shutdown();
};
_appManager.RunApplication(cmdLine, appPackage, appMetadata);
};
}
// Run the app (this is a blocking call).
app.Run();
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Error launching application : {0}", ex.InnerException != null
? ex.InnerException.Message : ex.Message), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
Environment.ExitCode = 1;
MessageBoxResult result = MessageBox.Show("Critical error. Should collect log files?", "Error", MessageBoxButton.YesNo);
if (result == MessageBoxResult.Yes)
{
string errMessage = "";
try
{
String dstDiretory = ParagonLogManager.LogDirectory;
String fileName = "dump-file-" + DateTime.Now.ToString("dd_MM_yyyy_HH-mm-ss-fff") + ".zip";
String fullPath = Path.Combine(dstDiretory, fileName);
//Dump apps.
WebApplication runningApp = (WebApplication)_appManager.AllApplicaions.FirstOrDefault();
AppInfo appInfo = (AppInfo)runningApp.GetRunningApps().FirstOrDefault();
if (string.IsNullOrEmpty(fileName))
throw new ArgumentNullException("fileName", "Memory dump file name not provided.");
lock (Lock)
{
var browserFileName = string.Format("browser-{0}.dmp", appInfo.AppId);
var browserFilePath = Path.Combine(ParagonLogManager.LogDirectory, browserFileName);
MemoryDump.MiniDumpToFile(browserFilePath, Process.GetProcessById(appInfo.BrowserInfo.Pid), System.Runtime.InteropServices.Marshal.GetExceptionPointers());
var rendererFileName = string.Format("renderer-{0}.dmp", appInfo.AppId);
var rendererFilePath = Path.Combine(ParagonLogManager.LogDirectory, rendererFileName);
MemoryDump.MiniDumpToFile(rendererFilePath, Process.GetProcessById(appInfo.RenderInfo.Pid), System.Runtime.InteropServices.Marshal.GetExceptionPointers());
}
String packagePath = Path.Combine(dstDiretory, "package");
//delete temp directory. Ensure cleanup.
if (System.IO.Directory.Exists(packagePath))
System.IO.Directory.Delete(packagePath, true);
//Create temp directory
System.IO.Directory.CreateDirectory(packagePath);
//Copy files to temp directory to avoid denied access to files with open handler.
string[] fileEntries = Directory.GetFiles(dstDiretory);
System.Collections.Generic.List<string> files = fileEntries.ToList();
foreach (string file in fileEntries)
{
if (!file.EndsWith(".zip"))
{
File.Copy(file, Path.Combine(packagePath, Path.GetFileName(file)));
}
}
//Zip files.
fileEntries = Directory.GetFiles(packagePath);
AddFilesToZip(fullPath, fileEntries);
errMessage += string.Format("\n\nLog files and application dump files are zipped in:\n{0}.", fullPath);
}
catch (Exception ex1)
{
var logger = ParagonLogManager.GetLogger();
errMessage = string.Format("Failed to collect log files & dump running apps: {0}", ex1.ToString());
logger.Error(errMessage);
}
MessageBox.Show(errMessage, "Exception", MessageBoxButton.OK);
}
throw;
}
}
private static Dictionary<string, string> _contentTypesGiven = new Dictionary<string, string>();
private static void AddFilesToZip(string zipFilename, string[] fileEntries)
{
foreach (string fileToAdd in fileEntries)
{
using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
{
string destFilename = ".\\" + Path.GetFileName(fileToAdd);
Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
if (zip.PartExists(uri))
{
zip.DeletePart(uri);
}
PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
{
using (Stream dest = part.GetStream())
{
CopyStream(fileStream, dest);
}
}
}
}
}
private static void CopyStream(System.IO.FileStream inputStream, System.IO.Stream outputStream)
{
long BUFFER_SIZE = 4096;
long bufferSize = inputStream.Length < BUFFER_SIZE ? inputStream.Length : BUFFER_SIZE;
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
long bytesWritten = 0;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0)
{
outputStream.Write(buffer, 0, bytesRead);
bytesWritten += bufferSize;
}
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var logger = ParagonLogManager.GetLogger();
logger.Error(string.Format("An unhandled domain exception has occurred: {0}", e.ExceptionObject ?? string.Empty));
var errMessage = "A fatal error has occurred.";
if (_appManager != null && _appManager.AllApplicaions != null)
{
var apps = _appManager.AllApplicaions.Select(app => app.Name).ToArray();
if (apps.Length > 0)
{
errMessage += "\n\nThe following applications will be closed: \n " + string.Join(", ", apps);
}
}
errMessage += "\n\nPlease contact your internal helpdesk.\n";
MessageBox.Show(errMessage, "Unhandled Exception", MessageBoxButton.OK);
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
/// <summary>
/// Parameter Sets used for Azure Site Recovery commands.
/// </summary>
internal static class ASRParameterSets
{
/// <summary>
/// Add protected entities to RP
/// </summary>
internal const string AddProtectedEntities = "AddProtectedEntities";
/// <summary>
/// Add replication protected items to RP
/// </summary>
internal const string AddReplicationProtectedItems = "AddReplicationProtectedItems";
/// <summary>
/// To append group to RP.
/// </summary>
internal const string AppendGroup = "AppendGroup";
/// <summary>
/// Handle ARS Vault.
/// </summary>
internal const string ARSVault = "AzureRecoveryServicesVault";
/// </summary>
/// Handle ASR Vault.
/// </summary>
internal const string ASRVault = "AzureSiteRecoveryVault";
/// </summary>
/// Handle ASR Vault - Azure Fabric.
/// </summary>
internal const string Azure = "Azure";
/// </summary>
/// Handle ASR Vault - A2A Fabric.
/// </summary>
internal const string AzureToAzure = "AzureToAzure";
/// </summary>
/// Handle ASR Vault - A2A Fabric.
/// </summary>
internal const string AzureToAzureWithoutDiskDetails = "AzureToAzureWithoutDiskDetails";
/// </summary>
/// Handle ASR Vault - Paramset for A2a ManagedDisk.
/// </summary>
internal const string AzureToAzureManagedDisk = "AzureToAzureManagedDisk";
/// </summary>
/// Handle ASR Vault - A2A Fabric name.
/// </summary>
internal const string AzureToAzureWithFabricName = "AzureToAzureWithFabricName";
/// </summary>
/// Handle ASR Vault - A2A Fabric -AzureToAzureWithMultipleStorageAccount.
/// </summary>
internal const string AzureToAzureWithMultipleStorageAccount = "AzureToAzureWithMultipleStorageAccount";
/// </summary>
/// Handle ASR Vault.
/// </summary>
internal const string AzureToVMware = "AzureToVMware";
/// <summary>
/// When only Name is passed to the command.
/// </summary>
internal const string ByFabricObject = "ByFabricObject";
/// <summary>
/// When FabricId is passed to the command.
/// </summary>
internal const string ByFabricId = "ByFabricId";
/// <summary>
/// When only Name is passed to the command.
/// </summary>
internal const string ByFabricName = "ByFabricName";
/// <summary>
/// When only Name is passed to the command.
/// </summary>
internal const string ByFriendlyName = "ByFriendlyName";
/// <summary>
/// When only Friendly Name is passed to the command Legacy.
/// </summary>
internal const string ByFriendlyNameLegacy = "ByFriendlyNameLegacy";
/// <summary>
/// When only ID is passed to the command.
/// </summary>
internal const string ById = "ById";
/// <summary>
/// When group of IDs are passed to the command.
/// </summary>
internal const string ByIDs = "ByIDs";
/// <summary>
/// When group of IDs and ID are passed to the command.
/// </summary>
internal const string ByIDsWithId = "ByIDsWithId";
/// <summary>
/// When group of IDs and Name are passed to the command.
/// </summary>
internal const string ByIDsWithName = "ByIDsWithName";
/// <summary>
/// When only Name is passed to the command.
/// </summary>
internal const string ByName = "ByName";
/// <summary>
/// When only NetworkName Fabric is passed to the command.
/// </summary>
internal const string ByNetworkNameFabric = "ByNetworkNameFabric";
/// <summary>
/// When only NetworkName FabricName is passed to the command.
/// </summary>
internal const string ByNetworkNameFabricName = "ByNetworkNameFabricName";
/// <summary>
/// When only Name is passed to the command Legacy.
/// </summary>
internal const string ByNameLegacy = "ByNameLegacy";
/// <summary>
/// To define parameter set containing network object.
/// </summary>
internal const string ByNetworkObject = "ByNetworkObject";
/// <summary>
/// When only Object is passed to the command.
/// </summary>
internal const string ByObject = "ByObject";
/// <summary>
/// When Object and Name are passed to the command.
/// </summary>
internal const string ByObjectWithFriendlyName = "ByObjectWithFriendlyName";
/// <summary>
/// When Object and Name are passed to the command Legacy.
/// </summary>
internal const string ByObjectWithFriendlyNameLegacy = "ByObjectWithFriendlyNameLegacy";
/// <summary>
/// When Object and ID are passed to the command.
/// </summary>
internal const string ByObjectWithId = "ByObjectWithId";
/// <summary>
/// When Object and Name are passed to the command.
/// </summary>
internal const string ByObjectWithName = "ByObjectWithName";
/// <summary>
/// When Object and Name are passed to the command Legacy.
/// </summary>
internal const string ByObjectWithNameLegacy = "ByObjectWithNameLegacy";
/// <summary>
/// When parameters are passed to the command.
/// </summary>
internal const string ByParam = "ByParam";
/// <summary>
/// When only PC and PE ids are passed to the command.
/// </summary>
internal const string ByPEId = "ByPEId";
/// <summary>
/// When only PC and PE ids are passed along with logical network ID to the command.
/// </summary>
internal const string ByPEIdWithLogicalNetworkID = "ByPEIdWithLogicalNetworkID";
/// <summary>
/// When only PC and PE ids are passed along with VM network to the command.
/// </summary>
internal const string ByPEIdWithVMNetwork = "ByPEIdWithVMNetwork";
/// <summary>
/// When only PC and PE ids are passed along with VM network ID to the command.
/// </summary>
internal const string ByPEIdWithVMNetworkID = "ByPEIdWithVMNetworkID";
/// <summary>
/// When only PE Object is passed to the command.
/// </summary>
internal const string ByPEObject = "ByPEObject";
/// <summary>
/// When only PE Object with E2A provider is passed to the command.
/// </summary>
internal const string ByPEObjectE2A = "ByPEObjectE2A";
/// <summary>
/// When only PE Object with E2A provider is passed to the failback command.
/// </summary>
internal const string ByPEObjectE2AFailback = "ByPEObjectE2AFailback";
/// <summary>
/// When only PE Object is passed along with Logical VM network to the command.
/// </summary>
internal const string ByPEObjectWithAzureVMNetworkId = "ByPEObjectWithAzureVMNetworkId";
/// <summary>
/// When only PE Object is passed along with logical network ID to the command.
/// </summary>
internal const string ByPEObjectWithLogicalNetworkID = "ByPEObjectWithLogicalNetworkID";
/// <summary>
/// When only PE Object is passed along with Logical VM network to the command.
/// </summary>
internal const string ByPEObjectWithLogicalVMNetwork = "ByPEObjectWithLogicalVMNetwork";
/// <summary>
/// When only PE Object is passed along with VM network to the command.
/// </summary>
internal const string ByPEObjectWithVMNetwork = "ByPEObjectWithVMNetwork";
/// <summary>
/// When only PE Object is passed along with VM network ID to the command.
/// </summary>
internal const string ByPEObjectWithVMNetworkID = "ByPEObjectWithVMNetworkID";
/// <summary>
/// When Object and Name are passed to the command.
/// </summary>
internal const string ByProtectableItemObject = "ByProtectableItemObject";
/// <summary>
/// When only Name is ResourceId to the command.
/// </summary>
internal const string ByResourceId = "ByResourceId";
/// <summary>
/// When only RP File is passed to the command.
/// </summary>
internal const string ByRPFile = "ByRPFile";
/// <summary>
/// When only RP ID is passed to the command.
/// </summary>
internal const string ByRPId = "ByRPId";
/// <summary>
/// When only RP Id is passed along with logical network ID to the command.
/// </summary>
internal const string ByRPIdWithLogicalNetworkID = "ByRPIdWithLogicalNetworkID";
/// <summary>
/// When only RP Id is passed along with VM network to the command.
/// </summary>
internal const string ByRPIdWithVMNetwork = "ByRPIdWithVMNetwork";
/// <summary>
/// When only RP Id is passed along with VM network ID to the command.
/// </summary>
internal const string ByRPIdWithVMNetworkID = "ByRPIdWithVMNetworkID";
/// <summary>
/// When only RPI Object with RecoveryTag is passed to the command.currently used only in case on InMage.
/// </summary>
internal const string ByRPIObjectWithRecoveryTag = "ByRPIObjectWithRecoveryTag";
/// <summary>
/// When only RPI Object is passed to the command.
/// </summary>
internal const string ByRPIObject = "ByRPIObject";
/// <summary>
/// When only RPI Object is passed along with Logical VM network to the command.
/// </summary>
internal const string ByRPIObjectWithAzureVMNetworkId = "ByRPIObjectWithAzureVMNetworkId";
/// <summary>
/// When only RPI Object is passed along with Logical VM network to the command.
/// </summary>
internal const string ByRPIObjectWithAzureVMNetworkIdAndRecoveryTag = "ByRPIObjectWithAzureVMNetworkIdAndRecoveryTag";
/// <summary>
/// When only RPI Object is passed along with Logical VM network to the command.
/// </summary>
internal const string ByRPIObjectWithAzureVMNetworkIdAndRecoveryPoint = "ByRPIObjectWithAzureVMNetworkIdAndRecoveryPoint";
/// <summary>
/// When only RPI Object is passed along with Logical VM network to the command.
/// </summary>
internal const string ByRPIObjectWithLogicalVMNetwork = "ByRPIObjectWithLogicalVMNetwork";
/// <summary>
/// When only RPI Object is passed along with VM network to the command.
/// </summary>
internal const string ByRPIObjectWithVMNetwork = "ByRPIObjectWithVMNetwork";
/// <summary>
/// When only RPI Object is passed along with VM network to the command.
/// </summary>
internal const string ByRPIObjectWithVMNetworkAndRecoveryTag = "ByRPIObjectWithVMNetworkAndRecoveryTag";
/// <summary>
/// When only RPI Object is passed along with VM network to the command.
/// </summary>
internal const string ByRPIObjectWithVMNetworkAndRecoveryPoint = "ByRPIObjectWithVMNetworkAndRecoveryPoint";
/// <summary>
/// When only RP Object is passed to the command.
/// </summary>
internal const string ByRPObject = "ByRPObject";
/// <summary>
/// When only RP Object with E2A provider is passed to the command.
/// </summary>
internal const string ByRPObjectE2A = "ByRPObjectE2A";
/// <summary>
/// When only RP Object with E2A provider is passed to the failback command.
/// </summary>
internal const string ByRPObjectE2AFailback = "ByRPObjectE2AFailback";
/// <summary>
/// When only RP Object is passed along with Azure VM Network Id to the command.
/// </summary>
internal const string ByRPObjectWithAzureVMNetworkId = "ByRPObjectWithAzureVMNetworkId";
/// <summary>
/// When only RP Object is passed along with Azure VM Network Id to the command.
/// </summary>
internal const string ByRPObjectWithAzureVMNetworkIdAndRecoveryTag = "ByRPObjectWithAzureVMNetworkIdAndRecoveryTag";
/// <summary>
/// When only RP object is passed along with logical network ID to the command.
/// </summary>
internal const string ByRPObjectWithLogicalNetworkID = "ByRPObjectWithLogicalNetworkID";
/// <summary>
/// When only RP Object is passed along with VM network to the command.
/// </summary>
internal const string ByRPObjectWithVMNetwork = "ByRPObjectWithVMNetwork";
/// <summary>
/// When only RP Object is passed along with VM network to the command.
/// </summary>
internal const string ByRPObjectWithVMNetworkAndRecoveryTag = "ByRPObjectWithVMNetworkAndRecoveryTag";
/// <summary>
/// When only RP Object is passed along with VM network ID to the command.
/// </summary>
internal const string ByRPObjectWithVMNetworkID = "ByRPObjectWithVMNetworkID";
/// <summary>
/// When only Server Object is passed to the command.
/// </summary>
internal const string ByServerObject = "ByServerObject";
/// <summary>
/// When only Server Object is passed to the command.
/// </summary>
internal const string ByTime = "ByTime";
/// <summary>
/// When only Object type is passed to the command.
/// </summary>
internal const string ByType = "ByType";
/// <summary>
/// When nothing is passed to the command.
/// </summary>
internal const string Default = "Default";
/// <summary>
/// Disable
/// </summary>
internal const string Disable = "Disable";
/// <summary>
/// DisableEmailToSubcriptionOwner setAlertSettings.
/// </summary>
internal const string DisableEmailToSubcriptionOwner = "DisableEmailToSubcriptionOwner";
/// <summary>
/// Disable DR
/// </summary>
internal const string DisableDR = "DisableDR";
/// <summary>
/// For Disable replication group parameter set.
/// </summary>
internal const string DisableReplicationGroup = "DisableReplicationGroup";
/// <summary>
/// For Enable replication group parameter set.
/// </summary>
internal const string EnableReplicationGroup = "EnableReplicationGroup";
/// <summary>
/// Mapping between Enterprise to Azure.
/// </summary>
internal const string EnterpriseToAzure = "EnterpriseToAzure";
/// <summary>
/// Mapping between Enterprise to Azure.
/// </summary>
internal const string EnterpriseToAzureByName = "EnterpriseToAzureByName";
/// <summary>
/// Mapping between Enterprise to Azure Legacy.
/// </summary>
internal const string EnterpriseToAzureLegacy = "EnterpriseToAzureLegacy";
/// <summary>
/// Mapping between Enterprise to Enterprise.
/// </summary>
internal const string EnterpriseToEnterprise = "EnterpriseToEnterprise";
/// <summary>
/// Mapping between Enterprise to Enterprise.
/// </summary>
internal const string EnterpriseToEnterpriseByName = "EnterpriseToEnterpriseByName";
/// <summary>
/// Mapping between Enterprise to Enterprise Recovery Plan.
/// </summary>
internal const string EnterpriseToEnterpriseRP = "EnterpriseToEnterpriseRP";
/// <summary>
/// Mapping between Enterprise to Enterprise Legacy.
/// </summary>
internal const string EnterpriseToEnterpriseLegacy = "EnterpriseToEnterpriseLegacy";
/// <summary>
/// Mapping between Enterprise to Enterprise San.
/// </summary>
internal const string EnterpriseToEnterpriseSan = "EnterpriseToEnterpriseSan";
/// <summary>
/// EmailSubscriptionOwner SetAlert.
/// </summary>
internal const string EmailToSubscriptionOwner = "EmailToSubscriptionOwner";
/// <summary>
/// When only RP Object is passed to the command.
/// </summary>
internal const string ForSite = "ForSite";
/// <summary>
/// Mapping between HyperV Site to Azure.
/// </summary>
internal const string HyperVSiteToAzure = "HyperVSiteToAzure";
/// <summary>
/// Mapping between HyperV to Azure.
/// </summary>
internal const string HyperVToAzure = "HyperVToAzure";
/// <summary>
/// Mapping between HyperV Site to Azure Recovery Plan.
/// </summary>
internal const string HyperVSiteToAzureRP = "HyperVSiteToAzureRP";
/// <summary>
/// Mapping between HyperV to Azure Recovery Plan.
/// </summary>
internal const string HyperVToAzureRP = "HyperVToAzureRP";
/// <summary>
/// Mapping between HyperV Site to Azure Legacy.
/// </summary>
internal const string HyperVSiteToAzureLegacy = "HyperVSiteToAzureLegacy";
/// <summary>
/// To remove group from RP
/// </summary>
internal const string RemoveGroup = "RemoveGroup";
/// <summary>
/// Remove protected entities from RP
/// </summary>
internal const string RemoveProtectedEntities = "RemoveProtectedEntities";
/// <summary>
/// Remove replication protected items from RP
/// </summary>
internal const string RemoveReplicationProtectedItems = "RemoveReplicationProtectedItems";
/// <summary>
/// Set alerts to send to owners.
/// </summary>
internal const string SendToOwners = "SendToOwners";
/// <summary>
/// Set alerts to send to owners.
/// </summary>
internal const string Set = "Set";
/// <summary>
/// Set email addresses.
/// </summary>
internal const string SetEmail = "SetEmail";
/// <summary>
/// Mapping for VMware to Azure.
/// </summary>
internal const string VMwareToAzure = "VMwareToAzure";
/// <summary>
/// Mapping for both VMware to Azure and VMware to VMware.
/// </summary>
internal const string VMwareToAzureAndVMwareToVMware = "VMwareToAzureAndVMwareToVMware";
/// <summary>
/// Mapping for both VMware to Azure and VMware to VMware for RP.
/// </summary>
internal const string VMwareToAzureAndVMwareToVMwareRP = "VMwareToAzureAndVMwareToVMwareRP";
/// <summary>
/// Mapping for both VMware to Azure and VMware to VMware for RPI.
/// </summary>
internal const string VMwareToAzureAndVMwareToVMwareRPI =
"VMwareToAzureAndVMwareToVMwareRPI";
/// <summary>
/// Mapping for VMware to Azure for RP.
/// </summary>
internal const string VMwareToAzureRP = "VMwareToAzureRP";
/// <summary>
/// Mapping for VMware to Azure for RPI.
/// </summary>
internal const string VMwareToAzureRPI = "VMwareToAzureRPI";
/// <summary>
/// Mapping for VMware to VMware.
/// </summary>
internal const string VMWareToVMWare = "VMWareToVMWare";
/// <summary>
/// Mapping for VMware to VMware for RPI.
/// </summary>
internal const string VMwareToVMwareRPI = "VMwareToVMwareRPI";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.