context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Dalssoft.DiagramNet
{
/// <summary>
/// This class control the size of elements
/// </summary>
internal class ResizeAction
{
public delegate void OnElementResizingDelegate(ElementEventArgs e);
private OnElementResizingDelegate onElementResizingDelegate;
private bool isResizing = false;
private IResizeController resizeCtrl = null;
private Document document = null;
public ResizeAction()
{
}
public bool IsResizing
{
get
{
return isResizing;
}
}
public bool IsResizingLink
{
get
{
return ((resizeCtrl != null) && (resizeCtrl.OwnerElement is BaseLinkElement));
}
}
public void Select(Document document)
{
this.document = document;
// Get Resize Controller
if ((document.SelectedElements.Count == 1) && (document.SelectedElements[0] is IControllable))
{
IController ctrl = ((IControllable) document.SelectedElements[0]).GetController();
if (ctrl is IResizeController)
{
ctrl.OwnerElement.Invalidate();
resizeCtrl = (IResizeController) ctrl;
ShowResizeCorner(true);
}
}
else
resizeCtrl = null;
}
public void Start(Point mousePoint, OnElementResizingDelegate onElementResizingDelegate)
{
isResizing = false;
if (resizeCtrl == null) return;
this.onElementResizingDelegate = onElementResizingDelegate;
resizeCtrl.OwnerElement.Invalidate();
CornerPosition corPos = resizeCtrl.HitTestCorner(mousePoint);
if (corPos != CornerPosition.Nothing)
{
//Events
ElementEventArgs eventResizeArg = new ElementEventArgs(resizeCtrl.OwnerElement);
onElementResizingDelegate(eventResizeArg);
resizeCtrl.Start(mousePoint, corPos);
UpdateResizeCorner();
isResizing = true;
}
}
public void Resize(Point dragPoint)
{
if ((resizeCtrl != null) && (resizeCtrl.CanResize))
{
//Events
ElementEventArgs eventResizeArg = new ElementEventArgs(resizeCtrl.OwnerElement);
onElementResizingDelegate(eventResizeArg);
resizeCtrl.OwnerElement.Invalidate();
resizeCtrl.Resize(dragPoint);
ILabelController lblCtrl = ControllerHelper.GetLabelController(resizeCtrl.OwnerElement);
if (lblCtrl != null)
lblCtrl.SetLabelPosition();
else
{
if (resizeCtrl.OwnerElement is ILabelElement)
{
LabelElement label = ((ILabelElement) resizeCtrl.OwnerElement).Label;
label.PositionBySite(resizeCtrl.OwnerElement);
}
}
UpdateResizeCorner();
}
}
public void End(Point posEnd)
{
if (resizeCtrl != null)
{
resizeCtrl.OwnerElement.Invalidate();
resizeCtrl.End(posEnd);
//Events
ElementEventArgs eventResizeArg = new ElementEventArgs(resizeCtrl.OwnerElement);
onElementResizingDelegate(eventResizeArg);
isResizing = false;
}
}
public void DrawResizeCorner(Graphics g)
{
if (resizeCtrl != null)
{
foreach(RectangleElement r in resizeCtrl.Corners)
{
if (document.Action == DesignerAction.Select)
{
if (r.Visible) r.Draw(g);
}
else if (document.Action == DesignerAction.Connect)
{
// if is Connect Mode, then resize only Links.
if (resizeCtrl.OwnerElement is BaseLinkElement)
if (r.Visible) r.Draw(g);
}
}
}
}
public void UpdateResizeCorner()
{
if (resizeCtrl != null)
resizeCtrl.UpdateCornersPos();
}
public Cursor UpdateResizeCornerCursor(Point mousePoint)
{
if ((resizeCtrl == null) || (!resizeCtrl.CanResize)) return Cursors.Default;
CornerPosition corPos = resizeCtrl.HitTestCorner(mousePoint);
switch(corPos)
{
case CornerPosition.TopLeft:
return Cursors.SizeNWSE;
case CornerPosition.TopCenter:
return Cursors.SizeNS;
case CornerPosition.TopRight:
return Cursors.SizeNESW;
case CornerPosition.MiddleLeft:
case CornerPosition.MiddleRight:
return Cursors.SizeWE;
case CornerPosition.BottomLeft:
return Cursors.SizeNESW;
case CornerPosition.BottomCenter:
return Cursors.SizeNS;
case CornerPosition.BottomRight:
return Cursors.SizeNWSE;
default:
return Cursors.Default;
}
}
public void ShowResizeCorner(bool show)
{
if (resizeCtrl != null)
{
bool canResize = resizeCtrl.CanResize;
for(int i = 0; i < resizeCtrl.Corners.Length; i++)
{
if (canResize)
resizeCtrl.Corners[i].Visible = show;
else
resizeCtrl.Corners[i].Visible = false;
}
if (resizeCtrl.Corners.Length >= (int) CornerPosition.MiddleCenter)
resizeCtrl.Corners[(int) CornerPosition.MiddleCenter].Visible = false;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using ParquetSharp.Column;
using ParquetSharp.Column.Statistics;
using ParquetSharp.External;
using ParquetSharp.Hadoop.Metadata;
using ParquetSharp.Hadoop.Util;
using ParquetSharp.Schema;
using static ParquetSharp.Hadoop.ParquetFileWriter;
namespace ParquetSharp.Hadoop
{
/**
* Utility to print footer information
* @author Julien Le Dem
*
*/
public class PrintFooter
{
public static void Main(string[] args)
{
if (args.Length != 1)
{
System.Console.WriteLine("usage PrintFooter <path>");
return;
}
Path path = new Path(new Uri(args[0]).AbsolutePath);
Configuration configuration = new Configuration();
FileSystem fs = path.getFileSystem(configuration);
FileStatus fileStatus = fs.getFileStatus(path);
Path summary = new Path(fileStatus.getPath(), PARQUET_METADATA_FILE);
if (fileStatus.isDir() && fs.exists(summary))
{
System.Console.WriteLine("reading summary file");
FileStatus summaryStatus = fs.getFileStatus(summary);
List<Footer> readSummaryFile = ParquetFileReader.readSummaryFile(configuration, summaryStatus);
foreach (Footer footer in readSummaryFile)
{
add(footer.getParquetMetadata());
}
}
else {
List<FileStatus> statuses;
if (fileStatus.isDir())
{
System.Console.WriteLine("listing files in " + fileStatus.getPath());
statuses = Arrays.asList(fs.listStatus(fileStatus.getPath(), HiddenFileFilter.INSTANCE));
}
else {
statuses = new List<FileStatus>();
statuses.Add(fileStatus);
}
System.Console.WriteLine("opening " + statuses.Count + " files");
int i = 0;
ExecutorService threadPool = Executors.newFixedThreadPool(5);
try
{
long t0 = Epoch.currentTimeMillis();
Deque<Future<ParquetMetadata>> footers = new LinkedBlockingDeque<Future<ParquetMetadata>>();
foreach (FileStatus currentFile in statuses)
{
footers.add(threadPool.submit(() =>
{
try
{
ParquetMetadata footer = ParquetFileReader.readFooter(configuration, currentFile, NO_FILTER);
return footer;
}
catch (Exception e)
{
throw new ParquetDecodingException("could not read footer", e);
}
}));
}
int previousPercent = 0;
int n = 60;
System.Console.Write("0% [");
for (int j = 0; j < n; j++)
{
System.Console.Write(" ");
}
System.Console.Write("] 100%");
for (int j = 0; j < n + 6; j++)
{
System.Console.Write('\b');
}
while (!footers.isEmpty())
{
Future<ParquetMetadata> futureFooter = footers.removeFirst();
if (!futureFooter.isDone())
{
footers.addLast(futureFooter);
continue;
}
ParquetMetadata footer = futureFooter.get();
int currentPercent = (++i * n / statuses.size());
while (currentPercent > previousPercent)
{
System.Console.Write("*");
previousPercent++;
}
add(footer);
}
System.Console.WriteLine("");
long t1 = Epoch.currentTimeMillis();
System.Console.WriteLine("read all footers in " + (t1 - t0) + " ms");
}
finally
{
threadPool.shutdownNow();
}
}
long total = 0;
long totalUnc = 0;
foreach (KeyValuePair<ColumnDescriptor, ColStats> entry in stats)
{
ColStats colStats = entry.Value;
total += colStats.allStats.total;
totalUnc += colStats.uncStats.total;
}
foreach (KeyValuePair<ColumnDescriptor, ColStats> entry in stats)
{
ColStats colStats = entry.Value;
System.Console.WriteLine(entry.Key + " " + percent(colStats.allStats.total, total) + "% of all space " + colStats);
}
System.Console.WriteLine("number of blocks: " + blockCount);
System.Console.WriteLine("total data size: " + humanReadable(total) + " (raw " + humanReadable(totalUnc) + ")");
System.Console.WriteLine("total record: " + humanReadable(recordCount));
System.Console.WriteLine("average block size: " + humanReadable(total / blockCount) + " (raw " + humanReadable(totalUnc / blockCount) + ")");
System.Console.WriteLine("average record count: " + humanReadable(recordCount / blockCount));
}
private static void add(ParquetMetadata footer)
{
foreach (BlockMetaData blockMetaData in footer.getBlocks())
{
++blockCount;
MessageType schema = footer.getFileMetaData().getSchema();
recordCount += blockMetaData.getRowCount();
foreach (ColumnChunkMetaData columnMetaData in blockMetaData.getColumns())
{
ColumnDescriptor desc = schema.getColumnDescription(columnMetaData.getPath().toArray());
add(
desc,
columnMetaData.getValueCount(),
columnMetaData.getTotalSize(),
columnMetaData.getTotalUncompressedSize(),
columnMetaData.getEncodings(),
columnMetaData.getStatistics());
}
}
}
private static void printTotalString(string message, long total, long totalUnc)
{
System.Console.WriteLine("total " + message + ": " + humanReadable(total) + " (raw " + humanReadable(totalUnc) + " saved " + percentComp(totalUnc, total) + "%)");
}
private static float percentComp(long raw, long compressed)
{
return percent(raw - compressed, raw);
}
private static float percent(long numerator, long denominator)
{
return ((float)((numerator) * 1000 / denominator)) / 10;
}
private static string humanReadable(long size)
{
if (size < 1000)
{
return size.ToString(CultureInfo.InvariantCulture);
}
long currentSize = size;
long previousSize = size * 1000;
int count = 0;
string[] unit = { "", "K", "M", "G", "T", "P" };
while (currentSize >= 1000)
{
previousSize = currentSize;
currentSize = currentSize / 1000;
++count;
}
return ((float)previousSize / 1000) + unit[count];
}
private static Dictionary<ColumnDescriptor, ColStats> stats = new LinkedDictionary<ColumnDescriptor, ColStats>();
private static int blockCount = 0;
private static long recordCount = 0;
private class Stats
{
internal long min = long.MaxValue;
internal long max = long.MinValue;
internal long total = 0;
public void add(long length)
{
min = Math.Min(length, min);
max = Math.Max(length, max);
total += length;
}
public string toString(int blocks)
{
return
"min: " + humanReadable(min) +
" max: " + humanReadable(max) +
" average: " + humanReadable(total / blocks) +
" total: " + humanReadable(total);
}
}
private class ColStats
{
Stats valueCountStats = new Stats();
Stats allStats = new Stats();
Stats uncStats = new Stats();
HashSet<Encoding> encodings = new HashSet<Encoding>();
Statistics colValuesStats = null;
int blocks = 0;
public void add(long valueCount, long size, long uncSize, IEnumerable<Encoding> encodings, Statistics colValuesStats)
{
++blocks;
valueCountStats.add(valueCount);
allStats.add(size);
uncStats.add(uncSize);
this.encodings.UnionWith(encodings);
this.colValuesStats = colValuesStats;
}
public override string ToString()
{
long raw = uncStats.total;
long compressed = allStats.total;
return encodings + " " + allStats.toString(blocks) + " (raw data: " + humanReadable(raw) + (raw == 0 ? "" : " saving " + (raw - compressed) * 100 / raw + "%") + ")\n"
+ " values: " + valueCountStats.toString(blocks) + "\n"
+ " uncompressed: " + uncStats.toString(blocks) + "\n"
+ " column values statistics: " + colValuesStats.ToString();
}
}
private static void add(ColumnDescriptor desc, long valueCount, long size, long uncSize, IEnumerable<Encoding> encodings, Statistics colValuesStats)
{
ColStats colStats;
if (!stats.TryGetValue(desc, out colStats))
{
colStats = new ColStats();
stats.Add(desc, colStats);
}
colStats.add(valueCount, size, uncSize, encodings, colValuesStats);
}
}
}
| |
using System.Collections.Generic;
using Eto.Forms;
#if XAMMAC2
using AppKit;
using Foundation;
using CoreGraphics;
using ObjCRuntime;
using CoreAnimation;
using CoreImage;
#else
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using MonoMac.ObjCRuntime;
using MonoMac.CoreAnimation;
using MonoMac.CoreImage;
#if Mac64
using CGSize = MonoMac.Foundation.NSSize;
using CGRect = MonoMac.Foundation.NSRect;
using CGPoint = MonoMac.Foundation.NSPoint;
using nfloat = System.Double;
using nint = System.Int64;
using nuint = System.UInt64;
#else
using CGSize = System.Drawing.SizeF;
using CGRect = System.Drawing.RectangleF;
using CGPoint = System.Drawing.PointF;
using nfloat = System.Single;
using nint = System.Int32;
using nuint = System.UInt32;
#endif
#endif
namespace Eto.Mac
{
public static class KeyMap
{
static readonly Dictionary<ushort, Keys> keymap = new Dictionary<ushort, Keys>();
static readonly Dictionary<Keys, string> inverse = new Dictionary<Keys, string>();
public static Keys MapKey(ushort key)
{
Keys value;
return keymap.TryGetValue(key, out value) ? value : Keys.None;
}
enum KeyCharacters
{
NSParagraphSeparatorCharacter = 0x2029,
NSLineSeparatorCharacter = 0x2028,
NSTabCharacter = 0x0009,
NSFormFeedCharacter = 0x000c,
NSNewlineCharacter = 0x000a,
NSCarriageReturnCharacter = 0x000d,
NSEnterCharacter = 0x0003,
NSBackspaceCharacter = 0x0008,
NSBackTabCharacter = 0x0019,
NSDeleteCharacter = 0x007f
}
public static Keys Convert(string keyEquivalent, NSEventModifierMask modifier)
{
return Keys.None;
}
public static string KeyEquivalent(Keys key)
{
string value;
return inverse.TryGetValue(key & Keys.KeyMask, out value) ? value : string.Empty;
}
public static NSEventModifierMask KeyEquivalentModifierMask(this Keys key)
{
key &= Keys.ModifierMask;
var mask = (NSEventModifierMask)0;
if (key.HasFlag(Keys.Shift))
mask |= NSEventModifierMask.ShiftKeyMask;
if (key.HasFlag(Keys.Alt))
mask |= NSEventModifierMask.AlternateKeyMask;
if (key.HasFlag(Keys.Control))
mask |= NSEventModifierMask.ControlKeyMask;
if (key.HasFlag(Keys.Application))
mask |= NSEventModifierMask.CommandKeyMask;
if (key == Keys.CapsLock)
mask |= NSEventModifierMask.AlphaShiftKeyMask;
if (key == Keys.NumberLock)
mask |= NSEventModifierMask.NumericPadKeyMask;
return mask;
}
public static NSEventModifierMask ModifierMask(this Keys key)
{
var mask = KeyEquivalentModifierMask(key);
if (key == Keys.CapsLock)
mask |= NSEventModifierMask.AlphaShiftKeyMask;
if (key == Keys.NumberLock)
mask |= NSEventModifierMask.NumericPadKeyMask;
return mask;
}
public static Keys ToEto(this NSEventModifierMask mask)
{
Keys key = Keys.None;
if (mask.HasFlag(NSEventModifierMask.ControlKeyMask))
key |= Keys.Control;
if (mask.HasFlag(NSEventModifierMask.CommandKeyMask))
key |= Keys.Application;
if (mask.HasFlag(NSEventModifierMask.ShiftKeyMask))
key |= Keys.Shift;
if (mask.HasFlag(NSEventModifierMask.AlternateKeyMask))
key |= Keys.Alt;
return key;
}
static KeyMap()
{
keymap.Add(0, Keys.A);
keymap.Add(11, Keys.B);
keymap.Add(8, Keys.C);
keymap.Add(2, Keys.D);
keymap.Add(14, Keys.E);
keymap.Add(3, Keys.F);
keymap.Add(5, Keys.G);
keymap.Add(4, Keys.H);
keymap.Add(34, Keys.I);
keymap.Add(38, Keys.J);
keymap.Add(40, Keys.K);
keymap.Add(37, Keys.L);
keymap.Add(46, Keys.M);
keymap.Add(45, Keys.N);
keymap.Add(31, Keys.O);
keymap.Add(35, Keys.P);
keymap.Add(12, Keys.Q);
keymap.Add(15, Keys.R);
keymap.Add(1, Keys.S);
keymap.Add(17, Keys.T);
keymap.Add(32, Keys.U);
keymap.Add(9, Keys.V);
keymap.Add(13, Keys.W);
keymap.Add(7, Keys.X);
keymap.Add(16, Keys.Y);
keymap.Add(6, Keys.Z);
keymap.Add(18, Keys.D1);
keymap.Add(19, Keys.D2);
keymap.Add(20, Keys.D3);
keymap.Add(21, Keys.D4);
keymap.Add(23, Keys.D5);
keymap.Add(22, Keys.D6);
keymap.Add(26, Keys.D7);
keymap.Add(28, Keys.D8);
keymap.Add(25, Keys.D9);
keymap.Add(29, Keys.D0);
keymap.Add(122, Keys.F1);
keymap.Add(120, Keys.F2);
keymap.Add(99, Keys.F3);
keymap.Add(118, Keys.F4);
keymap.Add(96, Keys.F5);
keymap.Add(97, Keys.F6);
keymap.Add(98, Keys.F7);
keymap.Add(100, Keys.F8);
keymap.Add(101, Keys.F9);
keymap.Add(109, Keys.F10);
keymap.Add(103, Keys.F11);
keymap.Add(111, Keys.F12);
keymap.Add(50, Keys.Grave);
keymap.Add(27, Keys.Minus);
keymap.Add(24, Keys.Equal);
keymap.Add(42, Keys.Backslash);
keymap.Add(49, Keys.Space);
//keymap.Add(30, Keys.]);
//keymap.Add(33, Keys.[);
keymap.Add(39, Keys.Quote);
keymap.Add(41, Keys.Semicolon);
keymap.Add(44, Keys.ForwardSlash);
keymap.Add(47, Keys.Period);
keymap.Add(43, Keys.Comma);
keymap.Add(36, Keys.Enter);
keymap.Add(48, Keys.Tab);
//keymap.Add(76, Keys.Return);
keymap.Add(53, Keys.Escape);
keymap.Add(76, Keys.Insert);
keymap.Add(51, Keys.Backspace);
keymap.Add(117, Keys.Delete);
keymap.Add(125, Keys.Down);
keymap.Add(126, Keys.Up);
keymap.Add(123, Keys.Left);
keymap.Add(124, Keys.Right);
keymap.Add(116, Keys.PageUp);
keymap.Add(121, Keys.PageDown);
keymap.Add(119, Keys.End);
keymap.Add(115, Keys.Home);
keymap.Add(110, Keys.ContextMenu);
inverse.Add(Keys.A, "a");
inverse.Add(Keys.B, "b");
inverse.Add(Keys.C, "c");
inverse.Add(Keys.D, "d");
inverse.Add(Keys.E, "e");
inverse.Add(Keys.F, "f");
inverse.Add(Keys.G, "g");
inverse.Add(Keys.H, "h");
inverse.Add(Keys.I, "i");
inverse.Add(Keys.J, "j");
inverse.Add(Keys.K, "k");
inverse.Add(Keys.L, "l");
inverse.Add(Keys.M, "m");
inverse.Add(Keys.N, "n");
inverse.Add(Keys.O, "o");
inverse.Add(Keys.P, "p");
inverse.Add(Keys.Q, "q");
inverse.Add(Keys.R, "r");
inverse.Add(Keys.S, "s");
inverse.Add(Keys.T, "t");
inverse.Add(Keys.U, "u");
inverse.Add(Keys.V, "v");
inverse.Add(Keys.W, "w");
inverse.Add(Keys.X, "x");
inverse.Add(Keys.Y, "y");
inverse.Add(Keys.Z, "z");
inverse.Add(Keys.Period, ".");
inverse.Add(Keys.Comma, ",");
inverse.Add(Keys.Space, " ");
inverse.Add(Keys.Backslash, "\\");
inverse.Add(Keys.ForwardSlash, "/");
inverse.Add(Keys.Equal, "=");
inverse.Add(Keys.Grave, "`");
inverse.Add(Keys.Minus, "-");
inverse.Add(Keys.Semicolon, ";");
inverse.Add(Keys.Up, ((char)NSKey.UpArrow).ToString());
inverse.Add(Keys.Down, ((char)NSKey.DownArrow).ToString());
inverse.Add(Keys.Right, ((char)NSKey.RightArrow).ToString());
inverse.Add(Keys.Left, ((char)NSKey.LeftArrow).ToString());
inverse.Add(Keys.Home, ((char)NSKey.Home).ToString());
inverse.Add(Keys.End, ((char)NSKey.End).ToString());
#if !__UNIFIED__
inverse.Add(Keys.Insert, ((char)NSKey.Insert).ToString());
#endif
inverse.Add(Keys.Delete, ((char)KeyCharacters.NSDeleteCharacter).ToString());
inverse.Add(Keys.Backspace, ((char)KeyCharacters.NSBackspaceCharacter).ToString());
inverse.Add(Keys.Tab, ((char)KeyCharacters.NSTabCharacter).ToString());
inverse.Add(Keys.D0, "0");
inverse.Add(Keys.D1, "1");
inverse.Add(Keys.D2, "2");
inverse.Add(Keys.D3, "3");
inverse.Add(Keys.D4, "4");
inverse.Add(Keys.D5, "5");
inverse.Add(Keys.D6, "6");
inverse.Add(Keys.D7, "7");
inverse.Add(Keys.D8, "8");
inverse.Add(Keys.D9, "9");
inverse.Add(Keys.F1, ((char)NSKey.F1).ToString());
inverse.Add(Keys.F2, ((char)NSKey.F2).ToString());
inverse.Add(Keys.F3, ((char)NSKey.F3).ToString());
inverse.Add(Keys.F4, ((char)NSKey.F4).ToString());
inverse.Add(Keys.F5, ((char)NSKey.F5).ToString());
inverse.Add(Keys.F6, ((char)NSKey.F6).ToString());
inverse.Add(Keys.F7, ((char)NSKey.F7).ToString());
inverse.Add(Keys.F8, ((char)NSKey.F8).ToString());
inverse.Add(Keys.F9, ((char)NSKey.F9).ToString());
inverse.Add(Keys.F10, ((char)NSKey.F10).ToString());
inverse.Add(Keys.F11, ((char)NSKey.F11).ToString());
inverse.Add(Keys.F12, ((char)NSKey.F12).ToString());
}
}
}
| |
// 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 Microsoft.Azure.Batch.Protocol
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for JobScheduleOperations.
/// </summary>
public static partial class JobScheduleOperationsExtensions
{
/// <summary>
/// Checks the specified job schedule exists.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule which you want to check.
/// </param>
/// <param name='jobScheduleExistsOptions'>
/// Additional parameters for the operation
/// </param>
public static bool Exists(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleExistsOptions jobScheduleExistsOptions = default(JobScheduleExistsOptions))
{
return ((IJobScheduleOperations)operations).ExistsAsync(jobScheduleId, jobScheduleExistsOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Checks the specified job schedule exists.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule which you want to check.
/// </param>
/// <param name='jobScheduleExistsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<bool> ExistsAsync(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleExistsOptions jobScheduleExistsOptions = default(JobScheduleExistsOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ExistsWithHttpMessagesAsync(jobScheduleId, jobScheduleExistsOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a job schedule from the specified account.
/// </summary>
/// <remarks>
/// When you delete a job schedule, this also deletes all jobs and tasks under
/// that schedule. When tasks are deleted, all the files in their working
/// directories on the compute nodes are also deleted (the retention period is
/// ignored). The job schedule statistics are no longer accessible once the job
/// schedule is deleted, though they are still counted towards account lifetime
/// statistics.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule to delete.
/// </param>
/// <param name='jobScheduleDeleteOptions'>
/// Additional parameters for the operation
/// </param>
public static JobScheduleDeleteHeaders Delete(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleDeleteOptions jobScheduleDeleteOptions = default(JobScheduleDeleteOptions))
{
return ((IJobScheduleOperations)operations).DeleteAsync(jobScheduleId, jobScheduleDeleteOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a job schedule from the specified account.
/// </summary>
/// <remarks>
/// When you delete a job schedule, this also deletes all jobs and tasks under
/// that schedule. When tasks are deleted, all the files in their working
/// directories on the compute nodes are also deleted (the retention period is
/// ignored). The job schedule statistics are no longer accessible once the job
/// schedule is deleted, though they are still counted towards account lifetime
/// statistics.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule to delete.
/// </param>
/// <param name='jobScheduleDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<JobScheduleDeleteHeaders> DeleteAsync(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleDeleteOptions jobScheduleDeleteOptions = default(JobScheduleDeleteOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(jobScheduleId, jobScheduleDeleteOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Gets information about the specified job schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule to get.
/// </param>
/// <param name='jobScheduleGetOptions'>
/// Additional parameters for the operation
/// </param>
public static CloudJobSchedule Get(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleGetOptions jobScheduleGetOptions = default(JobScheduleGetOptions))
{
return ((IJobScheduleOperations)operations).GetAsync(jobScheduleId, jobScheduleGetOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the specified job schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule to get.
/// </param>
/// <param name='jobScheduleGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CloudJobSchedule> GetAsync(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleGetOptions jobScheduleGetOptions = default(JobScheduleGetOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(jobScheduleId, jobScheduleGetOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the properties of the specified job schedule.
/// </summary>
/// <remarks>
/// This replaces only the job schedule properties specified in the request.
/// For example, if the schedule property is not specified with this request,
/// then the Batch service will keep the existing schedule. Changes to a job
/// schedule only impact jobs created by the schedule after the update has
/// taken place; currently running jobs are unaffected.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule to update.
/// </param>
/// <param name='jobSchedulePatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobSchedulePatchOptions'>
/// Additional parameters for the operation
/// </param>
public static JobSchedulePatchHeaders Patch(this IJobScheduleOperations operations, string jobScheduleId, JobSchedulePatchParameter jobSchedulePatchParameter, JobSchedulePatchOptions jobSchedulePatchOptions = default(JobSchedulePatchOptions))
{
return ((IJobScheduleOperations)operations).PatchAsync(jobScheduleId, jobSchedulePatchParameter, jobSchedulePatchOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the properties of the specified job schedule.
/// </summary>
/// <remarks>
/// This replaces only the job schedule properties specified in the request.
/// For example, if the schedule property is not specified with this request,
/// then the Batch service will keep the existing schedule. Changes to a job
/// schedule only impact jobs created by the schedule after the update has
/// taken place; currently running jobs are unaffected.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule to update.
/// </param>
/// <param name='jobSchedulePatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobSchedulePatchOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<JobSchedulePatchHeaders> PatchAsync(this IJobScheduleOperations operations, string jobScheduleId, JobSchedulePatchParameter jobSchedulePatchParameter, JobSchedulePatchOptions jobSchedulePatchOptions = default(JobSchedulePatchOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.PatchWithHttpMessagesAsync(jobScheduleId, jobSchedulePatchParameter, jobSchedulePatchOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Updates the properties of the specified job schedule.
/// </summary>
/// <remarks>
/// This fully replaces all the updateable properties of the job schedule. For
/// example, if the schedule property is not specified with this request, then
/// the Batch service will remove the existing schedule. Changes to a job
/// schedule only impact jobs created by the schedule after the update has
/// taken place; currently running jobs are unaffected.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule to update.
/// </param>
/// <param name='jobScheduleUpdateParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobScheduleUpdateOptions'>
/// Additional parameters for the operation
/// </param>
public static JobScheduleUpdateHeaders Update(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleUpdateParameter jobScheduleUpdateParameter, JobScheduleUpdateOptions jobScheduleUpdateOptions = default(JobScheduleUpdateOptions))
{
return ((IJobScheduleOperations)operations).UpdateAsync(jobScheduleId, jobScheduleUpdateParameter, jobScheduleUpdateOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the properties of the specified job schedule.
/// </summary>
/// <remarks>
/// This fully replaces all the updateable properties of the job schedule. For
/// example, if the schedule property is not specified with this request, then
/// the Batch service will remove the existing schedule. Changes to a job
/// schedule only impact jobs created by the schedule after the update has
/// taken place; currently running jobs are unaffected.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule to update.
/// </param>
/// <param name='jobScheduleUpdateParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobScheduleUpdateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<JobScheduleUpdateHeaders> UpdateAsync(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleUpdateParameter jobScheduleUpdateParameter, JobScheduleUpdateOptions jobScheduleUpdateOptions = default(JobScheduleUpdateOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(jobScheduleId, jobScheduleUpdateParameter, jobScheduleUpdateOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Disables a job schedule.
/// </summary>
/// <remarks>
/// No new jobs will be created until the job schedule is enabled again.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule to disable.
/// </param>
/// <param name='jobScheduleDisableOptions'>
/// Additional parameters for the operation
/// </param>
public static JobScheduleDisableHeaders Disable(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleDisableOptions jobScheduleDisableOptions = default(JobScheduleDisableOptions))
{
return ((IJobScheduleOperations)operations).DisableAsync(jobScheduleId, jobScheduleDisableOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Disables a job schedule.
/// </summary>
/// <remarks>
/// No new jobs will be created until the job schedule is enabled again.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule to disable.
/// </param>
/// <param name='jobScheduleDisableOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<JobScheduleDisableHeaders> DisableAsync(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleDisableOptions jobScheduleDisableOptions = default(JobScheduleDisableOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.DisableWithHttpMessagesAsync(jobScheduleId, jobScheduleDisableOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Enables a job schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule to enable.
/// </param>
/// <param name='jobScheduleEnableOptions'>
/// Additional parameters for the operation
/// </param>
public static JobScheduleEnableHeaders Enable(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleEnableOptions jobScheduleEnableOptions = default(JobScheduleEnableOptions))
{
return ((IJobScheduleOperations)operations).EnableAsync(jobScheduleId, jobScheduleEnableOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Enables a job schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule to enable.
/// </param>
/// <param name='jobScheduleEnableOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<JobScheduleEnableHeaders> EnableAsync(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleEnableOptions jobScheduleEnableOptions = default(JobScheduleEnableOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.EnableWithHttpMessagesAsync(jobScheduleId, jobScheduleEnableOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Terminates a job schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule to terminates.
/// </param>
/// <param name='jobScheduleTerminateOptions'>
/// Additional parameters for the operation
/// </param>
public static JobScheduleTerminateHeaders Terminate(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleTerminateOptions jobScheduleTerminateOptions = default(JobScheduleTerminateOptions))
{
return ((IJobScheduleOperations)operations).TerminateAsync(jobScheduleId, jobScheduleTerminateOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Terminates a job schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule to terminates.
/// </param>
/// <param name='jobScheduleTerminateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<JobScheduleTerminateHeaders> TerminateAsync(this IJobScheduleOperations operations, string jobScheduleId, JobScheduleTerminateOptions jobScheduleTerminateOptions = default(JobScheduleTerminateOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.TerminateWithHttpMessagesAsync(jobScheduleId, jobScheduleTerminateOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Adds a job schedule to the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cloudJobSchedule'>
/// The job schedule to be added.
/// </param>
/// <param name='jobScheduleAddOptions'>
/// Additional parameters for the operation
/// </param>
public static JobScheduleAddHeaders Add(this IJobScheduleOperations operations, JobScheduleAddParameter cloudJobSchedule, JobScheduleAddOptions jobScheduleAddOptions = default(JobScheduleAddOptions))
{
return ((IJobScheduleOperations)operations).AddAsync(cloudJobSchedule, jobScheduleAddOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Adds a job schedule to the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cloudJobSchedule'>
/// The job schedule to be added.
/// </param>
/// <param name='jobScheduleAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<JobScheduleAddHeaders> AddAsync(this IJobScheduleOperations operations, JobScheduleAddParameter cloudJobSchedule, JobScheduleAddOptions jobScheduleAddOptions = default(JobScheduleAddOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.AddWithHttpMessagesAsync(cloudJobSchedule, jobScheduleAddOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Lists all of the job schedules in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleListOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<CloudJobSchedule> List(this IJobScheduleOperations operations, JobScheduleListOptions jobScheduleListOptions = default(JobScheduleListOptions))
{
return ((IJobScheduleOperations)operations).ListAsync(jobScheduleListOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the job schedules in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Microsoft.Rest.Azure.IPage<CloudJobSchedule>> ListAsync(this IJobScheduleOperations operations, JobScheduleListOptions jobScheduleListOptions = default(JobScheduleListOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(jobScheduleListOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the job schedules in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobScheduleListNextOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<CloudJobSchedule> ListNext(this IJobScheduleOperations operations, string nextPageLink, JobScheduleListNextOptions jobScheduleListNextOptions = default(JobScheduleListNextOptions))
{
return ((IJobScheduleOperations)operations).ListNextAsync(nextPageLink, jobScheduleListNextOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the job schedules in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobScheduleListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Microsoft.Rest.Azure.IPage<CloudJobSchedule>> ListNextAsync(this IJobScheduleOperations operations, string nextPageLink, JobScheduleListNextOptions jobScheduleListNextOptions = default(JobScheduleListNextOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, jobScheduleListNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
//
// XmlSchemaType.cs
//
// Authors:
// Dwivedi, Ajay kumar Adwiv@Yahoo.com
// Atsushi Enomoto atsushi@ximian.com
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.System.Xml;
using System.ComponentModel;
using Mono.Xml.Schema;
using Mono.System.Xml.Serialization;
#if NET_2_0_in_the_future
using MS.Internal.Xml;
#endif
namespace Mono.System.Xml.Schema
{
/// <summary>
/// Summary description for XmlSchemaType.
/// </summary>
public class XmlSchemaType : XmlSchemaAnnotated
{
private XmlSchemaDerivationMethod final;
private bool isMixed;
private string name;
bool recursed;
internal XmlQualifiedName BaseSchemaTypeName;
internal XmlSchemaType BaseXmlSchemaTypeInternal;
internal XmlSchemaDatatype DatatypeInternal;
internal XmlSchemaDerivationMethod resolvedDerivedBy;
internal XmlSchemaDerivationMethod finalResolved;
internal XmlQualifiedName QNameInternal;
public XmlSchemaType ()
{
final = XmlSchemaDerivationMethod.None;
QNameInternal = XmlQualifiedName.Empty;
}
#region Attributes
[Mono.System.Xml.Serialization.XmlAttribute("name")]
public string Name {
get{ return name; }
set{ name = value; }
}
[DefaultValue(XmlSchemaDerivationMethod.None)]
[Mono.System.Xml.Serialization.XmlAttribute("final")]
public XmlSchemaDerivationMethod Final {
get{ return final; }
set{ final = value; }
}
#endregion
#region Post Compilation Schema Information
[XmlIgnore]
public XmlQualifiedName QualifiedName {
get{ return QNameInternal; }
}
[XmlIgnore]
public XmlSchemaDerivationMethod FinalResolved {
get{ return finalResolved; }
}
[XmlIgnore]
#if NET_2_0
[Obsolete ("This property is going away. Use BaseXmlSchemaType instead")]
#endif
public object BaseSchemaType {
get{
if (BaseXmlSchemaType != null)
return BaseXmlSchemaType;
else if (this == XmlSchemaComplexType.AnyType)
return null; // This property is designed so.
else
return Datatype;
}
}
[XmlIgnore]
// FIXME:This property works as always returning a valid schema type.
[MonoTODO]
// In .NET 2.0, all schema types used in schema documents must
// be XmlSchemaType, even if it is primitive type, in terms of
// non-obsolete Mono.System.Xml.Schema members.
// To modify this property, we have to make sure that it does
// not affect to any compilation/validation logic.
#if NET_2_0
public XmlSchemaType BaseXmlSchemaType {
#else
internal XmlSchemaType BaseXmlSchemaType {
#endif
get { return BaseXmlSchemaTypeInternal; }
}
[XmlIgnore]
public XmlSchemaDerivationMethod DerivedBy {
get{ return resolvedDerivedBy; }
}
[XmlIgnore]
public XmlSchemaDatatype Datatype {
get{ return DatatypeInternal; }
}
[XmlIgnore]
public virtual bool IsMixed {
get{ return isMixed; }
set{ isMixed = value; }
}
#if NET_2_0
// LAMESPEC: for IDREFS it returns Idref. for ENTITIES
// it returns Entity. for NMTOKENS it returns NmToken.
[XmlIgnore]
public XmlTypeCode TypeCode {
get {
if (this == XmlSchemaComplexType.AnyType)
return XmlTypeCode.Item;
if (DatatypeInternal == XmlSchemaSimpleType.AnySimpleType)
return XmlTypeCode.AnyAtomicType;
if (this == XmlSchemaSimpleType.XsIDRefs)
return XmlTypeCode.Idref;
if (this == XmlSchemaSimpleType.XsEntities)
return XmlTypeCode.Entity;
if (this == XmlSchemaSimpleType.XsNMTokens)
return XmlTypeCode.NmToken;
if (DatatypeInternal != null)
return DatatypeInternal.TypeCode;
return BaseXmlSchemaType.TypeCode;
}
}
#endif
#endregion
#if NET_2_0
internal static XmlSchemaType GetBuiltInType (XmlQualifiedName qualifiedName)
{
XmlSchemaType t = GetBuiltInSimpleType (qualifiedName);
if (t == null)
t = GetBuiltInComplexType (qualifiedName);
return t;
}
internal static XmlSchemaType GetBuiltInType (XmlTypeCode typecode)
{
if (typecode == XmlTypeCode.Item)
return XmlSchemaComplexType.AnyType;
return GetBuiltInSimpleType (typecode);
}
#endif
#if NET_2_0
public static XmlSchemaComplexType GetBuiltInComplexType (XmlQualifiedName qualifiedName)
#else
internal static XmlSchemaComplexType GetBuiltInComplexType (XmlQualifiedName qualifiedName)
#endif
{
if (qualifiedName.Name == "anyType" && qualifiedName.Namespace == XmlSchema.Namespace)
return XmlSchemaComplexType.AnyType;
return null;
}
#if NET_2_0
public static XmlSchemaComplexType GetBuiltInComplexType (XmlTypeCode typeCode)
{
switch (typeCode) {
case XmlTypeCode.Item:
return XmlSchemaComplexType.AnyType;
}
return null;
}
#endif
#if NET_2_0
[MonoTODO]
public static XmlSchemaSimpleType GetBuiltInSimpleType (XmlQualifiedName qualifiedName)
{
if (qualifiedName.Namespace == "http://www.w3.org/2003/11/xpath-datatypes") {
switch (qualifiedName.Name) {
case "untypedAtomic":
return XmlSchemaSimpleType.XdtUntypedAtomic;
case "anyAtomicType":
return XmlSchemaSimpleType.XdtAnyAtomicType;
case "yearMonthDuration":
return XmlSchemaSimpleType.XdtYearMonthDuration;
case "dayTimeDuration":
return XmlSchemaSimpleType.XdtDayTimeDuration;
}
return null;
}
else if (qualifiedName.Namespace != XmlSchema.Namespace)
return null;
switch (qualifiedName.Name) {
case "anySimpleType":
return XmlSchemaSimpleType.XsAnySimpleType;
case "string":
return XmlSchemaSimpleType.XsString;
case "boolean":
return XmlSchemaSimpleType.XsBoolean;
case "decimal":
return XmlSchemaSimpleType.XsDecimal;
case "float":
return XmlSchemaSimpleType.XsFloat;
case "double":
return XmlSchemaSimpleType.XsDouble;
case "duration":
return XmlSchemaSimpleType.XsDuration;
case "dateTime":
return XmlSchemaSimpleType.XsDateTime;
case "time":
return XmlSchemaSimpleType.XsTime;
case "date":
return XmlSchemaSimpleType.XsDate;
case "gYearMonth":
return XmlSchemaSimpleType.XsGYearMonth;
case "gYear":
return XmlSchemaSimpleType.XsGYear;
case "gMonthDay":
return XmlSchemaSimpleType.XsGMonthDay;
case "gDay":
return XmlSchemaSimpleType.XsGDay;
case "gMonth":
return XmlSchemaSimpleType.XsGMonth;
case "hexBinary":
return XmlSchemaSimpleType.XsHexBinary;
case "base64Binary":
return XmlSchemaSimpleType.XsBase64Binary;
case "anyURI":
return XmlSchemaSimpleType.XsAnyUri;
case "QName":
return XmlSchemaSimpleType.XsQName;
case "NOTATION":
return XmlSchemaSimpleType.XsNotation;
case "normalizedString":
return XmlSchemaSimpleType.XsNormalizedString;
case "token":
return XmlSchemaSimpleType.XsToken;
case "language":
return XmlSchemaSimpleType.XsLanguage;
case "NMTOKEN":
return XmlSchemaSimpleType.XsNMToken;
case "NMTOKENS":
return XmlSchemaSimpleType.XsNMTokens;
case "Name":
return XmlSchemaSimpleType.XsName;
case "NCName":
return XmlSchemaSimpleType.XsNCName;
case "ID":
return XmlSchemaSimpleType.XsID;
case "IDREF":
return XmlSchemaSimpleType.XsIDRef;
case "IDREFS":
return XmlSchemaSimpleType.XsIDRefs;
case "ENTITY":
return XmlSchemaSimpleType.XsEntity;
case "ENTITIES":
return XmlSchemaSimpleType.XsEntities;
case "integer":
return XmlSchemaSimpleType.XsInteger;
case "nonPositiveInteger":
return XmlSchemaSimpleType.XsNonPositiveInteger;
case "negativeInteger":
return XmlSchemaSimpleType.XsNegativeInteger;
case "long":
return XmlSchemaSimpleType.XsLong;
case "int":
return XmlSchemaSimpleType.XsInt;
case "short":
return XmlSchemaSimpleType.XsShort;
case "byte":
return XmlSchemaSimpleType.XsByte;
case "nonNegativeInteger":
return XmlSchemaSimpleType.XsNonNegativeInteger;
case "positiveInteger":
return XmlSchemaSimpleType.XsPositiveInteger;
case "unsignedLong":
return XmlSchemaSimpleType.XsUnsignedLong;
case "unsignedInt":
return XmlSchemaSimpleType.XsUnsignedInt;
case "unsignedShort":
return XmlSchemaSimpleType.XsUnsignedShort;
case "unsignedByte":
return XmlSchemaSimpleType.XsUnsignedByte;
}
return null;
}
internal static XmlSchemaSimpleType GetBuiltInSimpleType (XmlSchemaDatatype type)
{
if (type is XsdEntities)
return XmlSchemaSimpleType.XsEntities;
else if (type is XsdNMTokens)
return XmlSchemaSimpleType.XsNMTokens;
else if (type is XsdIDRefs)
return XmlSchemaSimpleType.XsIDRefs;
else
return GetBuiltInSimpleType (type.TypeCode);
}
[MonoTODO]
// Don't use this method to cover all XML Schema datatypes.
public static XmlSchemaSimpleType GetBuiltInSimpleType (XmlTypeCode typeCode)
{
switch (typeCode) {
case XmlTypeCode.None:
case XmlTypeCode.Item:
case XmlTypeCode.Node:
case XmlTypeCode.Document: // node
case XmlTypeCode.Element: // node
case XmlTypeCode.Attribute: // node
case XmlTypeCode.Namespace: // node
case XmlTypeCode.ProcessingInstruction: // node
case XmlTypeCode.Comment: // node
case XmlTypeCode.Text: // node
return null;
case XmlTypeCode.AnyAtomicType:
return XmlSchemaSimpleType.XdtAnyAtomicType;
case XmlTypeCode.UntypedAtomic:
return XmlSchemaSimpleType.XdtUntypedAtomic;
case XmlTypeCode.String:
return XmlSchemaSimpleType.XsString;
case XmlTypeCode.Boolean:
return XmlSchemaSimpleType.XsBoolean;
case XmlTypeCode.Decimal:
return XmlSchemaSimpleType.XsDecimal;
case XmlTypeCode.Float:
return XmlSchemaSimpleType.XsFloat;
case XmlTypeCode.Double:
return XmlSchemaSimpleType.XsDouble;
case XmlTypeCode.Duration:
return XmlSchemaSimpleType.XsDuration;
case XmlTypeCode.DateTime:
return XmlSchemaSimpleType.XsDateTime;
case XmlTypeCode.Time:
return XmlSchemaSimpleType.XsTime;
case XmlTypeCode.Date:
return XmlSchemaSimpleType.XsDate;
case XmlTypeCode.GYearMonth:
return XmlSchemaSimpleType.XsGYearMonth;
case XmlTypeCode.GYear:
return XmlSchemaSimpleType.XsGYear;
case XmlTypeCode.GMonthDay:
return XmlSchemaSimpleType.XsGMonthDay;
case XmlTypeCode.GDay:
return XmlSchemaSimpleType.XsGDay;
case XmlTypeCode.GMonth:
return XmlSchemaSimpleType.XsGMonth;
case XmlTypeCode.HexBinary:
return XmlSchemaSimpleType.XsHexBinary;
case XmlTypeCode.Base64Binary:
return XmlSchemaSimpleType.XsBase64Binary;
case XmlTypeCode.AnyUri:
return XmlSchemaSimpleType.XsAnyUri;
case XmlTypeCode.QName:
return XmlSchemaSimpleType.XsQName;
case XmlTypeCode.Notation:
return XmlSchemaSimpleType.XsNotation;
case XmlTypeCode.NormalizedString:
return XmlSchemaSimpleType.XsNormalizedString;
case XmlTypeCode.Token:
return XmlSchemaSimpleType.XsToken;
case XmlTypeCode.Language:
return XmlSchemaSimpleType.XsLanguage;
case XmlTypeCode.NmToken: // NmTokens is not primitive
return XmlSchemaSimpleType.XsNMToken;
case XmlTypeCode.Name:
return XmlSchemaSimpleType.XsName;
case XmlTypeCode.NCName:
return XmlSchemaSimpleType.XsNCName;
case XmlTypeCode.Id:
return XmlSchemaSimpleType.XsID;
case XmlTypeCode.Idref: // Idrefs is not primitive
return XmlSchemaSimpleType.XsIDRef;
case XmlTypeCode.Entity: // Entities is not primitive
return XmlSchemaSimpleType.XsEntity;
case XmlTypeCode.Integer:
return XmlSchemaSimpleType.XsInteger;
case XmlTypeCode.NonPositiveInteger:
return XmlSchemaSimpleType.XsNonPositiveInteger;
case XmlTypeCode.NegativeInteger:
return XmlSchemaSimpleType.XsNegativeInteger;
case XmlTypeCode.Long:
return XmlSchemaSimpleType.XsLong;
case XmlTypeCode.Int:
return XmlSchemaSimpleType.XsInt;
case XmlTypeCode.Short:
return XmlSchemaSimpleType.XsShort;
case XmlTypeCode.Byte:
return XmlSchemaSimpleType.XsByte;
case XmlTypeCode.NonNegativeInteger:
return XmlSchemaSimpleType.XsNonNegativeInteger;
case XmlTypeCode.UnsignedLong:
return XmlSchemaSimpleType.XsUnsignedLong;
case XmlTypeCode.UnsignedInt:
return XmlSchemaSimpleType.XsUnsignedInt;
case XmlTypeCode.UnsignedShort:
return XmlSchemaSimpleType.XsUnsignedShort;
case XmlTypeCode.UnsignedByte:
return XmlSchemaSimpleType.XsUnsignedByte;
case XmlTypeCode.PositiveInteger:
return XmlSchemaSimpleType.XsPositiveInteger;
case XmlTypeCode.YearMonthDuration:
return XmlSchemaSimpleType.XdtYearMonthDuration;
case XmlTypeCode.DayTimeDuration:
return XmlSchemaSimpleType.XdtDayTimeDuration;
}
return null;
}
public static bool IsDerivedFrom (XmlSchemaType derivedType, XmlSchemaType baseType, XmlSchemaDerivationMethod except)
{
if (derivedType.BaseXmlSchemaType == null)
return false;
if ((derivedType.DerivedBy & except) != 0)
return false;
if (derivedType.BaseXmlSchemaType == baseType)
return true;
return IsDerivedFrom (derivedType.BaseXmlSchemaType,
baseType, except);
}
#endif
internal bool ValidateRecursionCheck ()
{
if (recursed)
return (this != XmlSchemaComplexType.AnyType);
recursed = true;
XmlSchemaType baseType = this.BaseXmlSchemaType as XmlSchemaType;
bool result = false;
if (baseType != null)
result = baseType.ValidateRecursionCheck ();
recursed = false;
return result;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 4/16/2009 12:11:19 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System.Collections.Generic;
using System.Data;
using DotSpatial.NTSExtension;
using DotSpatial.Serialization;
using GeoAPI.Geometries;
using GeoAPI.Operation.Buffer;
using NetTopologySuite.Geometries;
using NetTopologySuite.Operation.Buffer;
namespace DotSpatial.Data
{
/// <summary>
/// Extension Methods for the Features
/// </summary>
public static class FeatureExt
{
/// <summary>
/// Generates a new feature from the buffer of this feature. The DataRow of
/// the new feature will be null.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="distance">The double distance</param>
/// <returns>An IFeature representing the output from the buffer operation</returns>
public static IFeature Buffer(this IFeature self, double distance)
{
IGeometry g = self.Geometry.Buffer(distance);
return new Feature(g);
}
/// <summary>
/// Generates a new feature from the buffer of this feature. The DataRow of
/// the new feature will be null.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="distance">The double distance</param>
/// <param name="endCapStyle">The end cap style to use</param>
/// <returns>An IFeature representing the output from the buffer operation</returns>
public static IFeature Buffer(this IFeature self, double distance, EndCapStyle endCapStyle)
{
IGeometry g = self.Geometry.Buffer(distance, new BufferParameters { EndCapStyle = endCapStyle });
return new Feature(g);
}
/// <summary>
/// Generates a new feature from the buffer of this feature. The DataRow of
/// the new feature will be null.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="distance">The double distance</param>
/// <param name="quadrantSegments">The number of segments to use to approximate a quadrant of a circle</param>
/// <returns>An IFeature representing the output from the buffer operation</returns>
public static IFeature Buffer(this IFeature self, double distance, int quadrantSegments)
{
IGeometry g = self.Geometry.Buffer(distance, quadrantSegments);
return new Feature(g);
}
/// <summary>
/// Generates a new feature from the buffer of this feature. The DataRow of
/// the new feature will be null.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="distance">The double distance</param>
/// <param name="quadrantSegments">The number of segments to use to approximate a quadrant of a circle</param>
/// <param name="endCapStyle">The end cap style to use</param>
/// <returns>An IFeature representing the output from the buffer operation</returns>
public static IFeature Buffer(this IFeature self, double distance, int quadrantSegments, EndCapStyle endCapStyle)
{
IGeometry g = self.Geometry.Buffer(distance, quadrantSegments, endCapStyle);
return new Feature(g);
}
/// <summary>
/// Generates a buffer, but also adds the newly created feature to the specified output featureset.
/// This will also compare the field names of the input featureset with the destination featureset.
/// If a column name exists in both places, it will copy those values to the destination featureset.
/// </summary>
/// <param name="self">The feature to calcualate the buffer for.</param>
/// <param name="distance">The double distance to use for calculating the buffer</param>
/// <param name="destinationFeatureset">The output featureset to add this feature to and use
/// as a reference for determining which data columns to copy.</param>
/// <returns>The IFeature that represents the buffer feature.</returns>
public static IFeature Buffer(this IFeature self, double distance, IFeatureSet destinationFeatureset)
{
IFeature f = Buffer(self, distance);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
/// <summary>
/// Generates a buffer, but also adds the newly created feature to the specified output featureset.
/// This will also compare the field names of the input featureset with the destination featureset.
/// If a column name exists in both places, it will copy those values to the destination featureset.
/// </summary>
/// <param name="self">The feature to calcualate the buffer for.</param>
/// <param name="distance">The double distance to use for calculating the buffer</param>
/// <param name="endCapStyle">The end cap style to use</param>
/// <param name="destinationFeatureset">The output featureset to add this feature to and use
/// as a reference for determining which data columns to copy.</param>
/// <returns>The IFeature that represents the buffer feature.</returns>
public static IFeature Buffer(this IFeature self, double distance, EndCapStyle endCapStyle, IFeatureSet destinationFeatureset)
{
IFeature f = Buffer(self, distance, endCapStyle);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
/// <summary>
/// Generates a buffer, but also adds the newly created feature to the specified output featureset.
/// This will also compare the field names of the input featureset with the destination featureset.
/// If a column name exists in both places, it will copy those values to the destination featureset.
/// </summary>
/// <param name="self">The feature to calcualate the buffer for.</param>
/// <param name="distance">The double distance to use for calculating the buffer</param>
/// <param name="quadrantSegments">The number of segments to use to approximate a quadrant of a circle</param>
/// <param name="destinationFeatureset">The output featureset to add this feature to and use
/// as a reference for determining which data columns to copy.</param>
/// <returns>The IFeature that represents the buffer feature.</returns>
public static IFeature Buffer(this IFeature self, double distance, int quadrantSegments, IFeatureSet destinationFeatureset)
{
IFeature f = Buffer(self, distance, quadrantSegments);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
/// <summary>
/// Generates a buffer, but also adds the newly created feature to the specified output featureset.
/// This will also compare the field names of the input featureset with the destination featureset.
/// If a column name exists in both places, it will copy those values to the destination featureset.
/// </summary>
/// <param name="self">The feature to calcualate the buffer for.</param>
/// <param name="distance">The double distance to use for calculating the buffer</param>
/// <param name="quadrantSegments">The number of segments to use to approximate a quadrant of a circle</param>
/// <param name="endCapStyle">The end cap style to use</param>
/// <param name="destinationFeatureset">The output featureset to add this feature to and use
/// as a reference for determining which data columns to copy.</param>
/// <returns>The IFeature that represents the buffer feature.</returns>
public static IFeature Buffer(this IFeature self, double distance, int quadrantSegments, EndCapStyle endCapStyle, IFeatureSet destinationFeatureset)
{
IFeature f = Buffer(self, distance, quadrantSegments, endCapStyle);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
/// <summary>
/// If the geometry for this shape was loaded from a file, this contains the size
/// of this shape in 16-bit words as per the Esri Shapefile specification.
/// </summary>
public static int ContentLength(this IFeature self)
{
return self.ShapeIndex != null ? self.ShapeIndex.ContentLength : 0;
}
/// <summary>
/// Calculates a new feature that has a geometry that is the convex hull of this feature.
/// </summary>
/// <param name="self">This feature</param>
/// <returns>A new feature that is the convex hull of this feature.</returns>
public static IFeature ConvexHull(this IFeature self)
{
return new Feature(self.Geometry.ConvexHull());
}
/// <summary>
/// Calculates a new feature that has a geometry that is the convex hull of this feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="destinationFeatureset">The destination featureset to add this feature to</param>
/// <returns>The newly created IFeature</returns>
public static IFeature ConvexHull(this IFeature self, IFeatureSet destinationFeatureset)
{
IFeature f = ConvexHull(self);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
/// <summary>
/// Creates a new Feature that has a geometry that is the difference between this feature and the specified feature.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <returns>A new feature that is the geometric difference between this feature and the specified feature.</returns>
public static IFeature Difference(this IFeature self, IGeometry other)
{
if (other == null) return self.Copy();
IGeometry g = self.Geometry.Difference(other);
if (g == null || g.IsEmpty) return null;
return new Feature(g);
}
/// <summary>
/// Creates a new Feature that has a geometry that is the difference between this feature and the specified feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <param name="destinationFeatureSet">The featureset to add the new feature to.</param>
/// <param name="joinType">This clarifies the overall join strategy being used with regards to attribute fields.</param>
/// <returns>A new feature that is the geometric difference between this feature and the specified feature.</returns>
public static IFeature Difference(this IFeature self, IFeature other, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
IFeature f = Difference(self, other.Geometry);
if (f != null)
{
UpdateFields(self, other, f, destinationFeatureSet, joinType);
}
return f;
}
/// <summary>
/// Creates a new GML string describing the location of this point
/// </summary>
/// <returns>A String representing the Geographic Markup Language version of this point</returns>
public static string ExportToGml(this IFeature self)
{
var geo = self.Geometry as Geometry;
return (geo == null) ? "" : geo.ToGMLFeature().ToString();
}
// This handles the slightly complex business of attribute outputs.
private static void UpdateFields(IFeature self, IFeature other, IFeature result, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
if (destinationFeatureSet.FeatureType != result.FeatureType) return;
destinationFeatureSet.Features.Add(result);
if (joinType == FieldJoinType.None) return;
if (joinType == FieldJoinType.All)
{
// This overly complex mess is concerned with preventing duplicate field names.
// This assumes that numbers were appended when duplicates occured, and will
// repeat the process here to establish one set of string names and values.
Dictionary<string, object> mappings = new Dictionary<string, object>();
foreach (DataColumn dc in self.ParentFeatureSet.DataTable.Columns)
{
string name = dc.ColumnName;
int i = 1;
while (mappings.ContainsKey(name))
{
name = dc.ColumnName + i;
i++;
}
mappings.Add(name, self.DataRow[dc.ColumnName]);
}
foreach (DataColumn dc in other.ParentFeatureSet.DataTable.Columns)
{
string name = dc.ColumnName;
int i = 1;
while (mappings.ContainsKey(name))
{
name = dc.ColumnName + i;
i++;
}
mappings.Add(name, other.DataRow[dc.ColumnName]);
}
foreach (KeyValuePair<string, object> pair in mappings)
{
if (!result.DataRow.Table.Columns.Contains(pair.Key))
{
result.DataRow.Table.Columns.Add(pair.Key);
}
result.DataRow[pair.Key] = pair.Value;
}
}
if (joinType == FieldJoinType.LocalOnly)
{
foreach (DataColumn dc in destinationFeatureSet.DataTable.Columns)
{
if (self.DataRow.Table.Columns.Contains(dc.ColumnName))
{
result.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
}
if (joinType == FieldJoinType.ForeignOnly)
{
foreach (DataColumn dc in destinationFeatureSet.DataTable.Columns)
{
if (other.DataRow[dc.ColumnName] != null)
{
result.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
}
}
// /// <summary>
// /// Gets a boolean that is true if the geometry of this feature is disjoint with the geometry
// /// of the specified feature
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The feature to compare this feature to</param>
// /// <returns>Boolean, true if this feature is disjoint with the specified feature</returns>
// public static bool Disjoint(this IFeature self, IFeature other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Disjoint(Geometry.FromBasicGeometry(other));
// }
// /// <summary>
// /// Gets a boolean that is true if the geometry of this feature is disjoint with the geometry
// /// of the specified feature.
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The feature to compare this feature to</param>
// /// <returns>Boolean, true if this feature is disjoint with the specified feature</returns>
// public static bool Disjoint(this IFeature self, IGeometry other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Disjoint(other);
// }
// /// <summary>
// /// Distance between features.
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The feature to compare this feature to</param>
// /// <returns></returns>
// public static double Distance(this IFeature self, IFeature other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Distance(Geometry.FromBasicGeometry(other));
// }
// /// <summary>
// /// Gets a boolean that is true if the geometry of this feature is disjoint with the geometry
// /// of the specified feature
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The feature to compare this feature to</param>
// /// <returns>Boolean, true if this feature is disjoint with the specified feature</returns>
// public static double Distance(this IFeature self, IGeometry other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Distance(other);
// }
// /// <summary>
// /// Creates a new Feature that has a geometry that is the intersection between this feature and the specified feature.
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to compare to.</param>
// /// <returns>A new feature that is the geometric intersection between this feature and the specified feature.</returns>
// public static IFeature Intersection(this IFeature self, IFeature other)
// {
// IGeometry g = Geometry.FromBasicGeometry(self.Geometry).Intersection(Geometry.FromBasicGeometry(other.Geometry));
// if (g == null) return null;
// if (g.IsEmpty) return null;
// return new Feature(g);
// }
/// <summary>
/// Creates a new Feature that has a geometry that is the intersection between this feature and the specified feature.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <returns>A new feature that is the geometric intersection between this feature and the specified feature.</returns>
public static IFeature Intersection(this IFeature self, IGeometry other)
{
IGeometry g = self.Geometry.Intersection(other);
if (g == null || g.IsEmpty) return null;
return new Feature(g);
}
/// <summary>
/// Creates a new Feature that has a geometry that is the intersection between this feature and the specified feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <param name="destinationFeatureSet">The featureset to add the new feature to.</param>
/// <param name="joinType">This clarifies the overall join strategy being used with regards to attribute fields.</param>
/// <returns>A new feature that is the geometric intersection between this feature and the specified feature.</returns>
public static IFeature Intersection(this IFeature self, IFeature other, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
IFeature f = Intersection(self, other.Geometry);
if (f != null)
{
UpdateFields(self, other, f, destinationFeatureSet, joinType);
}
return f;
}
/// <summary>
/// Gets the integer number of parts associated with this feature.
/// </summary>
public static int NumParts(this IFeature self)
{
int count = 0;
if (self.FeatureType != FeatureType.Polygon)
return self.Geometry.NumGeometries;
IPolygon p = self.Geometry as IPolygon;
if (p == null)
{
// we have a multi-polygon situation
for (int i = 0; i < self.Geometry.NumGeometries; i++)
{
p = self.Geometry.GetGeometryN(i) as IPolygon;
if (p == null) continue;
count += 1; // Shell
count += p.NumInteriorRings; // Holes
}
}
else
{
// The feature is a polygon, not a multi-polygon
count += 1; // Shell
count += p.NumInteriorRings; // Holes
}
return count;
}
/// <summary>
/// Rotates the BasicGeometry of the feature by the given radian angle around the given Origin.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="origin">The coordinate the feature gets rotated around.</param>
/// <param name="radAngle">The rotation angle in radian.</param>
public static void Rotate(this IFeature self, Coordinate origin, double radAngle)
{
IGeometry geo = self.Geometry.Copy();
geo.Rotate(origin, radAngle);
self.Geometry = geo;
self.UpdateEnvelope();
}
/// <summary>
/// When a shape is loaded from a Shapefile, this will identify whether M or Z values are used
/// and whether or not the shape is null.
/// </summary>
public static ShapeType ShapeType(this IFeature self)
{
return self.ShapeIndex != null ? self.ShapeIndex.ShapeType : Data.ShapeType.NullShape;
}
/// <summary>
/// An index value that is saved in some file formats.
/// </summary>
public static int RecordNumber(this IFeature self)
{
return self.ShapeIndex != null ? self.ShapeIndex.RecordNumber : -1;
}
/// <summary>
/// Creates a new Feature that has a geometry that is the symmetric difference between this feature and the specified feature.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <returns>A new feature that is the geometric symmetric difference between this feature and the specified feature.</returns>
public static IFeature SymmetricDifference(this IFeature self, IGeometry other)
{
IGeometry g = self.Geometry.SymmetricDifference(other);
if (g == null || g.IsEmpty) return null;
return new Feature(g);
}
/// <summary>
/// Creates a new Feature that has a geometry that is the symmetric difference between this feature and the specified feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <param name="destinationFeatureSet">The featureset to add the new feature to.</param>
/// <param name="joinType">This clarifies the overall join strategy being used with regards to attribute fields.</param>
/// <returns>A new feature that is the geometric symmetric difference between this feature and the specified feature.</returns>
public static IFeature SymmetricDifference(this IFeature self, IFeature other, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
IFeature f = SymmetricDifference(self, other.Geometry);
if (f != null)
{
UpdateFields(self, other, f, destinationFeatureSet, joinType);
}
return f;
}
/// <summary>
/// Creates a new Feature that has a geometry that is the union between this feature and the specified feature.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <returns>A new feature that is the geometric union between this feature and the specified feature.</returns>
public static IFeature Union(this IFeature self, IGeometry other)
{
IGeometry g = self.Geometry.Union(other);
if (g == null || g.IsEmpty) return null;
return new Feature(g);
}
/// <summary>
/// Creates a new Feature that has a geometry that is the union between this feature and the specified feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <param name="destinationFeatureSet">The featureset to add the new feature to.</param>
/// <param name="joinType">Clarifies how the attributes should be handled during the union</param>
/// <returns>A new feature that is the geometric symmetric difference between this feature and the specified feature.</returns>
public static IFeature Union(this IFeature self, IFeature other, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
IFeature f = Union(self, other.Geometry);
if (f != null)
{
UpdateFields(self, other, f, destinationFeatureSet, joinType);
}
return f;
}
}
}
| |
// Copyright 2015, Google Inc. 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.
// Author: Chris Seeley
using Google.Api.Ads.Common.Lib;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Google.Api.Ads.Dfp.Lib {
/// <summary>
/// Lists all the services available through this library.
/// </summary>
public partial class DfpService : AdsService {
/// <summary>
/// All the services available in v201502.
/// </summary>
public class v201502 {
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ActivityGroupService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ActivityGroupService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ActivityService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ActivityService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/AdExclusionRuleService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature AdExclusionRuleService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/AdRuleService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature AdRuleService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/BaseRateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature BaseRateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ContactService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContactService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/AudienceSegmentService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature AudienceSegmentService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/CompanyService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature CompanyService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ContentService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContentService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ContentMetadataKeyHierarchyService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContentMetadataKeyHierarchyService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/CreativeService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/CreativeSetService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeSetService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/CreativeTemplateService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeTemplateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/CreativeWrapperService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeWrapperService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/CustomFieldService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CustomFieldService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/CustomTargetingService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CustomTargetingService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ExchangeRateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ExchangeRateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ForecastService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ForecastService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/InventoryService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature InventoryService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/LabelService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LabelService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/LineItemTemplateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemTemplateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/LineItemService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/LineItemCreativeAssociationService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemCreativeAssociationService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/LiveStreamEventService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LiveStreamEventService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/NetworkService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature NetworkService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/OrderService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature OrderService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/PackageService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature PackageService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ProductPackageItemService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ProductPackageItemService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ProductPackageService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ProductPackageService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/PlacementService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature PlacementService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/PremiumRateService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature PremiumRateService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ProductService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProductService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ProductTemplateService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProductTemplateService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ProposalService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProposalService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ProposalLineItemService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProposalLineItemService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/PublisherQueryLanguageService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature PublisherQueryLanguageService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/RateCardService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature RateCardService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ReconciliationOrderReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationOrderReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ReconciliationReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ReconciliationReportRowService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationReportRowService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/ReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/SharedAdUnitService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature SharedAdUnitService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/SuggestedAdUnitService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature SuggestedAdUnitService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/TeamService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature TeamService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/UserService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature UserService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/UserTeamAssociationService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature UserTeamAssociationService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201502/WorkflowRequestService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature WorkflowRequestService;
/// <summary>
/// Factory type for v201502 services.
/// </summary>
public static readonly Type factoryType = typeof(DfpServiceFactory);
/// <summary>
/// Static constructor to initialize the service constants.
/// </summary>
static v201502() {
ActivityGroupService = DfpService.MakeServiceSignature("v201502", "ActivityGroupService");
ActivityService = DfpService.MakeServiceSignature("v201502", "ActivityService");
AdExclusionRuleService = DfpService.MakeServiceSignature("v201502", "AdExclusionRuleService");
AdRuleService = DfpService.MakeServiceSignature("v201502", "AdRuleService");
BaseRateService = DfpService.MakeServiceSignature("v201502", "BaseRateService");
ContactService = DfpService.MakeServiceSignature("v201502", "ContactService");
AudienceSegmentService = DfpService.MakeServiceSignature("v201502",
"AudienceSegmentService");
CompanyService = DfpService.MakeServiceSignature("v201502", "CompanyService");
ContentService = DfpService.MakeServiceSignature("v201502", "ContentService");
ContentMetadataKeyHierarchyService = DfpService.MakeServiceSignature("v201502",
"ContentMetadataKeyHierarchyService");
CreativeService = DfpService.MakeServiceSignature("v201502", "CreativeService");
CreativeSetService = DfpService.MakeServiceSignature("v201502", "CreativeSetService");
CreativeTemplateService = DfpService.MakeServiceSignature("v201502",
"CreativeTemplateService");
CreativeWrapperService = DfpService.MakeServiceSignature("v201502",
"CreativeWrapperService");
CustomTargetingService = DfpService.MakeServiceSignature("v201502",
"CustomTargetingService");
CustomFieldService = DfpService.MakeServiceSignature("v201502",
"CustomFieldService");
ExchangeRateService = DfpService.MakeServiceSignature("v201502", "ExchangeRateService");
ForecastService = DfpService.MakeServiceSignature("v201502", "ForecastService");
InventoryService = DfpService.MakeServiceSignature("v201502", "InventoryService");
LabelService = DfpService.MakeServiceSignature("v201502", "LabelService");
LineItemTemplateService = DfpService.MakeServiceSignature("v201502",
"LineItemTemplateService");
LineItemService = DfpService.MakeServiceSignature("v201502", "LineItemService");
LineItemCreativeAssociationService =
DfpService.MakeServiceSignature("v201502", "LineItemCreativeAssociationService");
LiveStreamEventService = DfpService.MakeServiceSignature("v201502",
"LiveStreamEventService");
NetworkService = DfpService.MakeServiceSignature("v201502", "NetworkService");
OrderService = DfpService.MakeServiceSignature("v201502", "OrderService");
PackageService = DfpService.MakeServiceSignature("v201502", "PackageService");
ProductPackageService = DfpService.MakeServiceSignature("v201502", "ProductPackageService");
ProductPackageItemService = DfpService.MakeServiceSignature("v201502", "ProductPackageItemService");
PlacementService = DfpService.MakeServiceSignature("v201502", "PlacementService");
PremiumRateService = DfpService.MakeServiceSignature("v201502", "PremiumRateService");
ProductService = DfpService.MakeServiceSignature("v201502", "ProductService");
ProductTemplateService = DfpService.MakeServiceSignature("v201502",
"ProductTemplateService");
ProposalService = DfpService.MakeServiceSignature("v201502", "ProposalService");
ProposalLineItemService = DfpService.MakeServiceSignature("v201502",
"ProposalLineItemService");
PublisherQueryLanguageService = DfpService.MakeServiceSignature("v201502",
"PublisherQueryLanguageService");
RateCardService = DfpService.MakeServiceSignature("v201502", "RateCardService");
ReconciliationOrderReportService = DfpService.MakeServiceSignature("v201502",
"ReconciliationOrderReportService");
ReconciliationReportService = DfpService.MakeServiceSignature("v201502",
"ReconciliationReportService");
ReconciliationReportRowService = DfpService.MakeServiceSignature("v201502",
"ReconciliationReportRowService");
ReportService = DfpService.MakeServiceSignature("v201502", "ReportService");
SharedAdUnitService = DfpService.MakeServiceSignature("v201502",
"SharedAdUnitService");
SuggestedAdUnitService = DfpService.MakeServiceSignature("v201502",
"SuggestedAdUnitService");
TeamService = DfpService.MakeServiceSignature("v201502", "TeamService");
UserService = DfpService.MakeServiceSignature("v201502", "UserService");
UserTeamAssociationService = DfpService.MakeServiceSignature("v201502",
"UserTeamAssociationService");
WorkflowRequestService = DfpService.MakeServiceSignature("v201502",
"WorkflowRequestService");
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Controls.DocumentViewer.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Controls
{
public partial class DocumentViewer : System.Windows.Controls.Primitives.DocumentViewerBase
{
#region Methods and constructors
public void DecreaseZoom()
{
}
public DocumentViewer()
{
}
public void Find()
{
}
public void FitToHeight()
{
}
public void FitToMaxPagesAcross()
{
}
public void FitToMaxPagesAcross(int pagesAcross)
{
}
public void FitToWidth()
{
}
protected override System.Collections.ObjectModel.ReadOnlyCollection<System.Windows.Controls.Primitives.DocumentPageView> GetPageViewsCollection(out bool changed)
{
changed = default(bool);
return default(System.Collections.ObjectModel.ReadOnlyCollection<System.Windows.Controls.Primitives.DocumentPageView>);
}
public void IncreaseZoom()
{
}
public void MoveDown()
{
}
public void MoveLeft()
{
}
public void MoveRight()
{
}
public void MoveUp()
{
}
public override void OnApplyTemplate()
{
}
protected override void OnBringIntoView(System.Windows.DependencyObject element, System.Windows.Rect rect, int pageNumber)
{
}
protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
{
return default(System.Windows.Automation.Peers.AutomationPeer);
}
protected virtual new void OnDecreaseZoomCommand()
{
}
protected override void OnDocumentChanged()
{
}
protected virtual new void OnFindCommand()
{
}
protected override void OnFirstPageCommand()
{
}
protected virtual new void OnFitToHeightCommand()
{
}
protected virtual new void OnFitToMaxPagesAcrossCommand()
{
}
protected virtual new void OnFitToMaxPagesAcrossCommand(int pagesAcross)
{
}
protected virtual new void OnFitToWidthCommand()
{
}
protected override void OnGoToPageCommand(int pageNumber)
{
}
protected virtual new void OnIncreaseZoomCommand()
{
}
protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e)
{
}
protected override void OnLastPageCommand()
{
}
protected override void OnMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e)
{
}
protected virtual new void OnMoveDownCommand()
{
}
protected virtual new void OnMoveLeftCommand()
{
}
protected virtual new void OnMoveRightCommand()
{
}
protected virtual new void OnMoveUpCommand()
{
}
protected override void OnNextPageCommand()
{
}
protected override void OnPreviewMouseWheel(System.Windows.Input.MouseWheelEventArgs e)
{
}
protected override void OnPreviousPageCommand()
{
}
protected virtual new void OnScrollPageDownCommand()
{
}
protected virtual new void OnScrollPageLeftCommand()
{
}
protected virtual new void OnScrollPageRightCommand()
{
}
protected virtual new void OnScrollPageUpCommand()
{
}
protected virtual new void OnViewThumbnailsCommand()
{
}
public void ScrollPageDown()
{
}
public void ScrollPageLeft()
{
}
public void ScrollPageRight()
{
}
public void ScrollPageUp()
{
}
public void ViewThumbnails()
{
}
#endregion
#region Properties and indexers
public bool CanDecreaseZoom
{
get
{
return default(bool);
}
}
public bool CanIncreaseZoom
{
get
{
return default(bool);
}
}
public bool CanMoveDown
{
get
{
return default(bool);
}
}
public bool CanMoveLeft
{
get
{
return default(bool);
}
}
public bool CanMoveRight
{
get
{
return default(bool);
}
}
public bool CanMoveUp
{
get
{
return default(bool);
}
}
public double ExtentHeight
{
get
{
return default(double);
}
}
public double ExtentWidth
{
get
{
return default(double);
}
}
public static System.Windows.Input.RoutedUICommand FitToHeightCommand
{
get
{
Contract.Ensures(Contract.Result<System.Windows.Input.RoutedUICommand>() != null);
return default(System.Windows.Input.RoutedUICommand);
}
}
public static System.Windows.Input.RoutedUICommand FitToMaxPagesAcrossCommand
{
get
{
Contract.Ensures(Contract.Result<System.Windows.Input.RoutedUICommand>() != null);
return default(System.Windows.Input.RoutedUICommand);
}
}
public static System.Windows.Input.RoutedUICommand FitToWidthCommand
{
get
{
Contract.Ensures(Contract.Result<System.Windows.Input.RoutedUICommand>() != null);
return default(System.Windows.Input.RoutedUICommand);
}
}
public double HorizontalOffset
{
get
{
return default(double);
}
set
{
}
}
public double HorizontalPageSpacing
{
get
{
return default(double);
}
set
{
}
}
public int MaxPagesAcross
{
get
{
return default(int);
}
set
{
}
}
public bool ShowPageBorders
{
get
{
return default(bool);
}
set
{
}
}
public double VerticalOffset
{
get
{
return default(double);
}
set
{
}
}
public double VerticalPageSpacing
{
get
{
return default(double);
}
set
{
}
}
public double ViewportHeight
{
get
{
return default(double);
}
}
public double ViewportWidth
{
get
{
return default(double);
}
}
public static System.Windows.Input.RoutedUICommand ViewThumbnailsCommand
{
get
{
Contract.Ensures(Contract.Result<System.Windows.Input.RoutedUICommand>() != null);
return default(System.Windows.Input.RoutedUICommand);
}
}
public double Zoom
{
get
{
return default(double);
}
set
{
}
}
#endregion
#region Fields
public readonly static System.Windows.DependencyProperty CanDecreaseZoomProperty;
public readonly static System.Windows.DependencyProperty CanIncreaseZoomProperty;
public readonly static System.Windows.DependencyProperty CanMoveDownProperty;
public readonly static System.Windows.DependencyProperty CanMoveLeftProperty;
public readonly static System.Windows.DependencyProperty CanMoveRightProperty;
public readonly static System.Windows.DependencyProperty CanMoveUpProperty;
public readonly static System.Windows.DependencyProperty ExtentHeightProperty;
public readonly static System.Windows.DependencyProperty ExtentWidthProperty;
public readonly static System.Windows.DependencyProperty HorizontalOffsetProperty;
public readonly static System.Windows.DependencyProperty HorizontalPageSpacingProperty;
public readonly static System.Windows.DependencyProperty MaxPagesAcrossProperty;
public readonly static System.Windows.DependencyProperty ShowPageBordersProperty;
public readonly static System.Windows.DependencyProperty VerticalOffsetProperty;
public readonly static System.Windows.DependencyProperty VerticalPageSpacingProperty;
public readonly static System.Windows.DependencyProperty ViewportHeightProperty;
public readonly static System.Windows.DependencyProperty ViewportWidthProperty;
public readonly static System.Windows.DependencyProperty ZoomProperty;
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StockTraderRI.Modules.Watch.WatchList;
using StockTraderRI.Modules.Watch.Services;
using StockTraderRI.Infrastructure.Interfaces;
using Microsoft.Practices.Prism.PubSubEvents;
using Microsoft.Practices.Prism.Regions;
using Moq;
using System.Collections.ObjectModel;
using StockTraderRI.Infrastructure;
using StockTraderRI.Modules.Watch;
using System.ComponentModel;
namespace StockTraderRI.Modules.WatchList.Tests.WatchList
{
[TestClass]
public class WatchListViewModelFixture
{
[TestMethod]
public void WhenConstructed_IntializesValues()
{
// Prepare
MockMarketPricesUpdatedEvent marketPricesUpdatedEvent = new MockMarketPricesUpdatedEvent();
ObservableCollection<string> watchList = new ObservableCollection<string>();
watchList.Add("A");
watchList.Add("B");
watchList.Add("C");
Mock<IWatchListService> mockWatchListService = new Mock<IWatchListService>();
mockWatchListService.Setup(x => x.RetrieveWatchList()).Returns(watchList).Verifiable();
Mock<IMarketFeedService> mockMarketFeedService = new Mock<IMarketFeedService>();
mockMarketFeedService.Setup(x => x.GetPrice("A")).Returns(1);
mockMarketFeedService.Setup(x => x.GetPrice("B")).Returns(2);
mockMarketFeedService.Setup(x => x.GetPrice("C")).Returns(3);
Mock<IRegionManager> mockRegionManager = new Mock<IRegionManager>();
Mock<IEventAggregator> mockEventAggregator = new Mock<IEventAggregator>();
mockEventAggregator.Setup(x => x.GetEvent<MarketPricesUpdatedEvent>()).Returns(marketPricesUpdatedEvent);
IWatchListService watchListService = mockWatchListService.Object;
IMarketFeedService marketFeedService = mockMarketFeedService.Object;
IRegionManager regionManager = mockRegionManager.Object;
IEventAggregator eventAggregator = mockEventAggregator.Object;
// Act
WatchListViewModel actual = new WatchListViewModel(watchListService, marketFeedService, regionManager, eventAggregator);
// Verify
Assert.IsNotNull(actual);
Assert.AreEqual("WATCH LIST", actual.HeaderInfo);
Assert.AreEqual(3, actual.WatchListItems.Count);
Assert.IsNull(actual.CurrentWatchItem);
Assert.IsNotNull(actual.RemoveWatchCommand);
mockWatchListService.VerifyAll();
}
[TestMethod]
public void WhenCurrentWatchItemSet_PropertyIsUpdated()
{
// Prepare
MockMarketPricesUpdatedEvent marketPricesUpdatedEvent = new MockMarketPricesUpdatedEvent();
Mock<TickerSymbolSelectedEvent> mockTickerSymbolSelectedEvent = new Mock<TickerSymbolSelectedEvent>();
ObservableCollection<string> watchList = new ObservableCollection<string>();
watchList.Add("A");
watchList.Add("B");
watchList.Add("C");
Mock<IWatchListService> mockWatchListService = new Mock<IWatchListService>();
mockWatchListService.Setup(x => x.RetrieveWatchList()).Returns(watchList).Verifiable();
Mock<IMarketFeedService> mockMarketFeedService = new Mock<IMarketFeedService>();
mockMarketFeedService.Setup(x => x.GetPrice("A")).Returns(1);
mockMarketFeedService.Setup(x => x.GetPrice("B")).Returns(2);
mockMarketFeedService.Setup(x => x.GetPrice("C")).Returns(3);
Mock<IRegionManager> mockRegionManager = new Mock<IRegionManager>();
Mock<IEventAggregator> mockEventAggregator = new Mock<IEventAggregator>();
mockEventAggregator.Setup(x => x.GetEvent<MarketPricesUpdatedEvent>()).Returns(marketPricesUpdatedEvent);
mockEventAggregator.Setup(x => x.GetEvent<TickerSymbolSelectedEvent>()).Returns(mockTickerSymbolSelectedEvent.Object);
IWatchListService watchListService = mockWatchListService.Object;
IMarketFeedService marketFeedService = mockMarketFeedService.Object;
IRegionManager regionManager = mockRegionManager.Object;
IEventAggregator eventAggregator = mockEventAggregator.Object;
WatchListViewModel target = new WatchListViewModel(watchListService, marketFeedService, regionManager, eventAggregator);
bool propertyChangedRaised = false;
target.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "CurrentWatchItem")
{
propertyChangedRaised = true;
}
};
// Act
target.CurrentWatchItem = target.WatchListItems[1];
// Verify
Assert.AreSame(target.WatchListItems[1], target.CurrentWatchItem);
Assert.IsTrue(propertyChangedRaised);
}
[TestMethod]
public void WhenCurrentWatchItemSet_TickerSymbolSelectedEventRaised()
{
// Prepare
MockMarketPricesUpdatedEvent marketPricesUpdatedEvent = new MockMarketPricesUpdatedEvent();
Mock<TickerSymbolSelectedEvent> mockTickerSymbolSelectedEvent = new Mock<TickerSymbolSelectedEvent>();
mockTickerSymbolSelectedEvent.Setup(x => x.Publish("B")).Verifiable();
ObservableCollection<string> watchList = new ObservableCollection<string>();
watchList.Add("A");
watchList.Add("B");
watchList.Add("C");
Mock<IWatchListService> mockWatchListService = new Mock<IWatchListService>();
mockWatchListService.Setup(x => x.RetrieveWatchList()).Returns(watchList).Verifiable();
Mock<IMarketFeedService> mockMarketFeedService = new Mock<IMarketFeedService>();
mockMarketFeedService.Setup(x => x.GetPrice("A")).Returns(1);
mockMarketFeedService.Setup(x => x.GetPrice("B")).Returns(2);
mockMarketFeedService.Setup(x => x.GetPrice("C")).Returns(3);
Mock<IRegionManager> mockRegionManager = new Mock<IRegionManager>();
Mock<IEventAggregator> mockEventAggregator = new Mock<IEventAggregator>();
mockEventAggregator.Setup(x => x.GetEvent<MarketPricesUpdatedEvent>()).Returns(marketPricesUpdatedEvent);
mockEventAggregator.Setup(x => x.GetEvent<TickerSymbolSelectedEvent>()).Returns(mockTickerSymbolSelectedEvent.Object);
IWatchListService watchListService = mockWatchListService.Object;
IMarketFeedService marketFeedService = mockMarketFeedService.Object;
IRegionManager regionManager = mockRegionManager.Object;
IEventAggregator eventAggregator = mockEventAggregator.Object;
WatchListViewModel target = new WatchListViewModel(watchListService, marketFeedService, regionManager, eventAggregator);
// Act
target.CurrentWatchItem = target.WatchListItems[1];
// Verify
mockTickerSymbolSelectedEvent.VerifyAll();
}
[TestMethod]
public void WhenRemoveCommandExecuted_RemovesWatchEntry()
{
// Prepare
MockMarketPricesUpdatedEvent marketPricesUpdatedEvent = new MockMarketPricesUpdatedEvent();
ObservableCollection<string> watchList = new ObservableCollection<string>();
watchList.Add("A");
watchList.Add("B");
watchList.Add("C");
Mock<IWatchListService> mockWatchListService = new Mock<IWatchListService>();
mockWatchListService.Setup(x => x.RetrieveWatchList()).Returns(watchList).Verifiable();
Mock<IMarketFeedService> mockMarketFeedService = new Mock<IMarketFeedService>();
mockMarketFeedService.Setup(x => x.GetPrice("A")).Returns(1);
mockMarketFeedService.Setup(x => x.GetPrice("B")).Returns(2);
mockMarketFeedService.Setup(x => x.GetPrice("C")).Returns(3);
Mock<IRegion> mockMainRegion = new Mock<IRegion>();
Mock<IRegionManager> mockRegionManager = new Mock<IRegionManager>();
mockRegionManager.Setup(x => x.Regions[RegionNames.MainRegion]).Returns(mockMainRegion.Object);
Mock<IEventAggregator> mockEventAggregator = new Mock<IEventAggregator>();
mockEventAggregator.Setup(x => x.GetEvent<MarketPricesUpdatedEvent>()).Returns(marketPricesUpdatedEvent);
IWatchListService watchListService = mockWatchListService.Object;
IMarketFeedService marketFeedService = mockMarketFeedService.Object;
IRegionManager regionManager = mockRegionManager.Object;
IEventAggregator eventAggregator = mockEventAggregator.Object;
WatchListViewModel target = new WatchListViewModel(watchListService, marketFeedService, regionManager, eventAggregator);
// Act
target.RemoveWatchCommand.Execute("A");
// Verify
Assert.AreEqual(2, target.WatchListItems.Count);
}
[TestMethod]
public void WhenWatchListItemAdded_NavigatesToWatchListView()
{
// Prepare
MockMarketPricesUpdatedEvent marketPricesUpdatedEvent = new MockMarketPricesUpdatedEvent();
ObservableCollection<string> watchList = new ObservableCollection<string>();
watchList.Add("A");
watchList.Add("B");
watchList.Add("C");
Mock<IWatchListService> mockWatchListService = new Mock<IWatchListService>();
mockWatchListService.Setup(x => x.RetrieveWatchList()).Returns(watchList).Verifiable();
Mock<IMarketFeedService> mockMarketFeedService = new Mock<IMarketFeedService>();
mockMarketFeedService.Setup(x => x.GetPrice("A")).Returns(1);
mockMarketFeedService.Setup(x => x.GetPrice("B")).Returns(2);
mockMarketFeedService.Setup(x => x.GetPrice("C")).Returns(3);
Mock<IRegion> mockMainRegion = new Mock<IRegion>();
mockMainRegion.Setup(x => x.RequestNavigate(new Uri("/WatchListView", UriKind.RelativeOrAbsolute), It.IsAny<Action<NavigationResult>>())).Verifiable();
Mock<IRegionManager> mockRegionManager = new Mock<IRegionManager>();
mockRegionManager.Setup(x => x.Regions[RegionNames.MainRegion]).Returns(mockMainRegion.Object);
Mock<IEventAggregator> mockEventAggregator = new Mock<IEventAggregator>();
mockEventAggregator.Setup(x => x.GetEvent<MarketPricesUpdatedEvent>()).Returns(marketPricesUpdatedEvent);
IWatchListService watchListService = mockWatchListService.Object;
IMarketFeedService marketFeedService = mockMarketFeedService.Object;
IRegionManager regionManager = mockRegionManager.Object;
IEventAggregator eventAggregator = mockEventAggregator.Object;
WatchListViewModel target = new WatchListViewModel(watchListService, marketFeedService, regionManager, eventAggregator);
// Act
target.WatchListItems.Add(new WatchItem("D", 20));
// Verify
mockMainRegion.Verify(x => x.RequestNavigate(new Uri("/WatchListView", UriKind.RelativeOrAbsolute), It.IsAny<Action<NavigationResult>>()), Times.Once());
}
[TestMethod]
public void WhenMarketPriceNotAvailable_PriceSetToNull()
{
// Prepare
MockMarketPricesUpdatedEvent marketPricesUpdatedEvent = new MockMarketPricesUpdatedEvent();
ObservableCollection<string> watchList = new ObservableCollection<string>();
watchList.Add("A");
Mock<IWatchListService> mockWatchListService = new Mock<IWatchListService>();
mockWatchListService.Setup(x => x.RetrieveWatchList()).Returns(watchList).Verifiable();
Mock<IMarketFeedService> mockMarketFeedService = new Mock<IMarketFeedService>();
mockMarketFeedService.Setup(x => x.GetPrice("A")).Throws(new ArgumentException("tickerSymbol"));
Mock<IRegionManager> mockRegionManager = new Mock<IRegionManager>();
Mock<IEventAggregator> mockEventAggregator = new Mock<IEventAggregator>();
mockEventAggregator.Setup(x => x.GetEvent<MarketPricesUpdatedEvent>()).Returns(marketPricesUpdatedEvent);
IWatchListService watchListService = mockWatchListService.Object;
IMarketFeedService marketFeedService = mockMarketFeedService.Object;
IRegionManager regionManager = mockRegionManager.Object;
IEventAggregator eventAggregator = mockEventAggregator.Object;
// Act
WatchListViewModel actual = new WatchListViewModel(watchListService, marketFeedService, regionManager, eventAggregator);
// Verify
Assert.IsNotNull(actual);
Assert.AreEqual(1, actual.WatchListItems.Count);
Assert.AreEqual("A", actual.WatchListItems[0].TickerSymbol);
Assert.AreEqual(null, actual.WatchListItems[0].CurrentPrice);
}
[TestMethod]
public void WhenMarketPriceChagnes_PriceUpdated()
{
// Prepare
MockMarketPricesUpdatedEvent marketPricesUpdatedEvent = new MockMarketPricesUpdatedEvent();
ObservableCollection<string> watchList = new ObservableCollection<string>();
watchList.Add("A");
watchList.Add("B");
watchList.Add("C");
Mock<IWatchListService> mockWatchListService = new Mock<IWatchListService>();
mockWatchListService.Setup(x => x.RetrieveWatchList()).Returns(watchList).Verifiable();
Mock<IMarketFeedService> mockMarketFeedService = new Mock<IMarketFeedService>();
mockMarketFeedService.Setup(x => x.GetPrice("A")).Returns(1);
mockMarketFeedService.Setup(x => x.GetPrice("B")).Returns(2);
mockMarketFeedService.Setup(x => x.GetPrice("C")).Returns(3);
Mock<IRegionManager> mockRegionManager = new Mock<IRegionManager>();
Mock<IEventAggregator> mockEventAggregator = new Mock<IEventAggregator>();
mockEventAggregator.Setup(x => x.GetEvent<MarketPricesUpdatedEvent>()).Returns(marketPricesUpdatedEvent);
IWatchListService watchListService = mockWatchListService.Object;
IMarketFeedService marketFeedService = mockMarketFeedService.Object;
IRegionManager regionManager = mockRegionManager.Object;
IEventAggregator eventAggregator = mockEventAggregator.Object;
WatchListViewModel target = new WatchListViewModel(watchListService, marketFeedService, regionManager, eventAggregator);
Dictionary<string, decimal> newPrices = new Dictionary<string,decimal>()
{
{ "A", 10 },
{ "B", 20 },
{ "C", 30 },
};
// Act
marketPricesUpdatedEvent.Publish(newPrices);
// Verify
Assert.AreEqual(3, target.WatchListItems.Count);
Assert.AreEqual(10, target.WatchListItems[0].CurrentPrice);
Assert.AreEqual(20, target.WatchListItems[1].CurrentPrice);
Assert.AreEqual(30, target.WatchListItems[2].CurrentPrice);
}
private class MockMarketPricesUpdatedEvent : MarketPricesUpdatedEvent
{
public Action<IDictionary<string, decimal>> SubscribeArgumentAction;
public Predicate<IDictionary<string, decimal>> SubscribeArgumentFilter;
public ThreadOption SubscribeArgumentThreadOption;
public override SubscriptionToken Subscribe(Action<IDictionary<string, decimal>> action, ThreadOption threadOption, bool keepSubscriberReferenceAlive, Predicate<IDictionary<string, decimal>> filter)
{
SubscribeArgumentAction = action;
SubscribeArgumentFilter = filter;
SubscribeArgumentThreadOption = threadOption;
return null;
}
public override void Publish(IDictionary<string, decimal> payload)
{
this.SubscribeArgumentAction(payload);
}
}
private class MockTickerSymbolSelectedEvent : TickerSymbolSelectedEvent
{
public bool PublishCalled;
public string PublishArg;
public override void Publish(string payload)
{
PublishCalled = true;
PublishArg = payload;
}
}
}
}
| |
// 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 defines an internal class used to throw exceptions in BCL code.
// The main purpose is to reduce code size.
//
// The old way to throw an exception generates quite a lot IL code and assembly code.
// Following is an example:
// C# source
// throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
// IL code:
// IL_0003: ldstr "key"
// IL_0008: ldstr "ArgumentNull_Key"
// IL_000d: call string System.Environment::GetResourceString(string)
// IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string)
// IL_0017: throw
// which is 21bytes in IL.
//
// So we want to get rid of the ldstr and call to Environment.GetResource in IL.
// In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the
// argument name and resource name in a small integer. The source code will be changed to
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key);
//
// The IL code will be 7 bytes.
// IL_0008: ldc.i4.4
// IL_0009: ldc.i4.4
// IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument)
// IL_000f: ldarg.0
//
// This will also reduce the Jitted code size a lot.
//
// It is very important we do this for generic classes because we can easily generate the same code
// multiple times for different instantiation.
//
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace System
{
[StackTraceHidden]
internal static class ThrowHelper
{
internal static void ThrowArrayTypeMismatchException()
{
throw new ArrayTypeMismatchException();
}
internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType)
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeWithPointersNotSupported, targetType));
}
internal static void ThrowIndexOutOfRangeException()
{
throw new IndexOutOfRangeException();
}
internal static void ThrowArgumentOutOfRangeException()
{
throw new ArgumentOutOfRangeException();
}
internal static void ThrowArgumentException_DestinationTooShort()
{
throw new ArgumentException(SR.Argument_DestinationTooShort, "destination");
}
internal static void ThrowArgumentException_OverlapAlignmentMismatch()
{
throw new ArgumentException(SR.Argument_OverlapAlignmentMismatch);
}
internal static void ThrowArgumentException_CannotExtractScalar(ExceptionArgument argument)
{
throw GetArgumentException(ExceptionResource.Argument_CannotExtractScalar, argument);
}
internal static void ThrowArgumentOutOfRange_IndexException()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.index,
ExceptionResource.ArgumentOutOfRange_Index);
}
internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.index,
ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
internal static void ThrowValueArgumentOutOfRange_NeedNonNegNumException()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.value,
ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.length,
ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.startIndex,
ExceptionResource.ArgumentOutOfRange_Index);
}
internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.count,
ExceptionResource.ArgumentOutOfRange_Count);
}
internal static void ThrowWrongKeyTypeArgumentException<T>(T key, Type targetType)
{
// Generic key to move the boxing to the right hand side of throw
throw GetWrongKeyTypeArgumentException((object)key, targetType);
}
internal static void ThrowWrongValueTypeArgumentException<T>(T value, Type targetType)
{
// Generic key to move the boxing to the right hand side of throw
throw GetWrongValueTypeArgumentException((object)value, targetType);
}
private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key)
{
return new ArgumentException(SR.Format(SR.Argument_AddingDuplicateWithKey, key));
}
internal static void ThrowAddingDuplicateWithKeyArgumentException<T>(T key)
{
// Generic key to move the boxing to the right hand side of throw
throw GetAddingDuplicateWithKeyArgumentException((object)key);
}
internal static void ThrowKeyNotFoundException<T>(T key)
{
// Generic key to move the boxing to the right hand side of throw
throw GetKeyNotFoundException((object)key);
}
internal static void ThrowArgumentException(ExceptionResource resource)
{
throw GetArgumentException(resource);
}
internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument)
{
throw GetArgumentException(resource, argument);
}
private static ArgumentNullException GetArgumentNullException(ExceptionArgument argument)
{
return new ArgumentNullException(GetArgumentName(argument));
}
internal static void ThrowArgumentNullException(ExceptionArgument argument)
{
throw GetArgumentNullException(argument);
}
internal static void ThrowArgumentNullException(ExceptionResource resource)
{
throw new ArgumentNullException(GetResourceString(resource));
}
internal static void ThrowArgumentNullException(ExceptionArgument argument, ExceptionResource resource)
{
throw new ArgumentNullException(GetArgumentName(argument), GetResourceString(resource));
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument)
{
throw new ArgumentOutOfRangeException(GetArgumentName(argument));
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
{
throw GetArgumentOutOfRangeException(argument, resource);
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource)
{
throw GetArgumentOutOfRangeException(argument, paramNumber, resource);
}
internal static void ThrowInvalidOperationException()
{
throw new InvalidOperationException();
}
internal static void ThrowInvalidOperationException(ExceptionResource resource)
{
throw GetInvalidOperationException(resource);
}
internal static void ThrowInvalidOperationException_OutstandingReferences()
{
throw new InvalidOperationException(SR.Memory_OutstandingReferences);
}
internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e)
{
throw new InvalidOperationException(GetResourceString(resource), e);
}
internal static void ThrowSerializationException(ExceptionResource resource)
{
throw new SerializationException(GetResourceString(resource));
}
internal static void ThrowSecurityException(ExceptionResource resource)
{
throw new System.Security.SecurityException(GetResourceString(resource));
}
internal static void ThrowRankException(ExceptionResource resource)
{
throw new RankException(GetResourceString(resource));
}
internal static void ThrowNotSupportedException(ExceptionResource resource)
{
throw new NotSupportedException(GetResourceString(resource));
}
internal static void ThrowUnauthorizedAccessException(ExceptionResource resource)
{
throw new UnauthorizedAccessException(GetResourceString(resource));
}
internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource)
{
throw new ObjectDisposedException(objectName, GetResourceString(resource));
}
internal static void ThrowObjectDisposedException(ExceptionResource resource)
{
throw new ObjectDisposedException(null, GetResourceString(resource));
}
internal static void ThrowNotSupportedException()
{
throw new NotSupportedException();
}
internal static void ThrowAggregateException(List<Exception> exceptions)
{
throw new AggregateException(exceptions);
}
internal static void ThrowOutOfMemoryException()
{
throw new OutOfMemoryException();
}
internal static void ThrowArgumentException_Argument_InvalidArrayType()
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
internal static void ThrowInvalidOperationException_InvalidOperation_EnumNotStarted()
{
throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
}
internal static void ThrowInvalidOperationException_InvalidOperation_EnumEnded()
{
throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
}
internal static void ThrowInvalidOperationException_EnumCurrent(int index)
{
throw GetInvalidOperationException_EnumCurrent(index);
}
internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion()
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen()
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
internal static void ThrowInvalidOperationException_InvalidOperation_NoValue()
{
throw new InvalidOperationException(SR.InvalidOperation_NoValue);
}
internal static void ThrowInvalidOperationException_ConcurrentOperationsNotSupported()
{
throw new InvalidOperationException(SR.InvalidOperation_ConcurrentOperationsNotSupported);
}
internal static void ThrowInvalidOperationException_HandleIsNotInitialized()
{
throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotInitialized);
}
internal static void ThrowInvalidOperationException_HandleIsNotPinned()
{
throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotPinned);
}
internal static void ThrowArraySegmentCtorValidationFailedExceptions(Array array, int offset, int count)
{
throw GetArraySegmentCtorValidationFailedException(array, offset, count);
}
internal static void ThrowFormatException_BadFormatSpecifier()
{
throw new FormatException(SR.Argument_BadFormatSpecifier);
}
internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge()
{
throw new ArgumentOutOfRangeException("precision", SR.Format(SR.Argument_PrecisionTooLarge, StandardFormat.MaxPrecision));
}
internal static void ThrowArgumentOutOfRangeException_SymbolDoesNotFit()
{
throw new ArgumentOutOfRangeException("symbol", SR.Argument_BadFormatSpecifier);
}
private static Exception GetArraySegmentCtorValidationFailedException(Array array, int offset, int count)
{
if (array == null)
return new ArgumentNullException(nameof(array));
if (offset < 0)
return new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
return new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
Debug.Assert(array.Length - offset < count);
return new ArgumentException(SR.Argument_InvalidOffLen);
}
private static ArgumentException GetArgumentException(ExceptionResource resource)
{
return new ArgumentException(GetResourceString(resource));
}
private static InvalidOperationException GetInvalidOperationException(ExceptionResource resource)
{
return new InvalidOperationException(GetResourceString(resource));
}
private static ArgumentException GetWrongKeyTypeArgumentException(object key, Type targetType)
{
return new ArgumentException(SR.Format(SR.Arg_WrongType, key, targetType), nameof(key));
}
private static ArgumentException GetWrongValueTypeArgumentException(object value, Type targetType)
{
return new ArgumentException(SR.Format(SR.Arg_WrongType, value, targetType), nameof(value));
}
private static KeyNotFoundException GetKeyNotFoundException(object key)
{
return new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key));
}
private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
{
return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource));
}
private static ArgumentException GetArgumentException(ExceptionResource resource, ExceptionArgument argument)
{
return new ArgumentException(GetResourceString(resource), GetArgumentName(argument));
}
private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource)
{
return new ArgumentOutOfRangeException(GetArgumentName(argument) + "[" + paramNumber.ToString() + "]", GetResourceString(resource));
}
private static InvalidOperationException GetInvalidOperationException_EnumCurrent(int index)
{
return new InvalidOperationException(
index < 0 ?
SR.InvalidOperation_EnumNotStarted :
SR.InvalidOperation_EnumEnded);
}
// Allow nulls for reference types and Nullable<U>, but not for value types.
// Aggressively inline so the jit evaluates the if in place and either drops the call altogether
// Or just leaves null test and call to the Non-returning ThrowHelper.ThrowArgumentNullException
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void IfNullAndNullsAreIllegalThenThrow<T>(object value, ExceptionArgument argName)
{
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
if (!(default(T) == null) && value == null)
ThrowHelper.ThrowArgumentNullException(argName);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void ThrowForUnsupportedVectorBaseType<T>() where T : struct
{
if (typeof(T) != typeof(byte) && typeof(T) != typeof(sbyte) &&
typeof(T) != typeof(short) && typeof(T) != typeof(ushort) &&
typeof(T) != typeof(int) && typeof(T) != typeof(uint) &&
typeof(T) != typeof(long) && typeof(T) != typeof(ulong) &&
typeof(T) != typeof(float) && typeof(T) != typeof(double))
{
ThrowNotSupportedException(ExceptionResource.Arg_TypeNotSupported);
}
}
#if false // Reflection-based implementation does not work for CoreRT/ProjectN
// This function will convert an ExceptionArgument enum value to the argument name string.
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetArgumentName(ExceptionArgument argument)
{
Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument),
"The enum value is not defined, please check the ExceptionArgument Enum.");
return argument.ToString();
}
#endif
private static string GetArgumentName(ExceptionArgument argument)
{
switch (argument)
{
case ExceptionArgument.obj:
return "obj";
case ExceptionArgument.dictionary:
return "dictionary";
case ExceptionArgument.array:
return "array";
case ExceptionArgument.info:
return "info";
case ExceptionArgument.key:
return "key";
case ExceptionArgument.text:
return "text";
case ExceptionArgument.values:
return "values";
case ExceptionArgument.value:
return "value";
case ExceptionArgument.startIndex:
return "startIndex";
case ExceptionArgument.task:
return "task";
case ExceptionArgument.bytes:
return "bytes";
case ExceptionArgument.byteIndex:
return "byteIndex";
case ExceptionArgument.byteCount:
return "byteCount";
case ExceptionArgument.ch:
return "ch";
case ExceptionArgument.chars:
return "chars";
case ExceptionArgument.charIndex:
return "charIndex";
case ExceptionArgument.charCount:
return "charCount";
case ExceptionArgument.s:
return "s";
case ExceptionArgument.input:
return "input";
case ExceptionArgument.ownedMemory:
return "ownedMemory";
case ExceptionArgument.list:
return "list";
case ExceptionArgument.index:
return "index";
case ExceptionArgument.capacity:
return "capacity";
case ExceptionArgument.collection:
return "collection";
case ExceptionArgument.item:
return "item";
case ExceptionArgument.converter:
return "converter";
case ExceptionArgument.match:
return "match";
case ExceptionArgument.count:
return "count";
case ExceptionArgument.action:
return "action";
case ExceptionArgument.comparison:
return "comparison";
case ExceptionArgument.exceptions:
return "exceptions";
case ExceptionArgument.exception:
return "exception";
case ExceptionArgument.pointer:
return "pointer";
case ExceptionArgument.start:
return "start";
case ExceptionArgument.format:
return "format";
case ExceptionArgument.culture:
return "culture";
case ExceptionArgument.comparer:
return "comparer";
case ExceptionArgument.comparable:
return "comparable";
case ExceptionArgument.source:
return "source";
case ExceptionArgument.state:
return "state";
case ExceptionArgument.length:
return "length";
case ExceptionArgument.comparisonType:
return "comparisonType";
case ExceptionArgument.manager:
return "manager";
case ExceptionArgument.sourceBytesToCopy:
return "sourceBytesToCopy";
case ExceptionArgument.callBack:
return "callBack";
case ExceptionArgument.creationOptions:
return "creationOptions";
case ExceptionArgument.function:
return "function";
case ExceptionArgument.scheduler:
return "scheduler";
case ExceptionArgument.continuationAction:
return "continuationAction";
case ExceptionArgument.continuationFunction:
return "continuationFunction";
case ExceptionArgument.tasks:
return "tasks";
case ExceptionArgument.asyncResult:
return "asyncResult";
case ExceptionArgument.beginMethod:
return "beginMethod";
case ExceptionArgument.endMethod:
return "endMethod";
case ExceptionArgument.endFunction:
return "endFunction";
case ExceptionArgument.cancellationToken:
return "cancellationToken";
case ExceptionArgument.continuationOptions:
return "continuationOptions";
case ExceptionArgument.delay:
return "delay";
case ExceptionArgument.millisecondsDelay:
return "millisecondsDelay";
case ExceptionArgument.millisecondsTimeout:
return "millisecondsTimeout";
case ExceptionArgument.stateMachine:
return "stateMachine";
case ExceptionArgument.timeout:
return "timeout";
case ExceptionArgument.type:
return "type";
case ExceptionArgument.sourceIndex:
return "sourceIndex";
case ExceptionArgument.sourceArray:
return "sourceArray";
case ExceptionArgument.destinationIndex:
return "destinationIndex";
case ExceptionArgument.destinationArray:
return "destinationArray";
case ExceptionArgument.pHandle:
return "pHandle";
case ExceptionArgument.other:
return "other";
case ExceptionArgument.newSize:
return "newSize";
case ExceptionArgument.lowerBounds:
return "lowerBounds";
case ExceptionArgument.lengths:
return "lengths";
case ExceptionArgument.len:
return "len";
case ExceptionArgument.keys:
return "keys";
case ExceptionArgument.indices:
return "indices";
case ExceptionArgument.index1:
return "index1";
case ExceptionArgument.index2:
return "index2";
case ExceptionArgument.index3:
return "index3";
case ExceptionArgument.length1:
return "length1";
case ExceptionArgument.length2:
return "length2";
case ExceptionArgument.length3:
return "length3";
case ExceptionArgument.endIndex:
return "endIndex";
case ExceptionArgument.elementType:
return "elementType";
case ExceptionArgument.arrayIndex:
return "arrayIndex";
default:
Debug.Fail("The enum value is not defined, please check the ExceptionArgument Enum.");
return "";
}
}
#if false // Reflection-based implementation does not work for CoreRT/ProjectN
// This function will convert an ExceptionResource enum value to the resource string.
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetResourceString(ExceptionResource resource)
{
Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource),
"The enum value is not defined, please check the ExceptionResource Enum.");
return SR.GetResourceString(resource.ToString());
}
#endif
private static string GetResourceString(ExceptionResource resource)
{
switch (resource)
{
case ExceptionResource.ArgumentOutOfRange_Index:
return SR.ArgumentOutOfRange_Index;
case ExceptionResource.ArgumentOutOfRange_IndexCount:
return SR.ArgumentOutOfRange_IndexCount;
case ExceptionResource.ArgumentOutOfRange_IndexCountBuffer:
return SR.ArgumentOutOfRange_IndexCountBuffer;
case ExceptionResource.ArgumentOutOfRange_Count:
return SR.ArgumentOutOfRange_Count;
case ExceptionResource.Arg_ArrayPlusOffTooSmall:
return SR.Arg_ArrayPlusOffTooSmall;
case ExceptionResource.NotSupported_ReadOnlyCollection:
return SR.NotSupported_ReadOnlyCollection;
case ExceptionResource.Arg_RankMultiDimNotSupported:
return SR.Arg_RankMultiDimNotSupported;
case ExceptionResource.Arg_NonZeroLowerBound:
return SR.Arg_NonZeroLowerBound;
case ExceptionResource.ArgumentOutOfRange_ListInsert:
return SR.ArgumentOutOfRange_ListInsert;
case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum:
return SR.ArgumentOutOfRange_NeedNonNegNum;
case ExceptionResource.ArgumentOutOfRange_SmallCapacity:
return SR.ArgumentOutOfRange_SmallCapacity;
case ExceptionResource.Argument_InvalidOffLen:
return SR.Argument_InvalidOffLen;
case ExceptionResource.Argument_CannotExtractScalar:
return SR.Argument_CannotExtractScalar;
case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection:
return SR.ArgumentOutOfRange_BiggerThanCollection;
case ExceptionResource.Serialization_MissingKeys:
return SR.Serialization_MissingKeys;
case ExceptionResource.Serialization_NullKey:
return SR.Serialization_NullKey;
case ExceptionResource.NotSupported_KeyCollectionSet:
return SR.NotSupported_KeyCollectionSet;
case ExceptionResource.NotSupported_ValueCollectionSet:
return SR.NotSupported_ValueCollectionSet;
case ExceptionResource.InvalidOperation_NullArray:
return SR.InvalidOperation_NullArray;
case ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted:
return SR.TaskT_TransitionToFinal_AlreadyCompleted;
case ExceptionResource.TaskCompletionSourceT_TrySetException_NullException:
return SR.TaskCompletionSourceT_TrySetException_NullException;
case ExceptionResource.TaskCompletionSourceT_TrySetException_NoExceptions:
return SR.TaskCompletionSourceT_TrySetException_NoExceptions;
case ExceptionResource.NotSupported_StringComparison:
return SR.NotSupported_StringComparison;
case ExceptionResource.ConcurrentCollection_SyncRoot_NotSupported:
return SR.ConcurrentCollection_SyncRoot_NotSupported;
case ExceptionResource.Task_MultiTaskContinuation_NullTask:
return SR.Task_MultiTaskContinuation_NullTask;
case ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple:
return SR.InvalidOperation_WrongAsyncResultOrEndCalledMultiple;
case ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList:
return SR.Task_MultiTaskContinuation_EmptyTaskList;
case ExceptionResource.Task_Start_TaskCompleted:
return SR.Task_Start_TaskCompleted;
case ExceptionResource.Task_Start_Promise:
return SR.Task_Start_Promise;
case ExceptionResource.Task_Start_ContinuationTask:
return SR.Task_Start_ContinuationTask;
case ExceptionResource.Task_Start_AlreadyStarted:
return SR.Task_Start_AlreadyStarted;
case ExceptionResource.Task_RunSynchronously_Continuation:
return SR.Task_RunSynchronously_Continuation;
case ExceptionResource.Task_RunSynchronously_Promise:
return SR.Task_RunSynchronously_Promise;
case ExceptionResource.Task_RunSynchronously_TaskCompleted:
return SR.Task_RunSynchronously_TaskCompleted;
case ExceptionResource.Task_RunSynchronously_AlreadyStarted:
return SR.Task_RunSynchronously_AlreadyStarted;
case ExceptionResource.AsyncMethodBuilder_InstanceNotInitialized:
return SR.AsyncMethodBuilder_InstanceNotInitialized;
case ExceptionResource.Task_ContinueWith_ESandLR:
return SR.Task_ContinueWith_ESandLR;
case ExceptionResource.Task_ContinueWith_NotOnAnything:
return SR.Task_ContinueWith_NotOnAnything;
case ExceptionResource.Task_Delay_InvalidDelay:
return SR.Task_Delay_InvalidDelay;
case ExceptionResource.Task_Delay_InvalidMillisecondsDelay:
return SR.Task_Delay_InvalidMillisecondsDelay;
case ExceptionResource.Task_Dispose_NotCompleted:
return SR.Task_Dispose_NotCompleted;
case ExceptionResource.Task_ThrowIfDisposed:
return SR.Task_ThrowIfDisposed;
case ExceptionResource.Task_WaitMulti_NullTask:
return SR.Task_WaitMulti_NullTask;
case ExceptionResource.ArgumentException_OtherNotArrayOfCorrectLength:
return SR.ArgumentException_OtherNotArrayOfCorrectLength;
case ExceptionResource.ArgumentNull_Array:
return SR.ArgumentNull_Array;
case ExceptionResource.ArgumentNull_SafeHandle:
return SR.ArgumentNull_SafeHandle;
case ExceptionResource.ArgumentOutOfRange_EndIndexStartIndex:
return SR.ArgumentOutOfRange_EndIndexStartIndex;
case ExceptionResource.ArgumentOutOfRange_Enum:
return SR.ArgumentOutOfRange_Enum;
case ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported:
return SR.ArgumentOutOfRange_HugeArrayNotSupported;
case ExceptionResource.Argument_AddingDuplicate:
return SR.Argument_AddingDuplicate;
case ExceptionResource.Argument_InvalidArgumentForComparison:
return SR.Argument_InvalidArgumentForComparison;
case ExceptionResource.Arg_LowerBoundsMustMatch:
return SR.Arg_LowerBoundsMustMatch;
case ExceptionResource.Arg_MustBeType:
return SR.Arg_MustBeType;
case ExceptionResource.Arg_Need1DArray:
return SR.Arg_Need1DArray;
case ExceptionResource.Arg_Need2DArray:
return SR.Arg_Need2DArray;
case ExceptionResource.Arg_Need3DArray:
return SR.Arg_Need3DArray;
case ExceptionResource.Arg_NeedAtLeast1Rank:
return SR.Arg_NeedAtLeast1Rank;
case ExceptionResource.Arg_RankIndices:
return SR.Arg_RankIndices;
case ExceptionResource.Arg_RanksAndBounds:
return SR.Arg_RanksAndBounds;
case ExceptionResource.InvalidOperation_IComparerFailed:
return SR.InvalidOperation_IComparerFailed;
case ExceptionResource.NotSupported_FixedSizeCollection:
return SR.NotSupported_FixedSizeCollection;
case ExceptionResource.Rank_MultiDimNotSupported:
return SR.Rank_MultiDimNotSupported;
case ExceptionResource.Arg_TypeNotSupported:
return SR.Arg_TypeNotSupported;
default:
Debug.Fail("The enum value is not defined, please check the ExceptionResource Enum.");
return "";
}
}
}
//
// The convention for this enum is using the argument name as the enum name
//
internal enum ExceptionArgument
{
obj,
dictionary,
array,
info,
key,
text,
values,
value,
startIndex,
task,
bytes,
byteIndex,
byteCount,
ch,
chars,
charIndex,
charCount,
s,
input,
ownedMemory,
list,
index,
capacity,
collection,
item,
converter,
match,
count,
action,
comparison,
exceptions,
exception,
pointer,
start,
format,
culture,
comparer,
comparable,
source,
state,
length,
comparisonType,
manager,
sourceBytesToCopy,
callBack,
creationOptions,
function,
scheduler,
continuationAction,
continuationFunction,
tasks,
asyncResult,
beginMethod,
endMethod,
endFunction,
cancellationToken,
continuationOptions,
delay,
millisecondsDelay,
millisecondsTimeout,
stateMachine,
timeout,
type,
sourceIndex,
sourceArray,
destinationIndex,
destinationArray,
pHandle,
other,
newSize,
lowerBounds,
lengths,
len,
keys,
indices,
index1,
index2,
index3,
length1,
length2,
length3,
endIndex,
elementType,
arrayIndex,
}
//
// The convention for this enum is using the resource name as the enum name
//
internal enum ExceptionResource
{
ArgumentOutOfRange_Index,
ArgumentOutOfRange_IndexCount,
ArgumentOutOfRange_IndexCountBuffer,
ArgumentOutOfRange_Count,
Arg_ArrayPlusOffTooSmall,
NotSupported_ReadOnlyCollection,
Arg_RankMultiDimNotSupported,
Arg_NonZeroLowerBound,
ArgumentOutOfRange_ListInsert,
ArgumentOutOfRange_NeedNonNegNum,
ArgumentOutOfRange_SmallCapacity,
Argument_InvalidOffLen,
Argument_CannotExtractScalar,
ArgumentOutOfRange_BiggerThanCollection,
Serialization_MissingKeys,
Serialization_NullKey,
NotSupported_KeyCollectionSet,
NotSupported_ValueCollectionSet,
InvalidOperation_NullArray,
TaskT_TransitionToFinal_AlreadyCompleted,
TaskCompletionSourceT_TrySetException_NullException,
TaskCompletionSourceT_TrySetException_NoExceptions,
NotSupported_StringComparison,
ConcurrentCollection_SyncRoot_NotSupported,
Task_MultiTaskContinuation_NullTask,
InvalidOperation_WrongAsyncResultOrEndCalledMultiple,
Task_MultiTaskContinuation_EmptyTaskList,
Task_Start_TaskCompleted,
Task_Start_Promise,
Task_Start_ContinuationTask,
Task_Start_AlreadyStarted,
Task_RunSynchronously_Continuation,
Task_RunSynchronously_Promise,
Task_RunSynchronously_TaskCompleted,
Task_RunSynchronously_AlreadyStarted,
AsyncMethodBuilder_InstanceNotInitialized,
Task_ContinueWith_ESandLR,
Task_ContinueWith_NotOnAnything,
Task_Delay_InvalidDelay,
Task_Delay_InvalidMillisecondsDelay,
Task_Dispose_NotCompleted,
Task_ThrowIfDisposed,
Task_WaitMulti_NullTask,
ArgumentException_OtherNotArrayOfCorrectLength,
ArgumentNull_Array,
ArgumentNull_SafeHandle,
ArgumentOutOfRange_EndIndexStartIndex,
ArgumentOutOfRange_Enum,
ArgumentOutOfRange_HugeArrayNotSupported,
Argument_AddingDuplicate,
Argument_InvalidArgumentForComparison,
Arg_LowerBoundsMustMatch,
Arg_MustBeType,
Arg_Need1DArray,
Arg_Need2DArray,
Arg_Need3DArray,
Arg_NeedAtLeast1Rank,
Arg_RankIndices,
Arg_RanksAndBounds,
InvalidOperation_IComparerFailed,
NotSupported_FixedSizeCollection,
Rank_MultiDimNotSupported,
Arg_TypeNotSupported,
}
}
| |
namespace AngleSharp.Core.Tests.Html
{
using AngleSharp.Html.Dom;
using NUnit.Framework;
/// <summary>
/// Tests generated according to the W3C-Test.org page:
/// http://www.w3c-test.org/html/semantics/forms/constraints/form-validation-validity-tooShort.html
/// </summary>
[TestFixture]
public class ValidityTooShortTests
{
[Test]
public void TestTooshortInputText1()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "");
element.Value = "abc";
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputText2()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "";
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputText3()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcde";
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputText4()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcd";
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputText5()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abc";
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputText6()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcde";
element.IsDirty = true;
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputText7()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "AAAAA";
element.IsDirty = true;
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputText8()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcd";
element.IsDirty = true;
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputText9()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abc";
element.IsDirty = true;
Assert.AreEqual("text", element.Type);
Assert.AreEqual(true, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputSearch1()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "");
element.Value = "abc";
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputSearch2()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "";
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputSearch3()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcde";
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputSearch4()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcd";
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputSearch5()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abc";
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputSearch6()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcde";
element.IsDirty = true;
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputSearch7()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "AAAAA";
element.IsDirty = true;
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputSearch8()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcd";
element.IsDirty = true;
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputSearch9()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abc";
element.IsDirty = true;
Assert.AreEqual("search", element.Type);
Assert.AreEqual(true, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputTel1()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "");
element.Value = "abc";
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputTel2()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "";
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputTel3()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcde";
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputTel4()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcd";
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputTel5()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abc";
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputTel6()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcde";
element.IsDirty = true;
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputTel7()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "AAAAA";
element.IsDirty = true;
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputTel8()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcd";
element.IsDirty = true;
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputTel9()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abc";
element.IsDirty = true;
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(true, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputUrl1()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "");
element.Value = "abc";
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputUrl2()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "";
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputUrl3()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcde";
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputUrl4()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcd";
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputUrl5()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abc";
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputUrl6()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcde";
element.IsDirty = true;
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputUrl7()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "AAAAA";
element.IsDirty = true;
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputUrl8()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcd";
element.IsDirty = true;
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputUrl9()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abc";
element.IsDirty = true;
Assert.AreEqual("url", element.Type);
Assert.AreEqual(true, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputEmail1()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "");
element.Value = "abc";
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputEmail2()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "";
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputEmail3()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcde";
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputEmail4()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcd";
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputEmail5()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abc";
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputEmail6()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcde";
element.IsDirty = true;
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputEmail7()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "AAAAA";
element.IsDirty = true;
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputEmail8()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcd";
element.IsDirty = true;
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputEmail9()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abc";
element.IsDirty = true;
Assert.AreEqual("email", element.Type);
Assert.AreEqual(true, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputPassword1()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "");
element.Value = "abc";
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputPassword2()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "";
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputPassword3()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcde";
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputPassword4()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcd";
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputPassword5()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abc";
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputPassword6()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcde";
element.IsDirty = true;
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputPassword7()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "AAAAA";
element.IsDirty = true;
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputPassword8()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcd";
element.IsDirty = true;
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortInputPassword9()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abc";
element.IsDirty = true;
Assert.AreEqual("password", element.Type);
Assert.AreEqual(true, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortTextarea1()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "");
element.Value = "abc";
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortTextarea2()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "";
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortTextarea3()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcde";
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortTextarea4()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcd";
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortTextarea5()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abc";
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortTextarea6()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcde";
element.IsDirty = true;
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortTextarea7()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "\r\n\r\n\r\n";
element.IsDirty = true;
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortTextarea8()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abcd";
element.IsDirty = true;
Assert.AreEqual(false, element.Validity.IsTooShort);
}
[Test]
public void TestTooshortTextarea9()
{
var document = ("").ToHtmlDocument();
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("minLength", "4");
element.Value = "abc";
element.IsDirty = true;
Assert.AreEqual(true, element.Validity.IsTooShort);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client;
[TestFixture]
[Category("group1")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientRegionInterestRegexInterest3Tests : ThinClientRegionSteps
{
#region Private members and methods
private UnitProcess m_client1, m_client2, m_client3, m_feeder;
private static string[] m_regexes = { "Key-*1", "Key-*2",
"Key-*3", "Key-*4" };
private const string m_regex23 = "Key-[23]";
private const string m_regexWildcard = "Key-.*";
private const int m_numUnicodeStrings = 5;
private static string[] m_keysNonRegex = { "key-1", "key-2", "key-3" };
private static string[] m_keysForRegex = {"key-regex-1",
"key-regex-2", "key-regex-3" };
private static string[] RegionNamesForInterestNotify =
{ "RegionTrue", "RegionFalse", "RegionOther" };
string GetUnicodeString(int index)
{
return new string('\x0905', 40) + index.ToString("D10");
}
#endregion
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
m_client3 = new UnitProcess();
m_feeder = new UnitProcess();
return new ClientBase[] { m_client1, m_client2, m_client3, m_feeder };
}
[TestFixtureTearDown]
public override void EndTests()
{
CacheHelper.StopJavaServers();
base.EndTests();
}
[TearDown]
public override void EndTest()
{
try
{
m_client1.Call(DestroyRegions);
m_client2.Call(DestroyRegions);
CacheHelper.ClearEndpoints();
}
finally
{
CacheHelper.StopJavaServers();
}
base.EndTest();
}
#region Steps for Thin Client IRegion<object, object> with Interest
public void StepFourIL()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
public void StepFourRegex3()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
try
{
Util.Log("Registering empty regular expression.");
region0.GetSubscriptionService().RegisterRegex(string.Empty);
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
try
{
Util.Log("Registering null regular expression.");
region1.GetSubscriptionService().RegisterRegex(null);
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
try
{
Util.Log("Registering non-existent regular expression.");
region1.GetSubscriptionService().UnregisterRegex("Non*Existent*Regex*");
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
}
public void StepFourFailoverRegex()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
UpdateEntry(m_regionNames[1], m_keys[1], m_vals[1], true);
UnregisterRegexes(null, m_regexes[2]);
}
public void StepFiveIL()
{
VerifyCreated(m_regionNames[0], m_keys[1]);
VerifyCreated(m_regionNames[1], m_keys[3]);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
}
public void StepFiveRegex()
{
CreateEntry(m_regionNames[0], m_keys[2], m_vals[2]);
CreateEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void CreateAllEntries(string regionName)
{
CreateEntry(regionName, m_keys[0], m_vals[0]);
CreateEntry(regionName, m_keys[1], m_vals[1]);
CreateEntry(regionName, m_keys[2], m_vals[2]);
CreateEntry(regionName, m_keys[3], m_vals[3]);
}
public void VerifyAllEntries(string regionName, bool newVal, bool checkVal)
{
string[] vals = newVal ? m_nvals : m_vals;
VerifyEntry(regionName, m_keys[0], vals[0], checkVal);
VerifyEntry(regionName, m_keys[1], vals[1], checkVal);
VerifyEntry(regionName, m_keys[2], vals[2], checkVal);
VerifyEntry(regionName, m_keys[3], vals[3], checkVal);
}
public void VerifyInvalidAll(string regionName, params string[] keys)
{
if (keys != null)
{
foreach (string key in keys)
{
VerifyInvalid(regionName, key);
}
}
}
public void UpdateAllEntries(string regionName, bool checkVal)
{
UpdateEntry(regionName, m_keys[0], m_nvals[0], checkVal);
UpdateEntry(regionName, m_keys[1], m_nvals[1], checkVal);
UpdateEntry(regionName, m_keys[2], m_nvals[2], checkVal);
UpdateEntry(regionName, m_keys[3], m_nvals[3], checkVal);
}
public void DoNetsearchAllEntries(string regionName, bool newVal,
bool checkNoKey)
{
string[] vals;
if (newVal)
{
vals = m_nvals;
}
else
{
vals = m_vals;
}
DoNetsearch(regionName, m_keys[0], vals[0], checkNoKey);
DoNetsearch(regionName, m_keys[1], vals[1], checkNoKey);
DoNetsearch(regionName, m_keys[2], vals[2], checkNoKey);
DoNetsearch(regionName, m_keys[3], vals[3], checkNoKey);
}
public void StepFiveFailoverRegex()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1], false);
}
public void StepSixIL()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(m_regionNames[1]);
region0.Remove(m_keys[1]);
region1.Remove(m_keys[3]);
}
public void StepSixRegex()
{
CreateEntry(m_regionNames[0], m_keys[0], m_vals[0]);
CreateEntry(m_regionNames[1], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UnregisterRegexes(null, m_regexes[3]);
}
public void StepSixFailoverRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2], false);
UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], false);
}
public void StepSevenIL()
{
VerifyDestroyed(m_regionNames[0], m_keys[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void StepSevenRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]);
UpdateEntry(m_regionNames[0], m_keys[2], m_nvals[2], true);
UpdateEntry(m_regionNames[1], m_keys[3], m_nvals[3], true);
UnregisterRegexes(null, m_regexes[1]);
}
public void StepSevenRegex2()
{
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]);
DoNetsearch(m_regionNames[0], m_keys[0], m_vals[0], true);
DoNetsearch(m_regionNames[0], m_keys[3], m_vals[3], true);
UpdateAllEntries(m_regionNames[1], true);
}
public void StepSevenInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().RegisterRegex(m_regex23);
VerifyInvalidAll(m_regionNames[0], m_keys[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3], true);
}
public void StepSevenFailoverRegex()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
UpdateEntry(m_regionNames[1], m_keys[2], m_vals[2], true);
VerifyEntry(m_regionNames[1], m_keys[1], m_nvals[1]);
}
public void StepEightIL()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2]);
}
public void StepEightRegex()
{
VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], true);
UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], true);
}
public void StepEightInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
region.GetSubscriptionService().RegisterAllKeys();
VerifyInvalidAll(m_regionNames[1], m_keys[0], m_keys[1],
m_keys[2], m_keys[3]);
UpdateAllEntries(m_regionNames[0], true);
}
public void StepEightFailoverRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
public void StepNineRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]);
}
public void StepNineRegex2()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[0], m_keys[1], m_nvals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3]);
}
public void StepNineInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().UnregisterRegex(m_regex23);
List<Object> keys = new List<Object>();
keys.Add(m_keys[0]);
keys.Add(m_keys[1]);
keys.Add(m_keys[2]);
region.GetSubscriptionService().RegisterKeys(keys);
VerifyInvalidAll(m_regionNames[0], m_keys[0], m_keys[1], m_keys[2]);
}
public void PutUnicodeKeys(string regionName, bool updates)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string key;
object val;
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
key = GetUnicodeString(index);
if (updates)
{
val = index + 100;
}
else
{
val = (float)index + 20.0F;
}
region[key] = val;
}
}
public void RegisterUnicodeKeys(string regionName)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string[] keys = new string[m_numUnicodeStrings];
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
keys[m_numUnicodeStrings - index - 1] = GetUnicodeString(index);
}
region.GetSubscriptionService().RegisterKeys(keys);
}
public void VerifyUnicodeKeys(string regionName, bool updates)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string key;
object expectedVal;
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
key = GetUnicodeString(index);
if (updates)
{
expectedVal = index + 100;
Assert.AreEqual(expectedVal, region.GetEntry(key).Value,
"Got unexpected value");
}
else
{
expectedVal = (float)index + 20.0F;
Assert.AreEqual(expectedVal, region[key],
"Got unexpected value");
}
}
}
public void CreateRegionsInterestNotify_Pool(string[] regionNames,
string locators, string poolName, bool notify, string nbs)
{
var props = Properties<string, string>.Create();
//props.Insert("notify-by-subscription-override", nbs);
CacheHelper.InitConfig(props);
CacheHelper.CreateTCRegion_Pool(regionNames[0], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
CacheHelper.CreateTCRegion_Pool(regionNames[1], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
CacheHelper.CreateTCRegion_Pool(regionNames[2], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
}
/*
public void CreateRegionsInterestNotify(string[] regionNames,
string endpoints, bool notify, string nbs)
{
Properties props = Properties.Create();
//props.Insert("notify-by-subscription-override", nbs);
CacheHelper.InitConfig(props);
CacheHelper.CreateTCRegion(regionNames[0], true, false,
new TallyListener(), endpoints, notify);
CacheHelper.CreateTCRegion(regionNames[1], true, false,
new TallyListener(), endpoints, notify);
CacheHelper.CreateTCRegion(regionNames[2], true, false,
new TallyListener(), endpoints, notify);
}
* */
public void DoFeed()
{
foreach (string regionName in RegionNamesForInterestNotify)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
foreach (string key in m_keysNonRegex)
{
region[key] = "00";
}
foreach (string key in m_keysForRegex)
{
region[key] = "00";
}
}
}
public void DoFeederOps()
{
foreach (string regionName in RegionNamesForInterestNotify)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
foreach (string key in m_keysNonRegex)
{
region[key] = "11";
region[key] = "22";
region[key] = "33";
region.GetLocalView().Invalidate(key);
region.Remove(key);
}
foreach (string key in m_keysForRegex)
{
region[key] = "11";
region[key] = "22";
region[key] = "33";
region.GetLocalView().Invalidate(key);
region.Remove(key);
}
}
}
public void DoRegister()
{
DoRegisterInterests(RegionNamesForInterestNotify[0], true);
DoRegisterInterests(RegionNamesForInterestNotify[1], false);
// We intentionally do not register interest in Region3
//DoRegisterInterestsBlah(RegionNamesForInterestNotifyBlah[2]);
}
public void DoRegisterInterests(string regionName, bool receiveValues)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
List<string> keys = new List<string>();
foreach (string key in m_keysNonRegex)
{
keys.Add(key);
}
region.GetSubscriptionService().RegisterKeys(keys.ToArray(), false, false, receiveValues);
region.GetSubscriptionService().RegisterRegex("key-regex.*", false, false, receiveValues);
}
public void DoUnregister()
{
DoUnregisterInterests(RegionNamesForInterestNotify[0]);
DoUnregisterInterests(RegionNamesForInterestNotify[1]);
}
public void DoUnregisterInterests(string regionName)
{
List<string> keys = new List<string>();
foreach (string key in m_keysNonRegex)
{
keys.Add(key);
}
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
region.GetSubscriptionService().UnregisterKeys(keys.ToArray());
region.GetSubscriptionService().UnregisterRegex("key-regex.*");
}
public void DoValidation(string clientName, string regionName,
int creates, int updates, int invalidates, int destroys)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
TallyListener<object, object> listener = region.Attributes.CacheListener as TallyListener<object, object>;
Util.Log(clientName + ": " + regionName + ": creates expected=" + creates +
", actual=" + listener.Creates);
Util.Log(clientName + ": " + regionName + ": updates expected=" + updates +
", actual=" + listener.Updates);
Util.Log(clientName + ": " + regionName + ": invalidates expected=" + invalidates +
", actual=" + listener.Invalidates);
Util.Log(clientName + ": " + regionName + ": destroys expected=" + destroys +
", actual=" + listener.Destroys);
Assert.AreEqual(creates, listener.Creates, clientName + ": " + regionName);
Assert.AreEqual(updates, listener.Updates, clientName + ": " + regionName);
Assert.AreEqual(invalidates, listener.Invalidates, clientName + ": " + regionName);
Assert.AreEqual(destroys, listener.Destroys, clientName + ": " + regionName);
}
#endregion
[Test]
public void RegexInterest3()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo complete.");
try {
m_client1.Call(RegisterRegexes, "a*", "*[*2-[");
Assert.Fail("Did not get expected exception!");
} catch (Exception ex) {
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
Util.Log("StepThree complete.");
m_client2.Call(StepFourRegex3);
Util.Log("StepFour complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
}
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using NodaTime.Text;
using NUnit.Framework;
using NodaTime.Test.Calendars;
namespace NodaTime.Test.Text
{
public class YearMonthPatternTest : PatternTestBase<YearMonth>
{
private static readonly YearMonth SampleYearMonth = new YearMonth(1976, 6);
internal static readonly Data[] InvalidPatternData = {
new Data { Pattern = "", Message = TextErrorMessages.FormatStringEmpty },
new Data { Pattern = "!", Message = TextErrorMessages.UnknownStandardFormat, Parameters = {'!', typeof(YearMonth).FullName }},
new Data { Pattern = "%", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { '%', typeof(YearMonth).FullName } },
new Data { Pattern = "\\", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { '\\', typeof(YearMonth).FullName } },
new Data { Pattern = "%%", Message = TextErrorMessages.PercentDoubled },
new Data { Pattern = "%\\", Message = TextErrorMessages.EscapeAtEndOfString },
new Data { Pattern = "MMMMM", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'M', 4 } },
new Data { Pattern = "M%", Message = TextErrorMessages.PercentAtEndOfString },
new Data { Pattern = "yyyyy", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'y', 4 } },
new Data { Pattern = "uuuuu", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'u', 4 } },
new Data { Pattern = "ggg", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'g', 2 } },
new Data { Pattern = "'qwe", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } },
new Data { Pattern = "'qwe\\", Message = TextErrorMessages.EscapeAtEndOfString },
new Data { Pattern = "'qwe\\'", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } },
// Note incorrect use of "u" (year) instead of "y" (year of era)
new Data { Pattern = "MM uuuu gg", Message = TextErrorMessages.EraWithoutYearOfEra },
// Era specifier and calendar specifier in the same pattern.
new Data { Pattern = "MM yyyy gg c", Message = TextErrorMessages.CalendarAndEra },
// Invalid patterns directly after the yyyy specifier. This will detect the issue early, but then
// continue and reject it in the normal path.
new Data { Pattern = "yyyy'", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } },
new Data { Pattern = "yyyy\\", Message = TextErrorMessages.EscapeAtEndOfString },
// Common typo, which is caught in 2.0...
new Data { Pattern = "yyyy-mm", Message = TextErrorMessages.UnquotedLiteral, Parameters = { 'm' } },
// T isn't valid in a year/month pattern
new Data { Pattern = "yyyy-MMT00:00:00", Message = TextErrorMessages.UnquotedLiteral, Parameters = { 'T' } },
// These became invalid in date patterns in v2.0, when we decided that y and yyy weren't sensible.
new Data { Pattern = "y M", Message = TextErrorMessages.InvalidRepeatCount, Parameters = { 'y', 1 } },
new Data { Pattern = "yyy M", Message = TextErrorMessages.InvalidRepeatCount, Parameters = { 'y', 3 } },
};
internal static Data[] ParseFailureData = {
new Data { Pattern = "yyyy gg", Text = "2011 NodaEra", Message = TextErrorMessages.MismatchedText, Parameters = {'g'} },
new Data { Pattern = "yyyy uuuu gg", Text = "0010 0009 B.C.", Message = TextErrorMessages.InconsistentValues2, Parameters = {'g', 'u', typeof(YearMonth)} },
new Data { Pattern = "yyyy MM MMMM", Text = "2011 10 January", Message = TextErrorMessages.InconsistentMonthTextValue },
// Don't match a short name against a long pattern
new Data { Pattern = "yyyy MMMM", Text = "2011 Oct", Message = TextErrorMessages.MismatchedText, Parameters = {'M'} },
// Or vice versa... although this time we match the "Oct" and then fail as we're expecting a space
new Data { Pattern = "MMM yyyy", Text = "October 2011", Message = TextErrorMessages.MismatchedCharacter, Parameters = {' '}},
// Invalid year, year-of-era, month
new Data { Pattern = "yyyy MM", Text = "0000 01", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = { 0, 'y', typeof(YearMonth) } },
new Data { Pattern = "yyyy MM", Text = "2011 15", Message = TextErrorMessages.MonthOutOfRange, Parameters = { 15, 2011 } },
// Year of era can't be negative...
new Data { Pattern = "yyyy MM", Text = "-15 01", Message = TextErrorMessages.UnexpectedNegative },
// Year of era and two-digit year, but they don't match
new Data { Pattern = "uuuu yy", Text = "2011 10", Message = TextErrorMessages.InconsistentValues2, Parameters = { 'y', 'u', typeof(YearMonth) } },
// Invalid calendar name
new Data { Pattern = "c yyyy MM", Text = "2015 01", Message = TextErrorMessages.NoMatchingCalendarSystem },
// Invalid year
new Data { Template = new YearMonth(1, 1, CalendarSystem.IslamicBcl), Pattern = "uuuu", Text = "9999", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = { 9999, 'u', typeof(YearMonth) } },
new Data { Template = new YearMonth(1, 1, CalendarSystem.IslamicBcl), Pattern = "yyyy", Text = "9999", Message = TextErrorMessages.YearOfEraOutOfRange, Parameters = { 9999, "EH", "Hijri" } },
// https://github.com/nodatime/nodatime/issues/414
new Data { Pattern = "yyyy-MM", Text = "1984-00", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = { 0, 'M', typeof(YearMonth) } },
new Data { Pattern = "M/yyyy", Text = "00/1984", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = { 0, 'M', typeof(YearMonth) } },
// Calendar ID parsing is now ordinal, case-sensitive
new Data(2011, 10) { Pattern = "yyyy MM c", Text = "2011 10 iso", Message = TextErrorMessages.NoMatchingCalendarSystem },
};
internal static Data[] ParseOnlyData = {
// Alternative era names
new Data(0, 10) { Pattern = "yyyy MM gg", Text = "0001 10 BCE" },
// Month parsing should be case-insensitive
new Data(2011, 10) { Pattern = "yyyy MMM", Text = "2011 OcT" },
new Data(2011, 10) { Pattern = "yyyy MMMM", Text = "2011 OcToBeR" },
// Genitive name is an extension of the non-genitive name; parse longer first.
// FIXME: Should we be using the genitive name at all?
new Data(2011, 1) { Pattern = "yyyy MMMM", Text = "2011 MonthName-Genitive", Culture = Cultures.GenitiveNameTestCultureWithLeadingNames },
new Data(2011, 1) { Pattern = "yyyy MMMM", Text = "2011 MonthName", Culture = Cultures.GenitiveNameTestCultureWithLeadingNames },
new Data(2011, 1) { Pattern = "yyyy MMM", Text = "2011 MN-Gen", Culture = Cultures.GenitiveNameTestCultureWithLeadingNames },
new Data(2011, 1) { Pattern = "yyyy MMM", Text = "2011 MN", Culture = Cultures.GenitiveNameTestCultureWithLeadingNames },
};
internal static Data[] FormatOnlyData = {
// Would parse back to 2011
new Data(1811, 7) { Pattern = "yy M", Text = "11 7" },
// Tests for the documented 2-digit formatting of BC years
// (Less of an issue since yy became "year of era")
new Data(-94, 7) { Pattern = "yy M", Text = "95 7" },
new Data(-93, 7) { Pattern = "yy M", Text = "94 7" },
};
internal static Data[] FormatAndParseData = {
// Standard patterns
new Data(2011, 10) { Pattern = "g", Text = "2011-10" },
// Custom patterns
new Data(2011, 10) { Pattern = "yyyy/MM", Text = "2011/10" },
new Data(2011, 10) { Pattern = "yyyy/MM", Text = "2011-10", Culture = Cultures.FrCa },
new Data(2011, 10) { Pattern = "yyyyMM", Text = "201110" },
new Data(2001, 7) { Pattern = "yy M", Text = "01 7" },
new Data(2011, 7) { Pattern = "yy M", Text = "11 7" },
new Data(2030, 7) { Pattern = "yy M", Text = "30 7" },
// Cutoff defaults to 30 (at the moment...)
new Data(1931, 7) { Pattern = "yy M", Text = "31 7" },
new Data(1976, 7) { Pattern = "yy M", Text = "76 7" },
// In the first century, we don't skip back a century for "high" two-digit year numbers.
new Data(25, 7) { Pattern = "yy M", Text = "25 7", Template = new YearMonth(50, 1) },
new Data(35, 7) { Pattern = "yy M", Text = "35 7", Template = new YearMonth(50, 1) },
new Data(2000, 10) { Pattern = "MM", Text = "10"},
new Data(1885, 10) { Pattern = "MM", Text = "10", Template = new YearMonth(1885, 10) },
// When we parse in all of the below tests, we'll use the month and day-of-month if it's provided;
// the template value is specified to allow simple roundtripping. (Day of week doesn't affect what value is parsed; it just validates.)
// Non-genitive month name when there's no "day of month", even if there's a "day of week"
new Data(2011, 1) { Pattern = "MMMM", Text = "FullNonGenName", Culture = Cultures.GenitiveNameTestCulture, Template = new YearMonth(2011, 5)},
new Data(2011, 1) { Pattern = "MMM", Text = "AbbrNonGenName", Culture = Cultures.GenitiveNameTestCulture, Template = new YearMonth(2011, 5) },
// Era handling
new Data(2011, 1) { Pattern = "yyyy MM gg", Text = "2011 01 A.D." },
new Data(2011, 1) { Pattern = "uuuu yyyy MM gg", Text = "2011 2011 01 A.D." },
new Data(-1, 1) { Pattern = "yyyy MM gg", Text = "0002 01 B.C." },
// Month handling
new Data(2011, 10) { Pattern = "yyyy MMMM", Text = "2011 October" },
new Data(2011, 10) { Pattern = "yyyy MMM", Text = "2011 Oct" },
// Year and two-digit year-of-era in the same format. Note that the year
// gives the full year information, so we're not stuck in the 20th/21st century
new Data(1825, 10) { Pattern = "uuuu yy MM", Text = "1825 25 10" },
// Negative years
new Data(-43, 3) { Pattern = "uuuu MM", Text = "-0043 03"},
// Calendar handling
new Data(2011, 10) { Pattern = "c yyyy MM", Text = "ISO 2011 10" },
new Data(2011, 10) { Pattern = "yyyy MM c", Text = "2011 10 ISO" },
new Data(2011, 10, CalendarSystem.Coptic) { Pattern = "c uuuu MM", Text = "Coptic 2011 10" },
new Data(2011, 10, CalendarSystem.Coptic) { Pattern = "uuuu MM c", Text = "2011 10 Coptic" },
new Data(180, 15, CalendarSystem.Badi) { Pattern = "uuuu MM c", Text = "0180 15 Badi" },
// 3 digit year patterns (odd, but valid)
new Data(12, 1) { Pattern = "uuu MM", Text = "012 01" },
new Data(-12, 1) { Pattern = "uuu MM", Text = "-012 01" },
new Data(123, 1) { Pattern = "uuu MM", Text = "123 01" },
new Data(-123, 1) { Pattern = "uuu MM", Text = "-123 01" },
new Data(1234, 1) { Pattern = "uuu MM", Text = "1234 01" },
new Data(-1234, 1) { Pattern = "uuu MM", Text = "-1234 01" },
};
internal static IEnumerable<Data> ParseData = ParseOnlyData.Concat(FormatAndParseData);
internal static IEnumerable<Data> FormatData = FormatOnlyData.Concat(FormatAndParseData);
[Test]
public void CreateWithCurrentCulture()
{
var yearMonth = new YearMonth(2017, 8);
using (CultureSaver.SetCultures(Cultures.EnUs))
{
var pattern = YearMonthPattern.CreateWithCurrentCulture("yyyy/MM");
Assert.AreEqual("2017/08", pattern.Format(yearMonth));
}
using (CultureSaver.SetCultures(Cultures.FrCa))
{
var pattern = YearMonthPattern.CreateWithCurrentCulture("yyyy/MM");
Assert.AreEqual("2017-08", pattern.Format(yearMonth));
}
}
[Test]
public void CreateWithSpecificCulture()
{
var pattern = YearMonthPattern.Create("yyyy/MM", Cultures.FrCa);
Assert.AreEqual("2017-08", pattern.Format(new YearMonth(2017, 8)));
}
[Test]
public void CreateWithTemplateValue()
{
// This is testing the Create call specifying the template directly, instead of the WithTemplate method
var template = new YearMonth(2000, 6);
var pattern = YearMonthPattern.Create("yyyy", CultureInfo.InvariantCulture, template);
Assert.AreEqual(template, pattern.TemplateValue);
var parseResult = pattern.Parse("1990");
Assert.True(parseResult.Success);
Assert.AreEqual(new YearMonth(1990, 6), parseResult.Value);
}
[Test]
public void ParseNull() => AssertParseNull(YearMonthPattern.Iso);
public sealed class Data : PatternTestData<YearMonth>
{
// Default to the start of the year 2000.
protected override YearMonth DefaultTemplate => YearMonthPattern.DefaultTemplateValue;
/// <summary>
/// Initializes a new instance of the <see cref="Data" /> class.
/// </summary>
/// <param name="value">The value.</param>
public Data(YearMonth value) : base(value)
{
}
public Data(int year, int month) : this(new YearMonth(year, month))
{
}
public Data(int year, int month, CalendarSystem calendar)
: this(new YearMonth(year, month, calendar))
{
}
public Data() : this(YearMonthPattern.DefaultTemplateValue)
{
}
internal override IPattern<YearMonth> CreatePattern() =>
YearMonthPattern.CreateWithInvariantCulture(Pattern!)
.WithTemplateValue(Template)
.WithCulture(Culture);
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// SpscTargetCore.cs
//
//
// A fast single-producer-single-consumer core for a target block.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security;
#pragma warning disable 0420 // turn off warning for passing volatiles to interlocked operations
namespace System.Threading.Tasks.Dataflow.Internal
{
// SpscTargetCore provides a fast target core for use in blocks that will only have single-producer-single-consumer
// semantics. Blocks configured with the default DOP==1 will be single consumer, so whether this core may be
// used is largely up to whether the block is also single-producer. The ExecutionDataflowBlockOptions.SingleProducerConstrained
// option can be used by a developer to inform a block that it will only be accessed by one producer at a time,
// and a block like ActionBlock can utilize that knowledge to choose this target instead of the default TargetCore.
// However, there are further constraints that might prevent this core from being used.
// - If the user specifies a CancellationToken, this core can't be used, as the cancellation request
// could come in concurrently with the single producer accessing the block, thus resulting in multiple producers.
// - If the user specifies a bounding capacity, this core can't be used, as the consumer processing items
// needs to synchronize with producers around the change in bounding count, and the consumer is again
// in effect another producer.
// - If the block has a source half (e.g. TransformBlock) and that source could potentially call back
// to the target half to, for example, notify it of exceptions occurring, again there would potentially
// be multiple producers.
// Thus, when and how this SpscTargetCore may be applied is significantly constrained.
/// <summary>
/// Provides a core implementation of <see cref="ITargetBlock{TInput}"/> for use when there's only a single producer posting data.
/// </summary>
/// <typeparam name="TInput">Specifies the type of data accepted by the <see cref="TargetCore{TInput}"/>.</typeparam>
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
internal sealed class SpscTargetCore<TInput>
{
/// <summary>The target block using this helper.</summary>
private readonly ITargetBlock<TInput> _owningTarget;
/// <summary>The messages in this target.</summary>
private readonly SingleProducerSingleConsumerQueue<TInput> _messages = new SingleProducerSingleConsumerQueue<TInput>();
/// <summary>The options to use to configure this block. The target core assumes these options are immutable.</summary>
private readonly ExecutionDataflowBlockOptions _dataflowBlockOptions;
/// <summary>An action to invoke for every accepted message.</summary>
private readonly Action<TInput> _action;
/// <summary>Exceptions that may have occurred and gone unhandled during processing. This field is lazily initialized.</summary>
private volatile List<Exception> _exceptions;
/// <summary>Whether to stop accepting new messages.</summary>
private volatile bool _decliningPermanently;
/// <summary>A task has reserved the right to run the completion routine.</summary>
private volatile bool _completionReserved;
/// <summary>
/// The Task currently active to process the block. This field is used to synchronize between producer and consumer,
/// and it should not be set to null once the block completes, as doing so would allow for races where the producer
/// gets another consumer task queued even though the block has completed.
/// </summary>
private volatile Task _activeConsumer;
/// <summary>A task representing the completion of the block. This field is lazily initialized.</summary>
private TaskCompletionSource<VoidResult> _completionTask;
/// <summary>Initialize the SPSC target core.</summary>
/// <param name="owningTarget">The owning target block.</param>
/// <param name="action">The action to be invoked for every message.</param>
/// <param name="dataflowBlockOptions">The options to use to configure this block. The target core assumes these options are immutable.</param>
internal SpscTargetCore(
ITargetBlock<TInput> owningTarget, Action<TInput> action, ExecutionDataflowBlockOptions dataflowBlockOptions)
{
Debug.Assert(owningTarget != null, "Expected non-null owningTarget");
Debug.Assert(action != null, "Expected non-null action");
Debug.Assert(dataflowBlockOptions != null, "Expected non-null dataflowBlockOptions");
_owningTarget = owningTarget;
_action = action;
_dataflowBlockOptions = dataflowBlockOptions;
}
internal bool Post(TInput messageValue)
{
if (_decliningPermanently)
return false;
// Store the offered message into the queue.
_messages.Enqueue(messageValue);
Interlocked.MemoryBarrier(); // ensure the read of _activeConsumer doesn't move up before the writes in Enqueue
// Make sure there's an active task available to handle processing this message. If we find the task
// is null, we'll try to schedule one using an interlocked operation. If we find the task is non-null,
// then there must be a task actively running. If there's a race where the task is about to complete
// and nulls out its reference (using a barrier), it'll subsequently check whether there are any messages in the queue,
// and since we put the messages into the queue before now, it'll find them and use an interlocked
// to re-launch itself.
if (_activeConsumer == null)
{
ScheduleConsumerIfNecessary(false);
}
return true;
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' />
internal DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, bool consumeToAccept)
{
// If we're not required to go back to the source to consume the offered message, try fast path.
return !consumeToAccept && Post(messageValue) ?
DataflowMessageStatus.Accepted :
OfferMessage_Slow(messageHeader, messageValue, source, consumeToAccept);
}
/// <summary>Implements the slow path for OfferMessage.</summary>
/// <param name="messageHeader">The message header for the offered value.</param>
/// <param name="messageValue">The offered value.</param>
/// <param name="source">The source offering the message. This may be null.</param>
/// <param name="consumeToAccept">true if we need to call back to the source to consume the message; otherwise, false if we can simply accept it directly.</param>
/// <returns>The status of the message.</returns>
private DataflowMessageStatus OfferMessage_Slow(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, bool consumeToAccept)
{
// If we're declining permanently, let the caller know.
if (_decliningPermanently)
{
return DataflowMessageStatus.DecliningPermanently;
}
// If the message header is invalid, throw.
if (!messageHeader.IsValid)
{
throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
}
// If the caller has requested we consume the message using ConsumeMessage, do so.
if (consumeToAccept)
{
if (source == null) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept));
bool consumed;
messageValue = source.ConsumeMessage(messageHeader, _owningTarget, out consumed);
if (!consumed) return DataflowMessageStatus.NotAvailable;
}
// See the "fast path" comments in Post
_messages.Enqueue(messageValue);
Interlocked.MemoryBarrier(); // ensure the read of _activeConsumer doesn't move up before the writes in Enqueue
if (_activeConsumer == null)
{
ScheduleConsumerIfNecessary(isReplica: false);
}
return DataflowMessageStatus.Accepted;
}
/// <summary>Schedules a consumer task if there's none currently running.</summary>
/// <param name="isReplica">Whether the new consumer is being scheduled to replace a currently running consumer.</param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private void ScheduleConsumerIfNecessary(bool isReplica)
{
// If there's currently no active task...
if (_activeConsumer == null)
{
// Create a new consumption task and try to set it as current as long as there's still no other task
var newConsumer = new Task(
state => ((SpscTargetCore<TInput>)state).ProcessMessagesLoopCore(),
this, CancellationToken.None, Common.GetCreationOptionsForTask(isReplica));
if (Interlocked.CompareExchange(ref _activeConsumer, newConsumer, null) == null)
{
// We won the race. This task is now the consumer.
#if FEATURE_TRACING
DataflowEtwProvider etwLog = DataflowEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TaskLaunchedForMessageHandling(
_owningTarget, newConsumer, DataflowEtwProvider.TaskLaunchedReason.ProcessingInputMessages, _messages.Count);
}
#endif
// Start the task. In the erroneous case where the scheduler throws an exception,
// just allow it to propagate. Our other option would be to fault the block with
// that exception, but in order for the block to complete we need to schedule a consumer
// task to do so, and it's very likely that if the scheduler is throwing an exception
// now, it would do so again.
newConsumer.Start(_dataflowBlockOptions.TaskScheduler);
}
}
}
/// <summary>Task body used to process messages.</summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ProcessMessagesLoopCore()
{
Debug.Assert(
_activeConsumer != null && _activeConsumer.Id == Task.CurrentId,
"This method should only be called when it's the active consumer.");
int messagesProcessed = 0;
int maxMessagesToProcess = _dataflowBlockOptions.ActualMaxMessagesPerTask;
// Continue processing as long as there's more processing to be done
bool continueProcessing = true;
while (continueProcessing)
{
continueProcessing = false;
TInput nextMessage = default(TInput);
try
{
// While there are more messages to be processed, process each one.
// NOTE: This loop is critical for performance. It must be super lean.
while (
_exceptions == null &&
messagesProcessed < maxMessagesToProcess &&
_messages.TryDequeue(out nextMessage))
{
messagesProcessed++; // done before _action invoked in case it throws exception
_action(nextMessage);
}
}
catch (Exception exc)
{
// If the exception is for cancellation, just ignore it.
// Otherwise, store it, and the finally block will handle completion.
if (!Common.IsCooperativeCancellation(exc))
{
_decliningPermanently = true; // stop accepting from producers
Common.StoreDataflowMessageValueIntoExceptionData<TInput>(exc, nextMessage, false);
StoreException(exc);
}
}
finally
{
// If more messages just arrived and we should still process them,
// loop back around and keep going.
if (!_messages.IsEmpty && _exceptions == null && (messagesProcessed < maxMessagesToProcess))
{
continueProcessing = true;
}
else
{
// If messages are being declined and we're empty, or if there's an exception,
// then there's no more work to be done and we should complete the block.
bool wasDecliningPermanently = _decliningPermanently;
if ((wasDecliningPermanently && _messages.IsEmpty) || _exceptions != null)
{
// Complete the block, as long as we're not already completing or completed.
if (!_completionReserved) // no synchronization necessary; this can't happen concurrently
{
_completionReserved = true;
CompleteBlockOncePossible();
}
}
else
{
// Mark that we're exiting.
Task previousConsumer = Interlocked.Exchange(ref _activeConsumer, null);
Debug.Assert(previousConsumer != null && previousConsumer.Id == Task.CurrentId,
"The running task should have been denoted as the active task.");
// Now that we're no longer the active task, double
// check to make sure there's really nothing to do,
// which could include processing more messages or completing.
// If there is more to do, schedule a task to try to do it.
// This is to handle a race with Post/Complete/Fault and this
// task completing.
if (!_messages.IsEmpty || // messages to be processed
(!wasDecliningPermanently && _decliningPermanently) || // potentially completion to be processed
_exceptions != null) // exceptions/completion to be processed
{
ScheduleConsumerIfNecessary(isReplica: true);
}
}
}
}
}
}
/// <summary>Gets the number of messages waiting to be processed.</summary>
internal int InputCount { get { return _messages.Count; } }
/// <summary>
/// Completes the target core. If an exception is provided, the block will end up in a faulted state.
/// If Complete is invoked more than once, or if it's invoked after the block is already
/// completing, all invocations after the first are ignored.
/// </summary>
/// <param name="exception">The exception to be stored.</param>
internal void Complete(Exception exception)
{
// If we're not yet declining permanently...
if (!_decliningPermanently)
{
// Mark us as declining permanently, and then kick off a processing task
// if we need one. It's this processing task's job to complete the block
// once all data has been consumed and/or we're in a valid state for completion.
if (exception != null) StoreException(exception);
_decliningPermanently = true;
ScheduleConsumerIfNecessary(isReplica: false);
}
}
/// <summary>
/// Ensures the exceptions list is initialized and stores the exception into the list using a lock.
/// </summary>
/// <param name="exception">The exception to store.</param>
private void StoreException(Exception exception)
{
// Ensure that the _exceptions field has been initialized.
// We need to synchronize the initialization and storing of
// the exception because this method could be accessed concurrently
// by the producer and consumer, a producer calling Fault and the
// processing task processing the user delegate which might throw.
lock (LazyInitializer.EnsureInitialized(ref _exceptions, () => new List<Exception>()))
{
_exceptions.Add(exception);
}
}
/// <summary>
/// Completes the block. This must only be called once, and only once all of the completion conditions are met.
/// </summary>
private void CompleteBlockOncePossible()
{
Debug.Assert(_completionReserved, "Should only invoke once completion has been reserved.");
// Dump any messages that might remain in the queue, which could happen if we completed due to exceptions.
TInput dumpedMessage;
while (_messages.TryDequeue(out dumpedMessage)) ;
// Complete the completion task
bool result;
if (_exceptions != null)
{
Exception[] exceptions;
lock (_exceptions) exceptions = _exceptions.ToArray();
result = CompletionSource.TrySetException(exceptions);
}
else
{
result = CompletionSource.TrySetResult(default(VoidResult));
}
Debug.Assert(result, "Expected completion task to not yet be completed");
// We explicitly do not set the _activeTask to null here, as that would
// allow for races where a producer calling OfferMessage could end up
// seeing _activeTask as null and queueing a new consumer task even
// though the block has completed.
#if FEATURE_TRACING
DataflowEtwProvider etwLog = DataflowEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.DataflowBlockCompleted(_owningTarget);
}
#endif
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
internal Task Completion { get { return CompletionSource.Task; } }
/// <summary>Gets the lazily-initialized completion source.</summary>
private TaskCompletionSource<VoidResult> CompletionSource
{
get { return LazyInitializer.EnsureInitialized(ref _completionTask, () => new TaskCompletionSource<VoidResult>()); }
}
/// <summary>Gets the DataflowBlockOptions used to configure this block.</summary>
internal ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _dataflowBlockOptions; } }
/// <summary>Gets information about this helper to be used for display in a debugger.</summary>
/// <returns>Debugging information about this target.</returns>
internal DebuggingInformation GetDebuggingInformation() { return new DebuggingInformation(this); }
/// <summary>Gets the object to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
var displayTarget = _owningTarget as IDebuggerDisplay;
return string.Format("Block=\"{0}\"",
displayTarget != null ? displayTarget.Content : _owningTarget);
}
}
/// <summary>Provides a wrapper for commonly needed debugging information.</summary>
internal sealed class DebuggingInformation
{
/// <summary>The target being viewed.</summary>
private readonly SpscTargetCore<TInput> _target;
/// <summary>Initializes the debugging helper.</summary>
/// <param name="target">The target being viewed.</param>
internal DebuggingInformation(SpscTargetCore<TInput> target) { _target = target; }
/// <summary>Gets the messages waiting to be processed.</summary>
internal IEnumerable<TInput> InputQueue { get { return _target._messages.ToList(); } }
/// <summary>Gets the current number of outstanding input processing operations.</summary>
internal Int32 CurrentDegreeOfParallelism { get { return _target._activeConsumer != null && !_target.Completion.IsCompleted ? 1 : 0; } }
/// <summary>Gets the DataflowBlockOptions used to configure this block.</summary>
internal ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _target._dataflowBlockOptions; } }
/// <summary>Gets whether the block is declining further messages.</summary>
internal bool IsDecliningPermanently { get { return _target._decliningPermanently; } }
/// <summary>Gets whether the block is completed.</summary>
internal bool IsCompleted { get { return _target.Completion.IsCompleted; } }
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using FileHelpers.Helpers;
namespace FileHelpers.Options
{
using System.Collections.Generic;
/// <summary>
/// This class allows you to set some options of the records at runtime.
/// With these options the library is now more flexible than ever.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public abstract class RecordOptions
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal IRecordInfo mRecordInfo;
/// <summary>
/// This class allows you to set some options of the records at runtime.
/// With these options the library is now more flexible than ever.
/// </summary>
/// <param name="info">Record information</param>
internal RecordOptions(IRecordInfo info)
{
mRecordInfo = info;
mRecordConditionInfo = new RecordConditionInfo(info);
mIgnoreCommentInfo = new IgnoreCommentInfo(info);
}
/// <summary>
/// Copies the fields in the current recordinfo.
/// </summary>
[Pure]
public FieldBaseCollection Fields
{
get { return new FieldBaseCollection(mRecordInfo.Fields); }
}
/// <summary>
/// Removes the filed from the underlying <seealso cref="IRecordInfo"/>.
/// </summary>
public void RemoveField(string fieldname)
{
mRecordInfo.RemoveField(fieldname);
}
/// <summary>
/// The number of fields of the record type.
/// </summary>
public int FieldCount
{
get { return mRecordInfo.FieldCount; }
}
// <summary>The number of fields of the record type.</summary>
//[System.Runtime.CompilerServices.IndexerName("FieldNames")]
//public string this[int index]
//{
// get
// {
// return mRecordInfo.mFields[index].mFieldInfo.Name;
// }
//}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string[] mFieldNames;
/// <summary>
/// Returns an string array with the fields names.
/// Note : Do NOT change the values of the array, clone it first if needed
/// </summary>
/// <returns>An string array with the fields names.</returns>
public string[] FieldsNames
{
get
{
if (mFieldNames == null) {
mFieldNames = new string[mRecordInfo.FieldCount];
for (int i = 0; i < mFieldNames.Length; i++)
mFieldNames[i] = mRecordInfo.Fields[i].FieldFriendlyName;
}
return mFieldNames;
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private Type[] mFieldTypes;
/// <summary>
/// Returns a Type[] array with the fields types.
/// Note : Do NOT change the values of the array, clone it first if
/// needed
/// </summary>
/// <returns>An Type[] array with the fields types.</returns>
public Type[] FieldsTypes
{
get
{
if (mFieldTypes == null) {
mFieldTypes = new Type[mRecordInfo.FieldCount];
for (int i = 0; i < mFieldTypes.Length; i++)
mFieldTypes[i] = mRecordInfo.Fields[i].FieldInfo.FieldType;
}
return mFieldTypes;
}
}
// /// <summary>Returns the type of the field at the specified index</summary>
// /// <returns>The type of the field.</returns>
// /// <param name="index">The index of the field</param>
// public Type GetFieldType(int index)
// {
// return mRecordInfo.mFields[index].mFieldInfo.FieldType;
// }
/// <summary>
/// Indicates the number of first lines to be discarded.
/// </summary>
public int IgnoreFirstLines
{
get { return mRecordInfo.IgnoreFirst; }
set
{
ExHelper.PositiveValue(value);
mRecordInfo.IgnoreFirst = value;
}
}
/// <summary>
/// Indicates the number of lines at the end of file to be discarded.
/// </summary>
public int IgnoreLastLines
{
get { return mRecordInfo.IgnoreLast; }
set
{
ExHelper.PositiveValue(value);
mRecordInfo.IgnoreLast = value;
}
}
/// <summary>
/// Indicates that the engine must ignore the empty lines while
/// reading.
/// </summary>
public bool IgnoreEmptyLines
{
get { return mRecordInfo.IgnoreEmptyLines; }
set { mRecordInfo.IgnoreEmptyLines = value; }
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly RecordConditionInfo mRecordConditionInfo;
/// <summary>
/// Used to tell the engine which records must be included or excluded
/// while reading.
/// </summary>
public RecordConditionInfo RecordCondition
{
get { return mRecordConditionInfo; }
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly IgnoreCommentInfo mIgnoreCommentInfo;
/// <summary>
/// Indicates that the engine must ignore the lines with this comment
/// marker.
/// </summary>
public IgnoreCommentInfo IgnoreCommentedLines
{
get { return mIgnoreCommentInfo; }
}
/// <summary>
/// Used to tell the engine which records must be included or excluded
/// while reading.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public sealed class RecordConditionInfo
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly IRecordInfo mRecordInfo;
/// <summary>
/// Used to tell the engine which records must be included or
/// excluded while reading.
/// </summary>
/// <param name="ri">Record information</param>
internal RecordConditionInfo(IRecordInfo ri)
{
mRecordInfo = ri;
}
/// <summary>
/// The condition used to include or exclude records.
/// </summary>
public RecordCondition Condition
{
get { return mRecordInfo.RecordCondition; }
set { mRecordInfo.RecordCondition = value; }
}
/// <summary>
/// The selector used by the <see cref="RecordCondition"/>.
/// </summary>
public string Selector
{
get { return mRecordInfo.RecordConditionSelector; }
set { mRecordInfo.RecordConditionSelector = value; }
}
}
/// <summary>
/// Indicates that the engine must ignore the lines with this comment
/// marker.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public sealed class IgnoreCommentInfo
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly IRecordInfo mRecordInfo;
/// <summary>
/// Indicates that the engine must ignore the lines with this
/// comment marker.
/// </summary>
/// <param name="ri">Record information</param>
internal IgnoreCommentInfo(IRecordInfo ri)
{
mRecordInfo = ri;
}
/// <summary>
/// <para>Indicates that the engine must ignore the lines with this
/// comment marker.</para>
/// <para>An empty string or null indicates that the engine doesn't
/// look for comments</para>
/// </summary>
public string CommentMarker
{
get { return mRecordInfo.CommentMarker; }
set
{
if (value != null)
value = value.Trim();
mRecordInfo.CommentMarker = value;
}
}
/// <summary>
/// Indicates if the comment can have spaces or tabs at left (true
/// by default)
/// </summary>
public bool InAnyPlace
{
get { return mRecordInfo.CommentAnyPlace; }
set { mRecordInfo.CommentAnyPlace = value; }
}
}
/// <summary>
/// Allows the creating of a record string of the given record. Is
/// useful when your want to log errors to a plan text file or database
/// </summary>
/// <param name="record">
/// The record that will be transformed to string
/// </param>
/// <returns>The string representation of the current record</returns>
public string RecordToString(object record)
{
return mRecordInfo.Operations.RecordToString(record);
}
/// <summary>
/// Allows to get an object[] with the values of the fields in the <paramref name="record"/>
/// </summary>
/// <param name="record">The record that will be transformed to object[]</param>
/// <returns>The object[] with the values of the fields in the current record</returns>
public object[] RecordToValues(object record)
{
return mRecordInfo.Operations.RecordToValues(record);
}
}
/// <summary>An amount of <seealso cref="FieldBase"/>.</summary>
public sealed class FieldBaseCollection
: List<FieldBase>
{
internal FieldBaseCollection(FieldBase[] fields)
: base(fields) {}
}
}
| |
// 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.Net.Sockets;
using System.Globalization;
namespace System.Net
{
/// <devdoc>
/// <para>
/// Provides an IP address.
/// </para>
/// </devdoc>
public class IPEndPoint : EndPoint
{
/// <devdoc>
/// <para>
/// Specifies the minimum acceptable value for the <see cref='System.Net.IPEndPoint.Port'/>
/// property.
/// </para>
/// </devdoc>
public const int MinPort = 0x00000000;
/// <devdoc>
/// <para>
/// Specifies the maximum acceptable value for the <see cref='System.Net.IPEndPoint.Port'/>
/// property.
/// </para>
/// </devdoc>
public const int MaxPort = 0x0000FFFF;
private IPAddress _address;
private int _port;
internal const int AnyPort = MinPort;
internal static IPEndPoint Any = new IPEndPoint(IPAddress.Any, AnyPort);
internal static IPEndPoint IPv6Any = new IPEndPoint(IPAddress.IPv6Any, AnyPort);
public override AddressFamily AddressFamily
{
get
{
// IPv6 Changes: Always delegate this to the address we are wrapping.
return _address.AddressFamily;
}
}
/// <devdoc>
/// <para>
/// Creates a new instance of the IPEndPoint class with the specified address and port.
/// </para>
/// </devdoc>
public IPEndPoint(long address, int port)
{
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
_port = port;
_address = new IPAddress(address);
}
/// <devdoc>
/// <para>
/// Creates a new instance of the IPEndPoint class with the specified address and port.
/// </para>
/// </devdoc>
public IPEndPoint(IPAddress address, int port)
{
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
_port = port;
_address = address;
}
/// <devdoc>
/// <para>
/// Gets or sets the IP address.
/// </para>
/// </devdoc>
public IPAddress Address
{
get
{
return _address;
}
set
{
_address = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the port.
/// </para>
/// </devdoc>
public int Port
{
get
{
return _port;
}
set
{
if (!TcpValidationHelpers.ValidatePortNumber(value))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_port = value;
}
}
public static bool TryParse(string s, out IPEndPoint result)
{
return TryParse(s.AsSpan(), out result);
}
public static bool TryParse(ReadOnlySpan<char> s, out IPEndPoint result)
{
int addressLength = s.Length; // If there's no port then send the entire string to the address parser
int lastColonPos = s.LastIndexOf(':');
// Look to see if this is an IPv6 address with a port.
if (lastColonPos > 0)
{
if (s[lastColonPos - 1] == ']')
{
addressLength = lastColonPos;
}
// Look to see if this is IPv4 with a port (IPv6 will have another colon)
else if (s.Slice(0, lastColonPos).LastIndexOf(':') == -1)
{
addressLength = lastColonPos;
}
}
if (IPAddress.TryParse(s.Slice(0, addressLength), out IPAddress address))
{
uint port = 0;
if (addressLength == s.Length ||
(uint.TryParse(s.Slice(addressLength + 1), NumberStyles.None, CultureInfo.InvariantCulture, out port) && port <= MaxPort))
{
result = new IPEndPoint(address, (int)port);
return true;
}
}
result = null;
return false;
}
public static IPEndPoint Parse(string s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
return Parse(s.AsSpan());
}
public static IPEndPoint Parse(ReadOnlySpan<char> s)
{
if (TryParse(s, out IPEndPoint result))
{
return result;
}
throw new FormatException(SR.bad_endpoint_string);
}
public override string ToString()
{
string format = (_address.AddressFamily == AddressFamily.InterNetworkV6) ? "[{0}]:{1}" : "{0}:{1}";
return string.Format(format, _address.ToString(), Port.ToString(NumberFormatInfo.InvariantInfo));
}
public override SocketAddress Serialize()
{
// Let SocketAddress do the bulk of the work
return new SocketAddress(Address, Port);
}
public override EndPoint Create(SocketAddress socketAddress)
{
// Validate SocketAddress
if (socketAddress.Family != this.AddressFamily)
{
throw new ArgumentException(SR.Format(SR.net_InvalidAddressFamily, socketAddress.Family.ToString(), this.GetType().FullName, this.AddressFamily.ToString()), nameof(socketAddress));
}
if (socketAddress.Size < 8)
{
throw new ArgumentException(SR.Format(SR.net_InvalidSocketAddressSize, socketAddress.GetType().FullName, this.GetType().FullName), nameof(socketAddress));
}
return socketAddress.GetIPEndPoint();
}
public override bool Equals(object comparand)
{
return comparand is IPEndPoint other && other._address.Equals(_address) && other._port == _port;
}
public override int GetHashCode()
{
return _address.GetHashCode() ^ _port;
}
}
}
| |
/*
* 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.Net;
using System.Reflection;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules.Avatar.Chat
{
public class IRCBridgeModule : INonSharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
internal static bool m_pluginEnabled = false;
internal static IConfig m_config = null;
internal static List<ChannelState> m_channels = new List<ChannelState>();
internal static List<RegionState> m_regions = new List<RegionState>();
internal static string m_password = String.Empty;
internal RegionState m_region = null;
#region INonSharedRegionModule Members
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "IRCBridgeModule"; }
}
public void Initialise(IConfigSource config)
{
m_config = config.Configs["IRC"];
if (m_config == null)
{
m_log.InfoFormat("[IRC-Bridge] module not configured");
return;
}
if (!m_config.GetBoolean("enabled", false))
{
m_log.InfoFormat("[IRC-Bridge] module disabled in configuration");
return;
}
if (config.Configs["RemoteAdmin"] != null)
{
m_password = config.Configs["RemoteAdmin"].GetString("access_password", m_password);
}
m_pluginEnabled = true;
}
public void AddRegion(Scene scene)
{
if (m_pluginEnabled)
{
try
{
m_log.InfoFormat("[IRC-Bridge] Connecting region {0}", scene.RegionInfo.RegionName);
if (!String.IsNullOrEmpty(m_password))
MainServer.Instance.AddXmlRPCHandler("irc_admin", XmlRpcAdminMethod, false);
m_region = new RegionState(scene, m_config);
lock (m_regions) m_regions.Add(m_region);
m_region.Open();
}
catch (Exception e)
{
m_log.WarnFormat("[IRC-Bridge] Region {0} not connected to IRC : {1}", scene.RegionInfo.RegionName, e.Message);
m_log.Debug(e);
}
}
else
{
m_log.WarnFormat("[IRC-Bridge] Not enabled. Connect for region {0} ignored", scene.RegionInfo.RegionName);
}
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
if (!m_pluginEnabled)
return;
if (m_region == null)
return;
if (!String.IsNullOrEmpty(m_password))
MainServer.Instance.RemoveXmlRPCHandler("irc_admin");
m_region.Close();
if (m_regions.Contains(m_region))
{
lock (m_regions) m_regions.Remove(m_region);
}
}
public void Close()
{
}
#endregion
public static XmlRpcResponse XmlRpcAdminMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
m_log.Info("[IRC-Bridge]: XML RPC Admin Entry");
XmlRpcResponse response = new XmlRpcResponse();
Hashtable responseData = new Hashtable();
try
{
Hashtable requestData = (Hashtable)request.Params[0];
bool found = false;
string region = String.Empty;
if (m_password != String.Empty)
{
if (!requestData.ContainsKey("password"))
throw new Exception("Invalid request");
if ((string)requestData["password"] != m_password)
throw new Exception("Invalid request");
}
if (!requestData.ContainsKey("region"))
throw new Exception("No region name specified");
region = (string)requestData["region"];
foreach (RegionState rs in m_regions)
{
if (rs.Region == region)
{
responseData["server"] = rs.cs.Server;
responseData["port"] = (int)rs.cs.Port;
responseData["user"] = rs.cs.User;
responseData["channel"] = rs.cs.IrcChannel;
responseData["enabled"] = rs.cs.irc.Enabled;
responseData["connected"] = rs.cs.irc.Connected;
responseData["nickname"] = rs.cs.irc.Nick;
found = true;
break;
}
}
if (!found) throw new Exception(String.Format("Region <{0}> not found", region));
responseData["success"] = true;
}
catch (Exception e)
{
m_log.InfoFormat("[IRC-Bridge] XML RPC Admin request failed : {0}", e.Message);
responseData["success"] = "false";
responseData["error"] = e.Message;
}
finally
{
response.Value = responseData;
}
m_log.Debug("[IRC-Bridge]: XML RPC Admin Exit");
return response;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Network;
using Microsoft.WindowsAzure.Management.Network.Models;
namespace Microsoft.WindowsAzure.Management.Network
{
/// <summary>
/// The Network Management API includes operations for managing the IP
/// Forwarding for your roles and network interfaces in your subscription.
/// </summary>
internal partial class IPForwardingOperations : IServiceOperations<NetworkManagementClient>, IIPForwardingOperations
{
/// <summary>
/// Initializes a new instance of the IPForwardingOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal IPForwardingOperations(NetworkManagementClient client)
{
this._client = client;
}
private NetworkManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Network.NetworkManagementClient.
/// </summary>
public NetworkManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Sets IP Forwarding on a network interface.
/// </summary>
/// <param name='serviceName'>
/// Required.
/// </param>
/// <param name='deploymentName'>
/// Required.
/// </param>
/// <param name='roleName'>
/// Required.
/// </param>
/// <param name='networkInterfaceName'>
/// Required.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Set IP Forwarding on network
/// interface operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginSettingIPForwardingOnNetworkInterfaceAsync(string serviceName, string deploymentName, string roleName, string networkInterfaceName, IPForwardingSetParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (roleName == null)
{
throw new ArgumentNullException("roleName");
}
if (networkInterfaceName == null)
{
throw new ArgumentNullException("networkInterfaceName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.State == null)
{
throw new ArgumentNullException("parameters.State");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("roleName", roleName);
tracingParameters.Add("networkInterfaceName", networkInterfaceName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginSettingIPForwardingOnNetworkInterfaceAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/roles/";
url = url + Uri.EscapeDataString(roleName);
url = url + "/networkinterfaces/";
url = url + Uri.EscapeDataString(networkInterfaceName);
url = url + "/ipforwarding";
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.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2016-07-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement iPForwardingElement = new XElement(XName.Get("IPForwarding", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(iPForwardingElement);
XElement stateElement = new XElement(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
stateElement.Value = parameters.State;
iPForwardingElement.Add(stateElement);
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// 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.Accepted)
{
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
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
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>
/// Sets IP Forwarding on a role.
/// </summary>
/// <param name='serviceName'>
/// Required.
/// </param>
/// <param name='deploymentName'>
/// Required.
/// </param>
/// <param name='roleName'>
/// Required.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Set IP Forwarding on role
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginSettingIPForwardingOnRoleAsync(string serviceName, string deploymentName, string roleName, IPForwardingSetParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (roleName == null)
{
throw new ArgumentNullException("roleName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.State == null)
{
throw new ArgumentNullException("parameters.State");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("roleName", roleName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginSettingIPForwardingOnRoleAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/roles/";
url = url + Uri.EscapeDataString(roleName);
url = url + "/ipforwarding";
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.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2016-07-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement iPForwardingElement = new XElement(XName.Get("IPForwarding", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(iPForwardingElement);
XElement stateElement = new XElement(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
stateElement.Value = parameters.State;
iPForwardingElement.Add(stateElement);
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// 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.Accepted)
{
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
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
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 the IP Forwarding applied to a network interface.
/// </summary>
/// <param name='serviceName'>
/// Required.
/// </param>
/// <param name='deploymentName'>
/// Required.
/// </param>
/// <param name='roleName'>
/// Required.
/// </param>
/// <param name='networkInterfaceName'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The IP Forwarding state associated with a role or network interface.
/// </returns>
public async Task<IPForwardingGetResponse> GetForNetworkInterfaceAsync(string serviceName, string deploymentName, string roleName, string networkInterfaceName, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (roleName == null)
{
throw new ArgumentNullException("roleName");
}
if (networkInterfaceName == null)
{
throw new ArgumentNullException("networkInterfaceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("roleName", roleName);
tracingParameters.Add("networkInterfaceName", networkInterfaceName);
TracingAdapter.Enter(invocationId, this, "GetForNetworkInterfaceAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/roles/";
url = url + Uri.EscapeDataString(roleName);
url = url + "/networkinterfaces/";
url = url + Uri.EscapeDataString(networkInterfaceName);
url = url + "/ipforwarding";
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
httpRequest.Headers.Add("x-ms-version", "2016-07-01");
// 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
IPForwardingGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new IPForwardingGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement iPForwardingElement = responseDoc.Element(XName.Get("IPForwarding", "http://schemas.microsoft.com/windowsazure"));
if (iPForwardingElement != null)
{
XElement stateElement = iPForwardingElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
result.State = stateInstance;
}
}
}
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 the IP Forwarding applied to a role.
/// </summary>
/// <param name='serviceName'>
/// Required.
/// </param>
/// <param name='deploymentName'>
/// Required.
/// </param>
/// <param name='roleName'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The IP Forwarding state associated with a role or network interface.
/// </returns>
public async Task<IPForwardingGetResponse> GetForRoleAsync(string serviceName, string deploymentName, string roleName, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (roleName == null)
{
throw new ArgumentNullException("roleName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("roleName", roleName);
TracingAdapter.Enter(invocationId, this, "GetForRoleAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/roles/";
url = url + Uri.EscapeDataString(roleName);
url = url + "/ipforwarding";
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
httpRequest.Headers.Add("x-ms-version", "2016-07-01");
// 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
IPForwardingGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new IPForwardingGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement iPForwardingElement = responseDoc.Element(XName.Get("IPForwarding", "http://schemas.microsoft.com/windowsazure"));
if (iPForwardingElement != null)
{
XElement stateElement = iPForwardingElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
result.State = stateInstance;
}
}
}
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>
/// Sets IP Forwarding on a network interface.
/// </summary>
/// <param name='serviceName'>
/// Required.
/// </param>
/// <param name='deploymentName'>
/// Required.
/// </param>
/// <param name='roleName'>
/// Required.
/// </param>
/// <param name='networkInterfaceName'>
/// Required.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Set IP Forwarding on network
/// interface operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> SetOnNetworkInterfaceAsync(string serviceName, string deploymentName, string roleName, string networkInterfaceName, IPForwardingSetParameters parameters, CancellationToken cancellationToken)
{
NetworkManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("roleName", roleName);
tracingParameters.Add("networkInterfaceName", networkInterfaceName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "SetOnNetworkInterfaceAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.IPForwarding.BeginSettingIPForwardingOnNetworkInterfaceAsync(serviceName, deploymentName, roleName, networkInterfaceName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// Sets IP Forwarding on a role.
/// </summary>
/// <param name='serviceName'>
/// Required.
/// </param>
/// <param name='deploymentName'>
/// Required.
/// </param>
/// <param name='roleName'>
/// Required.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Set IP Forwarding on role
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> SetOnRoleAsync(string serviceName, string deploymentName, string roleName, IPForwardingSetParameters parameters, CancellationToken cancellationToken)
{
NetworkManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("roleName", roleName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "SetOnRoleAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.IPForwarding.BeginSettingIPForwardingOnRoleAsync(serviceName, deploymentName, roleName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
}
}
| |
//
// TextEntryBackend.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 Xwt.Backends;
using System;
#if MONOMAC
using nint = System.Int32;
using nfloat = System.Single;
using MonoMac.Foundation;
using MonoMac.AppKit;
#else
using Foundation;
using AppKit;
#endif
namespace Xwt.Mac
{
public class TextEntryBackend: ViewBackend<NSView,ITextEntryEventSink>, ITextEntryBackend
{
int cacheSelectionStart, cacheSelectionLength;
bool checkMouseSelection;
public TextEntryBackend ()
{
}
internal TextEntryBackend (MacComboBox field)
{
ViewObject = field;
}
public override void Initialize ()
{
base.Initialize ();
if (ViewObject is MacComboBox) {
((MacComboBox)ViewObject).SetEntryEventSink (EventSink);
} else {
var view = new CustomTextField (EventSink, ApplicationContext);
ViewObject = new CustomAlignedContainer (EventSink, ApplicationContext, (NSView)view);
MultiLine = false;
}
canGetFocus = Widget.AcceptsFirstResponder ();
Frontend.MouseEntered += delegate {
checkMouseSelection = true;
};
Frontend.MouseExited += delegate {
checkMouseSelection = false;
HandleSelectionChanged ();
};
Frontend.MouseMoved += delegate {
if (checkMouseSelection)
HandleSelectionChanged ();
};
}
protected override void OnSizeToFit ()
{
Container.SizeToFit ();
}
CustomAlignedContainer Container {
get { return base.Widget as CustomAlignedContainer; }
}
public new NSTextField Widget {
get { return (ViewObject is MacComboBox) ? (NSTextField)ViewObject : (NSTextField) Container.Child; }
}
protected override Size GetNaturalSize ()
{
var s = base.GetNaturalSize ();
return new Size (EventSink.GetDefaultNaturalSize ().Width, s.Height);
}
#region ITextEntryBackend implementation
public string Text {
get {
return Widget.StringValue;
}
set {
Widget.StringValue = value ?? string.Empty;
}
}
public Alignment TextAlignment {
get {
return Widget.Alignment.ToAlignment ();
}
set {
Widget.Alignment = value.ToNSTextAlignment ();
}
}
public bool ReadOnly {
get {
return !Widget.Editable;
}
set {
Widget.Editable = !value;
}
}
public bool ShowFrame {
get {
return Widget.Bordered;
}
set {
Widget.Bordered = value;
}
}
public string PlaceholderText {
get {
return ((NSTextFieldCell) Widget.Cell).PlaceholderString;
}
set {
((NSTextFieldCell) Widget.Cell).PlaceholderString = value;
}
}
public bool MultiLine {
get {
if (Widget is MacComboBox)
return false;
return Widget.Cell.UsesSingleLineMode;
}
set {
if (Widget is MacComboBox)
return;
if (value) {
Widget.Cell.UsesSingleLineMode = false;
Widget.Cell.Scrollable = false;
Widget.Cell.Wraps = true;
} else {
Widget.Cell.UsesSingleLineMode = true;
Widget.Cell.Scrollable = true;
Widget.Cell.Wraps = false;
}
Container.ExpandVertically = value;
}
}
public int CursorPosition {
get {
if (Widget.CurrentEditor == null)
return 0;
return (int)Widget.CurrentEditor.SelectedRange.Location;
}
set {
Widget.CurrentEditor.SelectedRange = new NSRange (value, SelectionLength);
HandleSelectionChanged ();
}
}
public int SelectionStart {
get {
if (Widget.CurrentEditor == null)
return 0;
return (int)Widget.CurrentEditor.SelectedRange.Location;
}
set {
Widget.CurrentEditor.SelectedRange = new NSRange (value, SelectionLength);
HandleSelectionChanged ();
}
}
public int SelectionLength {
get {
if (Widget.CurrentEditor == null)
return 0;
return (int)Widget.CurrentEditor.SelectedRange.Length;
}
set {
Widget.CurrentEditor.SelectedRange = new NSRange (SelectionStart, value);
HandleSelectionChanged ();
}
}
public string SelectedText {
get {
if (Widget.CurrentEditor == null)
return String.Empty;
int start = SelectionStart;
int end = start + SelectionLength;
if (start == end) return String.Empty;
try {
return Text.Substring (start, end - start);
} catch {
return String.Empty;
}
}
set {
int cacheSelStart = SelectionStart;
int pos = cacheSelStart;
if (SelectionLength > 0) {
Text = Text.Remove (pos, SelectionLength).Insert (pos, value);
}
SelectionStart = pos;
SelectionLength = value.Length;
HandleSelectionChanged ();
}
}
void HandleSelectionChanged ()
{
if (cacheSelectionStart != SelectionStart ||
cacheSelectionLength != SelectionLength) {
cacheSelectionStart = SelectionStart;
cacheSelectionLength = SelectionLength;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnSelectionChanged ();
});
}
}
public void SetCompletions (string[] completions)
{
}
public void SetCompletionMatchFunc (Func<string, string, bool> matchFunc)
{
}
#endregion
#region Gross Hack
// The 'Widget' property is not virtual and the one on the base class holds
// the 'CustomAlignedContainer' object and *not* the NSTextField object. As
// such everything that uses the 'Widget' property in the base class might be
// working on the wrong object. The focus methods definitely need to work on
// the NSTextField directly, so i've overridden those and made them interact
// with the NSTextField instead of the CustomAlignedContainer.
bool canGetFocus = true;
public override bool CanGetFocus {
get { return canGetFocus; }
set { canGetFocus = value && Widget.AcceptsFirstResponder (); }
}
public override void SetFocus ()
{
if (Widget.Window != null && CanGetFocus)
Widget.Window.MakeFirstResponder (Widget);
}
public override bool HasFocus {
get {
return Widget.Window != null && Widget.Window.FirstResponder == Widget;
}
}
#endregion
}
class CustomTextField: NSTextField, IViewObject
{
ITextEntryEventSink eventSink;
ApplicationContext context;
CustomCell cell;
public CustomTextField (ITextEntryEventSink eventSink, ApplicationContext context)
{
this.context = context;
this.eventSink = eventSink;
this.Cell = cell = new CustomCell {
BezelStyle = NSTextFieldBezelStyle.Square,
Bezeled = true,
DrawsBackground = true,
BackgroundColor = NSColor.White,
Editable = true,
EventSink = eventSink,
Context = context,
};
}
public NSView View {
get {
return this;
}
}
public ViewBackend Backend { get; set; }
public override void DidChange (NSNotification notification)
{
base.DidChange (notification);
context.InvokeUserCode (delegate {
eventSink.OnChanged ();
eventSink.OnSelectionChanged ();
});
}
class CustomCell : NSTextFieldCell
{
CustomEditor editor;
public ApplicationContext Context {
get; set;
}
public ITextEntryEventSink EventSink {
get; set;
}
public CustomCell ()
{
}
public override NSTextView FieldEditorForView (NSView aControlView)
{
if (editor == null) {
editor = new CustomEditor {
Context = this.Context,
EventSink = this.EventSink,
FieldEditor = true,
Editable = true,
DrawsBackground = true,
BackgroundColor = NSColor.White,
};
}
return editor;
}
}
class CustomEditor : NSTextView
{
public ApplicationContext Context {
get; set;
}
public ITextEntryEventSink EventSink {
get; set;
}
public CustomEditor ()
{
}
public override void KeyDown (NSEvent theEvent)
{
Context.InvokeUserCode (delegate {
EventSink.OnKeyPressed (theEvent.ToXwtKeyEventArgs ());
});
base.KeyDown (theEvent);
}
nint cachedCursorPosition;
public override void KeyUp (NSEvent theEvent)
{
if (cachedCursorPosition != SelectedRange.Location) {
cachedCursorPosition = SelectedRange.Location;
Context.InvokeUserCode (delegate {
EventSink.OnSelectionChanged ();
EventSink.OnKeyReleased (theEvent.ToXwtKeyEventArgs ());
});
}
base.KeyUp (theEvent);
}
public override bool BecomeFirstResponder ()
{
var result = base.BecomeFirstResponder ();
if (result) {
Context.InvokeUserCode (() => {
EventSink.OnGotFocus ();
});
}
return result;
}
public override bool ResignFirstResponder ()
{
var result = base.ResignFirstResponder ();
if (result) {
Context.InvokeUserCode (() => {
EventSink.OnLostFocus ();
});
}
return result;
}
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Timers;
using System.Threading.Tasks;
using log4net;
using log4net.Config;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Grid.Framework;
using OpenSim.Grid.MessagingServer.Modules;
using System.Threading;
namespace OpenSim.Grid.MessagingServer
{
/// <summary>
/// </summary>
public class OpenMessage_Main : BaseOpenSimServer , IGridServiceCore
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private MessageServerConfig Cfg;
private MessageService msgsvc;
private MessageRegionModule m_regionModule;
private InterMessageUserServerModule m_userServerModule;
private UserDataBaseService m_userDataBaseService;
private ManualResetEvent Terminating = new ManualResetEvent(false);
private InWorldz.RemoteAdmin.RemoteAdmin m_radmin;
public static void Main(string[] args)
{
ServicePointManager.DefaultConnectionLimit = 12;
XmlConfigurator.Configure();
ArgvConfigSource configSource = new ArgvConfigSource(args);
configSource.Alias.AddAlias("On", true);
configSource.Alias.AddAlias("Off", false);
configSource.Alias.AddAlias("True", true);
configSource.Alias.AddAlias("False", false);
configSource.Alias.AddAlias("Yes", true);
configSource.Alias.AddAlias("No", false);
configSource.AddSwitch("Startup", "background");
m_log.Info("[SERVER]: Launching MessagingServer...");
OpenMessage_Main messageserver = new OpenMessage_Main();
messageserver.Startup();
messageserver.Work(configSource.Configs["Startup"].GetBoolean("background", false));
}
public OpenMessage_Main()
{
m_console = new LocalConsole("Messaging");
MainConsole.Instance = m_console;
}
private void Work(bool background)
{
if (background) {
Terminating.WaitOne();
Terminating.Close();
} else {
m_console.Notice("Enter help for a list of commands\n");
while (true)
{
m_console.Prompt();
}
}
}
private void registerWithUserServer()
{
retry:
if (m_userServerModule.registerWithUserServer())
{
m_log.Info("[SERVER]: Starting HTTP process");
m_httpServer = new BaseHttpServer(Cfg.HttpPort, null);
m_httpServer.AddXmlRPCHandler("login_to_simulator", msgsvc.UserLoggedOn);
m_httpServer.AddXmlRPCHandler("logout_of_simulator", msgsvc.UserLoggedOff);
m_httpServer.AddXmlRPCHandler("get_presence_info_bulk", msgsvc.GetPresenceInfoBulk);
m_httpServer.AddXmlRPCHandler("process_region_shutdown", msgsvc.ProcessRegionShutdown);
m_httpServer.AddXmlRPCHandler("agent_location", msgsvc.AgentLocation);
m_httpServer.AddXmlRPCHandler("agent_leaving", msgsvc.AgentLeaving);
m_httpServer.AddXmlRPCHandler("region_startup", m_regionModule.RegionStartup);
m_httpServer.AddXmlRPCHandler("region_shutdown", m_regionModule.RegionShutdown);
// New Style
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("login_to_simulator"), msgsvc.UserLoggedOn));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("logout_of_simulator"), msgsvc.UserLoggedOff));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("get_presence_info_bulk"), msgsvc.GetPresenceInfoBulk));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("process_region_shutdown"), msgsvc.ProcessRegionShutdown));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("agent_location"), msgsvc.AgentLocation));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("agent_leaving"), msgsvc.AgentLeaving));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("region_startup"), m_regionModule.RegionStartup));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("region_shutdown"), m_regionModule.RegionShutdown));
m_radmin = new InWorldz.RemoteAdmin.RemoteAdmin(Cfg.SSLPublicCertFile);
m_radmin.AddCommand("MessagingService", "Shutdown", MessagingServerShutdownHandler);
m_radmin.AddHandler(m_httpServer);
m_httpServer.Start();
m_log.Info("[SERVER]: Userserver registration was successful");
}
else
{
m_log.Error("[STARTUP]: Unable to connect to User Server, retrying in 5 seconds");
System.Threading.Thread.Sleep(5000);
goto retry;
}
}
public object MessagingServerShutdownHandler(IList args, IPEndPoint remoteClient)
{
m_radmin.CheckSessionValid(new UUID((string)args[0]));
try
{
int delay = (int)args[1];
string message;
if (delay > 0)
message = "Server is going down in " + delay.ToString() + " second(s).";
else
message = "Server is going down now.";
m_log.DebugFormat("[RADMIN] Shutdown: {0}", message);
// Perform shutdown
if (delay > 0)
System.Threading.Thread.Sleep(delay * 1000);
// Do this on a new thread so the actual shutdown call returns successfully.
Task.Factory.StartNew(() => Shutdown());
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN] Shutdown: failed: {0}", e.Message);
m_log.DebugFormat("[RADMIN] Shutdown: failed: {0}", e.ToString());
throw;
}
m_log.Info("[RADMIN]: Shutdown Administrator Request complete");
return true;
}
private void deregisterFromUserServer()
{
m_userServerModule.deregisterWithUserServer();
if (m_httpServer != null)
{
// try a completely fresh registration, with fresh handlers, too
m_httpServer.Stop();
m_httpServer = null;
}
m_console.Notice("[SERVER]: Deregistered from userserver.");
}
protected override void StartupSpecific()
{
Cfg = new MessageServerConfig("MESSAGING SERVER", (Path.Combine(Util.configDir(), "MessagingServer_Config.xml")));
m_userDataBaseService = new UserDataBaseService();
m_userDataBaseService.AddPlugin(Cfg.DatabaseProvider, Cfg.DatabaseConnect);
//Register the database access service so modules can fetch it
// RegisterInterface<UserDataBaseService>(m_userDataBaseService);
m_userServerModule = new InterMessageUserServerModule(Cfg, this);
m_userServerModule.Initialize();
msgsvc = new MessageService(Cfg, this, m_userDataBaseService);
msgsvc.Initialize();
m_regionModule = new MessageRegionModule(Cfg, this);
m_regionModule.Initialize();
registerWithUserServer();
m_userServerModule.PostInitialize();
msgsvc.PostInitialize();
m_regionModule.PostInitialize();
m_log.Info("[SERVER]: Messageserver 0.5 - Startup complete");
base.StartupSpecific();
m_console.Commands.AddCommand("messageserver", false, "clear cache",
"clear cache",
"Clear presence cache", HandleClearCache);
m_console.Commands.AddCommand("messageserver", false, "register",
"register",
"Re-register with user server(s)", HandleRegister);
}
private void HandleClearCache(string module, string[] cmd)
{
int entries = m_regionModule.ClearRegionCache();
m_console.Notice("Region cache cleared! Cleared " +
entries.ToString() + " entries");
}
private void HandleRegister(string module, string[] cmd)
{
deregisterFromUserServer();
registerWithUserServer();
}
public override void ShutdownSpecific()
{
Terminating.Set();
m_userServerModule.deregisterWithUserServer();
}
#region IUGAIMCore
protected Dictionary<Type, object> m_moduleInterfaces = new Dictionary<Type, object>();
/// <summary>
/// Register an Module interface.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="iface"></param>
public void RegisterInterface<T>(T iface)
{
lock (m_moduleInterfaces)
{
if (!m_moduleInterfaces.ContainsKey(typeof(T)))
{
m_moduleInterfaces.Add(typeof(T), iface);
}
}
}
public bool TryGet<T>(out T iface)
{
if (m_moduleInterfaces.ContainsKey(typeof(T)))
{
iface = (T)m_moduleInterfaces[typeof(T)];
return true;
}
iface = default(T);
return false;
}
public T Get<T>()
{
return (T)m_moduleInterfaces[typeof(T)];
}
public BaseHttpServer GetHttpServer()
{
return m_httpServer;
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using OpenLiveWriter.CoreServices;
namespace OpenLiveWriter.PostEditor.PostHtmlEditing.Behaviors
{
public enum SizerMode { Normal, Resizing };
public enum SizerHandle { None, TopLeft, TopRight, BottomLeft, BottomRight, Top, Left, Right, Bottom };
public delegate void SizerModeEventHandler(SizerHandle handle, SizerMode mode);
/// <summary>
/// Summary description for ResizerControl.
/// </summary>
public class ResizerControl : BehaviorControl
{
public event SizerModeEventHandler SizerModeChanged;
public event EventHandler Resized;
//private const string IMAGE_RESOURCE_PATH = "PostHtmlEditing.Behaviors.Images." ;
//private Bitmap activeHatchImage = ResourceHelper.LoadAssemblyResourceBitmap( IMAGE_RESOURCE_PATH + "ActiveHatch.png") ;
internal const int SIZERS_PADDING = 10;
private const int SIZERS_SIZE = 7;
private const int penWidth = 1;
private Rectangle tlCorner;
private Rectangle trCorner;
private Rectangle blCorner;
private Rectangle brCorner;
private Rectangle topSide;
private Rectangle rightSide;
private Rectangle bottomSide;
private Rectangle leftSide;
private SizerMode _mode;
private SizerHandle _activeHandle;
private Point _sizerModeLocation;
private Size _resizeInitialSize;
private bool _allowAspectRatioDistortion = true;
private Size _aspectRatioOffset = Size.Empty;
private ElementFocusPainter focusPainter;
public ResizerControl()
{
focusPainter = new ElementFocusPainter();
}
public Size AspectRatioOffset
{
get { return _aspectRatioOffset; }
set { _aspectRatioOffset = value; }
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
focusPainter.DrawFocusRectangle(e.Graphics);
if (Resizable)
{
PaintSizer(e.Graphics, tlCorner);
PaintSizer(e.Graphics, trCorner);
PaintSizer(e.Graphics, blCorner);
PaintSizer(e.Graphics, brCorner);
if (AllowAspectRatioDistortion)
{
PaintSizer(e.Graphics, topSide);
PaintSizer(e.Graphics, rightSide);
PaintSizer(e.Graphics, bottomSide);
PaintSizer(e.Graphics, leftSide);
}
}
}
private void PaintSizer(Graphics g, Rectangle rect)
{
g.FillRectangle(new SolidBrush(Color.White), rect);
g.DrawRectangle(new Pen(Color.Black, penWidth), rect);
}
private void UpdateActiveHandle(Point p)
{
//Warning: we only want to reset the handle if we are not resizing!
//Otherwise, we will lose our resize operation if the mouse slips outside
//of the corner.
if (Mode == SizerMode.Resizing)
{
return;
}
ActiveHandle = GetHandleForPoint(p);
}
public SizerHandle GetHandleForPoint(Point p)
{
if (tlCorner.Contains(p))
return SizerHandle.TopLeft;
else if (trCorner.Contains(p))
return SizerHandle.TopRight;
else if (blCorner.Contains(p))
return SizerHandle.BottomLeft;
else if (brCorner.Contains(p))
return SizerHandle.BottomRight;
else if (topSide.Contains(p))
return SizerHandle.Top;
else if (rightSide.Contains(p))
return SizerHandle.Right;
else if (bottomSide.Contains(p))
return SizerHandle.Bottom;
else if (leftSide.Contains(p))
return SizerHandle.Left;
else
return SizerHandle.None;
}
public override bool HitTestPoint(Point testPoint)
{
return GetHandleForPoint(testPoint) != SizerHandle.None;
}
protected override void OnLayout(EventArgs e)
{
base.OnLayout(e);
focusPainter.LayoutFocusRectangle(CalculateRelativeElementRectangle());
if (Resizable)
{
Size size = new Size(SIZERS_SIZE - penWidth, SIZERS_SIZE - penWidth);
tlCorner = new Rectangle(new Point(0, 0), size);
trCorner = new Rectangle(new Point(VirtualWidth - SIZERS_SIZE, 0), size);
blCorner = new Rectangle(new Point(0, VirtualHeight - SIZERS_SIZE), size);
brCorner = new Rectangle(new Point(VirtualWidth - SIZERS_SIZE, VirtualHeight - SIZERS_SIZE), size);
if (AllowAspectRatioDistortion)
{
topSide = Utility.CenterInRectangle(size, new Rectangle(new Point(0, 0), new Size(VirtualWidth, SIZERS_SIZE)));
rightSide = Utility.CenterInRectangle(size, new Rectangle(new Point(VirtualWidth - SIZERS_SIZE, 0), new Size(SIZERS_SIZE, VirtualHeight)));
bottomSide = Utility.CenterInRectangle(size, new Rectangle(new Point(0, VirtualHeight - SIZERS_SIZE), new Size(VirtualWidth, SIZERS_SIZE)));
leftSide = Utility.CenterInRectangle(size, new Rectangle(new Point(0, 0), new Size(SIZERS_SIZE, VirtualHeight)));
}
else
{
topSide = Rectangle.Empty;
rightSide = Rectangle.Empty;
bottomSide = Rectangle.Empty;
leftSide = Rectangle.Empty;
}
}
}
private Rectangle CalculateRelativeElementRectangle()
{
Point p = VirtualLocation;
//return new Rectangle(new Point(-p.X, -p.Y), Parent.ElementRectangle.Size);
return new Rectangle(SIZERS_PADDING, SIZERS_PADDING, VirtualWidth - SIZERS_PADDING * 2, VirtualHeight - SIZERS_PADDING * 2);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
Point p = new Point(e.X, e.Y);
UpdateActiveHandle(p);
if (_activeHandle != SizerHandle.None)
OnSizerModeChanged(_activeHandle, SizerMode.Resizing);
Point pntGlobal = Parent.TransformLocalToGlobal(new Point(e.X, e.Y));
_sizerModeLocation = pntGlobal; // new Point(e.X, e.Y);
}
protected override void OnMouseUp(MouseEventArgs e)
{
ResetModeToNormal();
base.OnMouseDown(e);
}
protected override void OnMouseLeave(EventArgs e)
{
ActiveHandle = SizerHandle.None;
ResetModeToNormal();
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
UpdateActiveHandle(new Point(e.X, e.Y));
if ((Control.MouseButtons & MouseButtons.Left) != MouseButtons.Left)
{
//we don't get mouse up events when the mouse leaves the editor
ResetModeToNormal();
}
else
{
if (Mode == SizerMode.Resizing)
{
Point pntGlobal = Parent.TransformLocalToGlobal(new Point(e.X, e.Y));
int xDelta = pntGlobal.X - _sizerModeLocation.X;
int yDelta = pntGlobal.Y - _sizerModeLocation.Y;
switch (_activeHandle)
{
case SizerHandle.TopLeft:
UpdateElementSize(_resizeInitialSize.Width - xDelta, _resizeInitialSize.Height - yDelta, true);
break;
case SizerHandle.TopRight:
UpdateElementSize(_resizeInitialSize.Width + xDelta, _resizeInitialSize.Height - Math.Min(yDelta, 0)/*hackish but creates a better experience when resizing using the topright knob*/ , true);
break;
case SizerHandle.BottomLeft:
UpdateElementSize(_resizeInitialSize.Width - xDelta, _resizeInitialSize.Height + yDelta, true);
break;
case SizerHandle.BottomRight:
UpdateElementSize(_resizeInitialSize.Width + xDelta, _resizeInitialSize.Height + yDelta, true);
break;
case SizerHandle.Top:
UpdateElementSize(_resizeInitialSize.Width, _resizeInitialSize.Height - yDelta, false);
break;
case SizerHandle.Right:
UpdateElementSize(_resizeInitialSize.Width + xDelta, _resizeInitialSize.Height, false);
break;
case SizerHandle.Bottom:
UpdateElementSize(_resizeInitialSize.Width, _resizeInitialSize.Height + yDelta, false);
break;
case SizerHandle.Left:
UpdateElementSize(_resizeInitialSize.Width - xDelta, _resizeInitialSize.Height, false);
break;
}
}
}
}
private void UpdateElementSize(int width, int height, bool preserveAspectRatio)
{
Size newSize = new Size(Math.Max(0, width), Math.Max(0, height));
if (preserveAspectRatio)
{
newSize = Utility.GetScaledMaxSize(_resizeInitialSize - _aspectRatioOffset, newSize - _aspectRatioOffset) + _aspectRatioOffset;
}
SizerSize = newSize;
}
public Size SizerSize
{
get
{
return new Size(VirtualWidth - SIZERS_PADDING * 2, VirtualHeight - SIZERS_PADDING * 2);
}
set
{
VirtualSize = new Size(value.Width + SIZERS_PADDING * 2, value.Height + SIZERS_PADDING * 2);
}
}
public SizerHandle ActiveSizerHandle
{
get
{
return _activeHandle;
}
}
protected virtual void OnSizerModeChanged(SizerHandle handle, SizerMode mode)
{
bool resizeStarted = _mode == SizerMode.Normal && mode == SizerMode.Resizing;
ActiveHandle = handle;
_mode = mode;
if (resizeStarted)
OnResizeStart();
if (SizerModeChanged != null)
SizerModeChanged(handle, mode);
}
private void OnResizeStart()
{
//save the current size
_resizeInitialSize = SizerSize;
}
protected override void OnVirtualSizeChanged(EventArgs e)
{
base.OnVirtualSizeChanged(e);
if (Resized != null)
{
Resized(this, EventArgs.Empty);
}
}
public bool AllowAspectRatioDistortion
{
get
{
return _allowAspectRatioDistortion;
}
set
{
if (_allowAspectRatioDistortion != value)
{
_allowAspectRatioDistortion = value;
PerformLayout();
Invalidate();
}
}
}
public bool Resizable
{
get
{
return _resizable;
}
set
{
if (_resizable != value)
{
_resizable = value;
PerformLayout();
Invalidate();
}
}
}
private bool _resizable;
public SizerMode Mode
{
get
{
return _mode;
}
}
private SizerHandle ActiveHandle
{
get
{
return _activeHandle;
}
set
{
if (_activeHandle != value)
{
_activeHandle = value;
}
}
}
private void ResetModeToNormal()
{
if (_mode != SizerMode.Normal)
{
OnSizerModeChanged(_activeHandle, SizerMode.Normal);
}
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Windows.Forms;
namespace DotSpatial.Data.Forms
{
/// <summary>
/// This handles the methodology of progress messaging in one place to make it easier to update.
/// </summary>
public class TimedProgressMeter
{
#region Fields
private readonly Timer _timer;
private double _endValue;
private int _oldProg; // the previous progress level
private int _prog; // the current progress level
private double _startValue;
private int _stepPercent = 1;
private double _value;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="TimedProgressMeter"/> class that shows progress against an expected time.
/// </summary>
/// <param name="progressHandler">An IProgressHandler that will actually handle the status messages sent by this meter.</param>
/// <param name="baseMessage">A base message to use as the basic status for this progress handler.</param>
/// <param name="estimatedTime">The time the process might take.</param>
public TimedProgressMeter(IProgressHandler progressHandler, string baseMessage, TimeSpan estimatedTime)
{
ProgressHandler = progressHandler;
Key = baseMessage;
_endValue = estimatedTime.TotalSeconds * 1000;
_timer = new Timer
{
Interval = Convert.ToInt32(estimatedTime.TotalSeconds * 10) // Attempt to have a tick once during each estimated percentile
};
_timer.Tick += TimerTick;
_timer.Start(); // Timers should be on another thread...
}
/// <summary>
/// Initializes a new instance of the <see cref="TimedProgressMeter"/> class, but doesn't support the IProgressHandler unless one is specified.
/// </summary>
public TimedProgressMeter()
: this(null, "Calculating values.", 100)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TimedProgressMeter"/> class.
/// A progress meter can't actually do anything without a progressHandler, which actually displays the status.
/// </summary>
/// <param name="progressHandler">An IProgressHandler that will actually handle the status messages sent by this meter.</param>
public TimedProgressMeter(IProgressHandler progressHandler)
: this(progressHandler, "Calculating values.", 100)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TimedProgressMeter"/> class that simply keeps track of progress and is capable of sending progress messages.
/// This assumes a MaxValue of 100 unless it is changed later.
/// </summary>
/// <param name="progressHandler">Any valid IProgressHandler that will display progress messages.</param>
/// <param name="baseMessage">A base message to use as the basic status for this progress handler.</param>
public TimedProgressMeter(IProgressHandler progressHandler, string baseMessage)
: this(progressHandler, baseMessage, 100)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TimedProgressMeter"/> class that simply keeps track of progress and is capable of sending progress messages.
/// </summary>
/// <param name="progressHandler">Any valid implementation if IProgressHandler that will handle the progress function.</param>
/// <param name="baseMessage">The message without any progress information.</param>
/// <param name="endValue">Percent shoudl show a range between the MinValue and MaxValue. MinValue is assumed to be 0.</param>
public TimedProgressMeter(IProgressHandler progressHandler, string baseMessage, object endValue)
{
_endValue = Convert.ToDouble(endValue);
ProgressHandler = progressHandler;
Reset();
Key = baseMessage;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the current integer progress level from 0 to 100. If a new update is less than or equal to the previous
/// value, then no progress will be displayed by the ProgressMeter. Values less than 0 are set to 0. Values greater than
/// 100 are set to 100.
/// </summary>
public int CurrentPercent
{
get
{
return _prog;
}
set
{
int val = value;
if (val < 0) val = 0;
if (val > 100)
{
_timer?.Stop();
val = 100;
}
_prog = val;
if (_prog >= _oldProg + _stepPercent)
{
SendProgress();
_oldProg = _prog;
}
}
}
/// <summary>
/// Gets or sets the current value relative to the specified MaxValue in order to update the progress.
/// Setting this will also update OldProgress if there is an integer change in the percentage, and send
/// a progress message to the IProgressHandler interface.
/// </summary>
public object CurrentValue
{
get
{
return _value;
}
set
{
_value = Convert.ToDouble(value);
if (_startValue < _endValue)
{
CurrentPercent = Convert.ToInt32(Math.Round(100 * (_value - _startValue) / (_endValue - _startValue)));
}
else
{
CurrentPercent = Convert.ToInt32(Math.Round(100 * (_startValue - _value) / (_startValue - _endValue)));
}
}
}
/// <summary>
/// Gets or sets the value that defines when the meter should show as 100% complete.
/// EndValue can be less than StartValue, but values closer to EndValue
/// will show as being closer to 100%.
/// </summary>
public object EndValue
{
get
{
return _endValue;
}
set
{
_endValue = Convert.ToDouble(value);
}
}
/// <summary>
/// Gets or sets the string that does not include any mention of progress percentage, but specifies what is occuring.
/// </summary>
public string Key { get; set; }
/// <summary>
/// Gets or sets the previous integer progress level from 0 to 100. If a new update is less than or equal to the previous
/// value, then no progress will be displayed by the ProgressMeter. Values less than 0 are set to 0. Values greater than
/// 100 are set to 100.
/// </summary>
public int PreviousPercent
{
get
{
return _oldProg;
}
set
{
int val = value;
if (val < 0) val = 0;
if (val > 100) val = 100;
_oldProg = val;
}
}
/// <summary>
/// Gets or sets the progress handler for this meter.
/// </summary>
public IProgressHandler ProgressHandler { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the progress meter should send messages to the IProgressHandler.
/// By default Silent is false, but setting this to true will disable the messaging portion.
/// </summary>
public bool Silent { get; set; }
/// <summary>
/// Gets or sets the minimum value defines when the meter should show as 0% complete.
/// </summary>
public object StartValue
{
get
{
return _startValue;
}
set
{
_startValue = Convert.ToDouble(value);
}
}
/// <summary>
/// Gets or sets an integer value that is 1 by default. Ordinarilly this will send a progress message only when the integer progress
/// has changed by 1 percentage point. For example, if StepPercent were set to 5, then a progress update would only
/// be sent out at 5%, 10% and so on. This helps reduce overhead in cases where showing status messages is actually
/// the majority of the processing time for the function.
/// </summary>
public int StepPercent
{
get
{
return _stepPercent;
}
set
{
_stepPercent = value;
if (_stepPercent < 1) _stepPercent = 1;
if (_stepPercent > 100) _stepPercent = 100;
}
}
#endregion
#region Methods
/// <summary>
/// Resets the progress meter to the 0 value. This sets the status message to "Ready.".
/// </summary>
public void Reset()
{
_prog = 0;
_oldProg = 0;
Key = "Ready.";
_timer?.Stop();
if (Silent) return;
if (ProgressHandler == null) return;
ProgressHandler.Reset();
Application.DoEvents(); // Allow the form to update a status bar if necessary.
}
/// <summary>
/// Sends a progress message to the IProgressHandler interface with the current message and progres.
/// </summary>
public void SendProgress()
{
if (Silent) return;
if (ProgressHandler == null) return;
ProgressHandler.Progress(_prog, Key + ", " + _prog + "% Complete.");
Application.DoEvents(); // Allow the form to update a status bar if necessary.
}
private void TimerTick(object sender, EventArgs e)
{
CurrentPercent++;
}
#endregion
}
}
| |
//
// 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.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.ExpressRoute;
using Microsoft.WindowsAzure.Management.ExpressRoute.Models;
namespace Microsoft.WindowsAzure.Management.ExpressRoute
{
internal partial class DedicatedCircuitStatsOperations : IServiceOperations<ExpressRouteManagementClient>, IDedicatedCircuitStatsOperations
{
/// <summary>
/// Initializes a new instance of the DedicatedCircuitStatsOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DedicatedCircuitStatsOperations(ExpressRouteManagementClient client)
{
this._client = client;
}
private ExpressRouteManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.ExpressRouteManagementClient.
/// </summary>
public ExpressRouteManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Get Dedicated Circuit Stats operation retrieves the
/// bytesin/bytesout of the dedicated circuit on primary/secondary
/// devices for specified peering type.
/// </summary>
/// <param name='serviceKey'>
/// Required. The service key representing the circuit.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public or microsoft.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get DedicatedCircuitStats operation response.
/// </returns>
public async Task<DedicatedCircuitStatsGetResponse> GetAsync(string serviceKey, BgpPeeringAccessType accessType, CancellationToken cancellationToken)
{
// Validate
if (serviceKey == null)
{
throw new ArgumentNullException("serviceKey");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
tracingParameters.Add("accessType", accessType);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits/";
url = url + Uri.EscapeDataString(serviceKey);
url = url + "/bgppeerings/";
url = url + Uri.EscapeDataString(ExpressRouteManagementClient.BgpPeeringAccessTypeToString(accessType));
url = url + "/stats";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
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
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// 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
DedicatedCircuitStatsGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DedicatedCircuitStatsGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement dedicatedCircuitStatsElement = responseDoc.Element(XName.Get("DedicatedCircuitStats", "http://schemas.microsoft.com/windowsazure"));
if (dedicatedCircuitStatsElement != null)
{
AzureDedicatedCircuitStats dedicatedCircuitStatsInstance = new AzureDedicatedCircuitStats();
result.DedicatedCircuitStats = dedicatedCircuitStatsInstance;
XElement primaryBytesInElement = dedicatedCircuitStatsElement.Element(XName.Get("PrimaryBytesIn", "http://schemas.microsoft.com/windowsazure"));
if (primaryBytesInElement != null)
{
ulong primaryBytesInInstance = ulong.Parse(primaryBytesInElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitStatsInstance.PrimaryBytesIn = primaryBytesInInstance;
}
XElement primaryBytesOutElement = dedicatedCircuitStatsElement.Element(XName.Get("PrimaryBytesOut", "http://schemas.microsoft.com/windowsazure"));
if (primaryBytesOutElement != null)
{
ulong primaryBytesOutInstance = ulong.Parse(primaryBytesOutElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitStatsInstance.PrimaryBytesOut = primaryBytesOutInstance;
}
XElement secondaryBytesInElement = dedicatedCircuitStatsElement.Element(XName.Get("SecondaryBytesIn", "http://schemas.microsoft.com/windowsazure"));
if (secondaryBytesInElement != null)
{
ulong secondaryBytesInInstance = ulong.Parse(secondaryBytesInElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitStatsInstance.SecondaryBytesIn = secondaryBytesInInstance;
}
XElement secondaryBytesOutElement = dedicatedCircuitStatsElement.Element(XName.Get("SecondaryBytesOut", "http://schemas.microsoft.com/windowsazure"));
if (secondaryBytesOutElement != null)
{
ulong secondaryBytesOutInstance = ulong.Parse(secondaryBytesOutElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitStatsInstance.SecondaryBytesOut = secondaryBytesOutInstance;
}
}
}
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();
}
}
}
}
}
| |
using Bridge.Test.NUnit;
using System;
namespace Bridge.ClientTest.Batch3.BridgeIssues
{
[Category(Constants.MODULE_ISSUES)]
[TestFixture(TestNameFormat = "#1025 - {0}")]
public class Bridge1025
{
public class C1 : IEquatable<int>, IEquatable<string>
{
public int intField;
public string strField;
public bool Equals(int other)
{
this.intField = other;
return true;
}
public bool Equals(string other)
{
this.strField = other;
return false;
}
}
public interface I1
{
int Prop1 { get; set; }
}
public interface I2
{
int Prop1 { get; set; }
}
public class C2 : I1, I2
{
private int i1;
private int i2;
int I1.Prop1
{
get { return this.i1; }
set { this.i1 = value - 1; }
}
int I2.Prop1
{
get { return this.i2; }
set { this.i2 = value + 1; }
}
}
public class C3 : I1, I2
{
public int Prop1 { get; set; }
}
public interface I3
{
string Foo();
}
public class C4 : I3
{
public string Foo()
{
return "C4";
}
}
public class C5 : C4, I3
{
string I3.Foo()
{
return "C5";
}
}
public interface I4
{
string Foo();
}
public class C6
{
public string Foo()
{
return "C6";
}
}
public class C7 : C6, I4
{
public new string Foo()
{
return "C7";
}
}
public interface I5<T>
{
T Foo();
}
public interface I6<T>
{
T Foo();
}
public class C8 : I5<int>, I5<String>
{
int I5<int>.Foo()
{
return 1;
}
string I5<string>.Foo()
{
return "test";
}
}
public class C9<T1, T2> : I5<T1>, I6<T2>
{
public string flag;
T1 I5<T1>.Foo()
{
this.flag = "I5";
return default(T1);
}
T2 I6<T2>.Foo()
{
this.flag = "I6";
return default(T2);
}
}
public interface I7<T1, T2, T3>
{
int Foo();
}
public class C10 : I7<int, string, bool>
{
public int Foo()
{
return 1;
}
}
public class C11<T1, T2, T3> : I7<T1, T2, T3>
{
public int Foo()
{
return 1;
}
}
public class C12<T1, T2, T3> : I7<I5<T1>, I5<T2>, I5<T3>>
{
public int Foo()
{
return 1;
}
}
public class C13<T1, T2, T3> : I7<I5<I5<T1>>, I5<I5<T2>>, I5<I5<T3>>>
{
public int Foo()
{
return 1;
}
}
public interface I8
{
int this[int index] { get; set; }
int Prop1 { get; }
string Prop2 { get; set; }
event Action Event1;
void Invoke();
}
public interface I9<T> : I8
{
new void Invoke();
}
public class C14 : I8
{
public int tmp;
public int this[int index]
{
get { return index; }
set { this.tmp = value; }
}
public int Prop1
{
get { return 2; }
}
public string Prop2 { get; set; }
public event Action Event1;
public void Invoke()
{
this.Event1();
}
}
public class C15 : C14, I9<int>
{
}
public interface I10
{
void Foo();
}
public class C16 : I10
{
public string log;
public void Foo()
{
this.log = "C16";
}
}
public class C17 : C16
{
public new void Foo()
{
this.log = "C17";
}
}
public class C18
{
public string log;
public void Foo()
{
this.log = "C18";
}
}
public class C19 : C18, I10
{
public new void Foo()
{
this.log = "C19";
}
}
public class C20 : I10
{
public string log;
public virtual void Foo()
{
this.log = "C20";
}
}
public class C21 : C20
{
public override void Foo()
{
this.log = "C21";
}
}
public class C22
{
public string log;
public void Foo()
{
this.log = "C22";
}
}
public class C23 : C22
{
}
public class C24 : C23, I10
{
}
[External]
public interface I11
{
[AccessorsIndexer]
int this[string index] { [Name("get")] get; [Name("set")] set; }
string this[int index] { get; set; }
int Prop1 { get; }
string Prop2 { get; set; }
event Action Event1;
void Foo();
}
[Test]
public static void TestC1()
{
var c1 = new C1();
IEquatable<int> i1 = c1;
IEquatable<string> i2 = c1;
Assert.True(i1.Equals(5));
Assert.AreEqual(5, c1.intField);
Assert.False(i2.Equals("6"));
Assert.AreEqual("6", c1.strField);
}
[Test]
public static void TestC2()
{
var c2 = new C2();
I1 i1 = c2;
I2 i2 = c2;
i1.Prop1 = 10;
Assert.AreEqual(9, i1.Prop1);
i2.Prop1 = 10;
Assert.AreEqual(11, i2.Prop1);
}
[Test]
public static void TestC3()
{
var c3 = new C3();
I1 i1 = c3;
I2 i2 = c3;
i1.Prop1 = 10;
Assert.AreEqual(10, i1.Prop1);
Assert.AreEqual(10, i2.Prop1);
Assert.AreEqual(10, c3.Prop1);
i2.Prop1 = 11;
Assert.AreEqual(11, i1.Prop1);
Assert.AreEqual(11, i2.Prop1);
Assert.AreEqual(11, c3.Prop1);
c3.Prop1 = 12;
Assert.AreEqual(12, i1.Prop1);
Assert.AreEqual(12, i2.Prop1);
Assert.AreEqual(12, c3.Prop1);
}
[Test]
public static void TestI3()
{
I3 i;
var a = new C4();
i = a;
Assert.AreEqual("C4", a.Foo());
Assert.AreEqual("C4", i.Foo());
var b = new C5();
i = b;
Assert.AreEqual("C4", b.Foo());
Assert.AreEqual("C5", i.Foo());
}
[Test]
public static void TestI4()
{
var a = new C7();
I4 i = a;
Assert.AreEqual("C7", a.Foo());
Assert.AreEqual("C7", i.Foo());
Assert.AreEqual("C6", ((C6)a).Foo());
}
[Test]
public static void TestI5()
{
var a = new C8();
I5<int> i1 = a;
I5<string> i2 = a;
Assert.AreEqual(1, i1.Foo());
Assert.AreEqual("test", i2.Foo());
}
[Test]
public static void TestI6()
{
var a = new C9<int, string>();
I5<int> i1 = a;
I6<string> i2 = a;
i1.Foo();
Assert.AreEqual("I5", a.flag);
i2.Foo();
Assert.AreEqual("I6", a.flag);
}
[Test]
public static void TestI7()
{
var a = new C10();
I7<int, string, bool> i = a;
Assert.AreEqual(1, i.Foo());
var a1 = new C11<int, string, bool>();
i = a1;
Assert.AreEqual(1, i.Foo());
var a2 = new C12<int, string, bool>();
I7<I5<int>, I5<string>, I5<bool>> i2 = a2;
Assert.AreEqual(1, i2.Foo());
var a3 = new C13<int, string, bool>();
I7<I5<I5<int>>, I5<I5<string>>, I5<I5<bool>>> i3 = a3;
Assert.AreEqual(1, i3.Foo());
}
[Test]
public static void TestI8()
{
var c15 = new C15();
I8 i8 = c15;
I9<int> i9 = c15;
Assert.AreEqual(11, i8[11]);
i8[0] = 15;
Assert.AreEqual(15, c15.tmp);
Assert.AreEqual(2, i8.Prop1);
i8.Prop2 = "test";
Assert.AreEqual("test", i8.Prop2);
var i = 0;
i8.Event1 += () => i = 9;
i8.Invoke();
Assert.AreEqual(9, i);
i = 0;
i9.Invoke();
Assert.AreEqual(9, i);
}
[Test]
public static void TestI10()
{
var c17 = new C17();
C16 c16 = c17;
I10 i10 = c17;
c17.Foo();
Assert.AreEqual("C17", c17.log);
c17.log = null;
c16.Foo();
Assert.AreEqual("C16", c17.log);
c17.log = null;
i10.Foo();
Assert.AreEqual("C16", c17.log);
}
[Test]
public static void TestI10_1()
{
var c19 = new C19();
C18 c18 = c19;
I10 i10 = c19;
c19.Foo();
Assert.AreEqual("C19", c19.log);
c19.log = null;
c18.Foo();
Assert.AreEqual("C18", c19.log);
c19.log = null;
i10.Foo();
Assert.AreEqual("C19", c19.log);
}
[Test]
public static void TestI10_2()
{
var c21 = new C21();
C20 c20 = c21;
I10 i10 = c21;
c21.Foo();
Assert.AreEqual("C21", c21.log);
c21.log = null;
c20.Foo();
Assert.AreEqual("C21", c21.log);
c21.log = null;
i10.Foo();
Assert.AreEqual("C21", c21.log);
var c24 = new C24();
i10 = c24;
i10.Foo();
Assert.AreEqual("C22", c24.log);
}
private static I11 GetI11()
{
var externalInstance = Script.ToPlainObject(new
{
get = (Func<int>)(() => 1),
set = (Action<string>)(s => { }),
addEvent1 = (Action<string>)(s => { }),
Foo = (Action)(() => { })
});
//@ Object.defineProperty(externalInstance, "Prop1", {value:2});
//@ Object.defineProperty(externalInstance, "Prop2", {value:"test", writable:true});
return externalInstance.As<I11>();
}
[Test]
public static void TestI11()
{
I11 i11 = Bridge1025.GetI11();
Assert.AreEqual(1, i11[""]);
i11[i11[1]] = 1;
i11[1] = "";
Assert.AreEqual(2, i11.Prop1);
Assert.AreEqual("test", i11.Prop2);
i11.Prop2 = "";
i11.Foo();
i11.Event1 += () => { };
}
[Test]
public static void TestI11_1()
{
Assert.AreEqual(1, Bridge1025.GetI11()[""]);
Bridge1025.GetI11()[Bridge1025.GetI11()[1]] = 1;
Bridge1025.GetI11()[1] = "";
Assert.AreEqual(2, Bridge1025.GetI11().Prop1);
Assert.AreEqual("test", Bridge1025.GetI11().Prop2);
Bridge1025.GetI11().Prop2 = "";
Bridge1025.GetI11().Foo();
Bridge1025.GetI11().Event1 += () => { };
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Execution;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.MSBuild
{
internal abstract class ProjectFile : IProjectFile
{
private readonly ProjectFileLoader _loader;
private readonly MSB.Evaluation.Project _loadedProject;
public ProjectFile(ProjectFileLoader loader, MSB.Evaluation.Project loadedProject)
{
_loader = loader;
_loadedProject = loadedProject;
}
~ProjectFile()
{
try
{
// unload project so collection will release global strings
_loadedProject.ProjectCollection.UnloadAllProjects();
}
catch
{
}
}
public virtual string FilePath
{
get { return _loadedProject.FullPath; }
}
public string GetPropertyValue(string name)
{
return _loadedProject.GetPropertyValue(name);
}
public abstract SourceCodeKind GetSourceCodeKind(string documentFileName);
public abstract string GetDocumentExtension(SourceCodeKind kind);
public abstract Task<ProjectFileInfo> GetProjectFileInfoAsync(CancellationToken cancellationToken);
protected async Task<ProjectInstance> BuildAsync(string taskName, MSB.Framework.ITaskHost taskHost, CancellationToken cancellationToken)
{
// prepare for building
var buildTargets = new BuildTargets(_loadedProject, "Compile");
// Don't execute this one. It will build referenced projects.
// Even when DesignTimeBuild is defined, it will still add the referenced project's output to the references list
// which we don't want.
buildTargets.Remove("ResolveProjectReferences");
// don't execute anything after CoreCompile target, since we've
// already done everything we need to compute compiler inputs by then.
buildTargets.RemoveAfter("CoreCompile", includeTargetInRemoval: false);
// create a project instance to be executed by build engine.
// The executed project will hold the final model of the project after execution via msbuild.
var executedProject = _loadedProject.CreateProjectInstance();
if (!executedProject.Targets.ContainsKey("Compile"))
{
return executedProject;
}
var hostServices = new Microsoft.Build.Execution.HostServices();
// connect the host "callback" object with the host services, so we get called back with the exact inputs to the compiler task.
hostServices.RegisterHostObject(_loadedProject.FullPath, "CoreCompile", taskName, taskHost);
var buildParameters = new MSB.Execution.BuildParameters(_loadedProject.ProjectCollection);
var buildRequestData = new MSB.Execution.BuildRequestData(executedProject, buildTargets.Targets, hostServices);
var result = await this.BuildAsync(buildParameters, buildRequestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (result.Exception != null)
{
throw result.Exception;
}
return executedProject;
}
// this lock is static because we are using the default build manager, and there is only one per process
private static readonly SemaphoreSlim s_buildManagerLock = new SemaphoreSlim(initialCount: 1);
private async Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
{
// only allow one build to use the default build manager at a time
using (await s_buildManagerLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
{
return await BuildAsync(MSB.Execution.BuildManager.DefaultBuildManager, parameters, requestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
}
}
private static Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildManager buildManager, MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
{
var taskSource = new TaskCompletionSource<MSB.Execution.BuildResult>();
buildManager.BeginBuild(parameters);
// enable cancellation of build
CancellationTokenRegistration registration = default(CancellationTokenRegistration);
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(() =>
{
try
{
buildManager.CancelAllSubmissions();
buildManager.EndBuild();
registration.Dispose();
}
finally
{
taskSource.TrySetCanceled();
}
});
}
// execute build async
try
{
buildManager.PendBuildRequest(requestData).ExecuteAsync(sub =>
{
// when finished
try
{
var result = sub.BuildResult;
buildManager.EndBuild();
registration.Dispose();
taskSource.TrySetResult(result);
}
catch (Exception e)
{
taskSource.TrySetException(e);
}
}, null);
}
catch (Exception e)
{
taskSource.SetException(e);
}
return taskSource.Task;
}
protected virtual string GetOutputDirectory()
{
var targetPath = _loadedProject.GetPropertyValue("TargetPath");
if (string.IsNullOrEmpty(targetPath))
{
targetPath = _loadedProject.DirectoryPath;
}
return Path.GetDirectoryName(this.GetAbsolutePath(targetPath));
}
protected virtual string GetAssemblyName()
{
var assemblyName = _loadedProject.GetPropertyValue("AssemblyName");
if (string.IsNullOrEmpty(assemblyName))
{
assemblyName = Path.GetFileNameWithoutExtension(_loadedProject.FullPath);
}
return PathUtilities.GetFileName(assemblyName);
}
protected IEnumerable<ProjectFileReference> GetProjectReferences(ProjectInstance executedProject)
{
return executedProject
.GetItems("ProjectReference")
.Where(i => !string.Equals(
i.GetMetadataValue("ReferenceOutputAssembly"),
bool.FalseString,
StringComparison.OrdinalIgnoreCase))
.Select(CreateProjectFileReference);
}
/// <summary>
/// Create a <see cref="ProjectFileReference"/> from a ProjectReference node in the MSBuild file.
/// </summary>
protected virtual ProjectFileReference CreateProjectFileReference(ProjectItemInstance reference)
{
return new ProjectFileReference(
path: reference.EvaluatedInclude,
aliases: ImmutableArray<string>.Empty);
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetDocumentsFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("Compile");
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetMetadataReferencesFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("ReferencePath");
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetAnalyzerReferencesFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("Analyzer");
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetAdditionalFilesFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("AdditionalFiles");
}
public MSB.Evaluation.ProjectProperty GetProperty(string name)
{
return _loadedProject.GetProperty(name);
}
protected IEnumerable<MSB.Framework.ITaskItem> GetTaskItems(MSB.Execution.ProjectInstance executedProject, string itemType)
{
return executedProject.GetItems(itemType);
}
protected string GetItemString(MSB.Execution.ProjectInstance executedProject, string itemType)
{
string text = "";
foreach (var item in executedProject.GetItems(itemType))
{
if (text.Length > 0)
{
text = text + " ";
}
text = text + item.EvaluatedInclude;
}
return text;
}
protected string ReadPropertyString(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return this.ReadPropertyString(executedProject, propertyName, propertyName);
}
protected string ReadPropertyString(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
var executedProperty = executedProject.GetProperty(executedPropertyName);
if (executedProperty != null)
{
return executedProperty.EvaluatedValue;
}
var evaluatedProperty = _loadedProject.GetProperty(evaluatedPropertyName);
if (evaluatedProperty != null)
{
return evaluatedProperty.EvaluatedValue;
}
return null;
}
protected bool ReadPropertyBool(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToBool(ReadPropertyString(executedProject, propertyName));
}
protected bool ReadPropertyBool(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToBool(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static bool ConvertToBool(string value)
{
return value != null && (string.Equals("true", value, StringComparison.OrdinalIgnoreCase) ||
string.Equals("On", value, StringComparison.OrdinalIgnoreCase));
}
protected int ReadPropertyInt(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToInt(ReadPropertyString(executedProject, propertyName));
}
protected int ReadPropertyInt(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToInt(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static int ConvertToInt(string value)
{
if (value == null)
{
return 0;
}
else
{
int result;
int.TryParse(value, out result);
return result;
}
}
protected ulong ReadPropertyULong(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToULong(ReadPropertyString(executedProject, propertyName));
}
protected ulong ReadPropertyULong(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToULong(this.ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static ulong ConvertToULong(string value)
{
if (value == null)
{
return 0;
}
else
{
ulong result;
ulong.TryParse(value, out result);
return result;
}
}
protected TEnum? ReadPropertyEnum<TEnum>(MSB.Execution.ProjectInstance executedProject, string propertyName)
where TEnum : struct
{
return ConvertToEnum<TEnum>(ReadPropertyString(executedProject, propertyName));
}
protected TEnum? ReadPropertyEnum<TEnum>(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
where TEnum : struct
{
return ConvertToEnum<TEnum>(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static TEnum? ConvertToEnum<TEnum>(string value)
where TEnum : struct
{
if (value == null)
{
return null;
}
else
{
TEnum result;
if (Enum.TryParse<TEnum>(value, out result))
{
return result;
}
else
{
return null;
}
}
}
/// <summary>
/// Resolves the given path that is possibly relative to the project directory.
/// </summary>
/// <remarks>
/// The resulting path is absolute but might not be normalized.
/// </remarks>
protected string GetAbsolutePath(string path)
{
// TODO (tomat): should we report an error when drive-relative path (e.g. "C:foo.cs") is encountered?
return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, _loadedProject.DirectoryPath) ?? path);
}
protected string GetDocumentFilePath(MSB.Framework.ITaskItem documentItem)
{
return GetAbsolutePath(documentItem.ItemSpec);
}
protected static bool IsDocumentLinked(MSB.Framework.ITaskItem documentItem)
{
return !string.IsNullOrEmpty(documentItem.GetMetadata("Link"));
}
private IDictionary<string, MSB.Evaluation.ProjectItem> _documents = null;
protected bool IsDocumentGenerated(MSB.Framework.ITaskItem documentItem)
{
if (_documents == null)
{
_documents = new Dictionary<string, MSB.Evaluation.ProjectItem>();
foreach (var item in _loadedProject.GetItems("compile"))
{
_documents[GetAbsolutePath(item.EvaluatedInclude)] = item;
}
}
return !_documents.ContainsKey(GetAbsolutePath(documentItem.ItemSpec));
}
protected static string GetDocumentLogicalPath(MSB.Framework.ITaskItem documentItem, string projectDirectory)
{
var link = documentItem.GetMetadata("Link");
if (!string.IsNullOrEmpty(link))
{
// if a specific link is specified in the project file then use it to form the logical path.
return link;
}
else
{
var result = documentItem.ItemSpec;
if (Path.IsPathRooted(result))
{
// If we have an absolute path, there are two possibilities:
result = Path.GetFullPath(result);
// If the document is within the current project directory (or subdirectory), then the logical path is the relative path
// from the project's directory.
if (result.StartsWith(projectDirectory, StringComparison.OrdinalIgnoreCase))
{
result = result.Substring(projectDirectory.Length);
}
else
{
// if the document lies outside the project's directory (or subdirectory) then place it logically at the root of the project.
// if more than one document ends up with the same logical name then so be it (the workspace will survive.)
return Path.GetFileName(result);
}
}
return result;
}
}
protected string GetReferenceFilePath(ProjectItemInstance projectItem)
{
return GetAbsolutePath(projectItem.EvaluatedInclude);
}
public void AddDocument(string filePath, string logicalPath = null)
{
var relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
Dictionary<string, string> metadata = null;
if (logicalPath != null && relativePath != logicalPath)
{
metadata = new Dictionary<string, string>();
metadata.Add("link", logicalPath);
relativePath = filePath; // link to full path
}
_loadedProject.AddItem("Compile", relativePath, metadata);
}
public void RemoveDocument(string filePath)
{
var relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
var items = _loadedProject.GetItems("Compile");
var item = items.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, filePath));
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
public void AddMetadataReference(MetadataReference reference, AssemblyIdentity identity)
{
var peRef = reference as PortableExecutableReference;
if (peRef != null && peRef.FilePath != null)
{
var metadata = new Dictionary<string, string>();
if (!peRef.Properties.Aliases.IsEmpty)
{
metadata.Add("Aliases", string.Join(",", peRef.Properties.Aliases));
}
if (IsInGAC(peRef.FilePath) && identity != null)
{
_loadedProject.AddItem("Reference", identity.GetDisplayName(), metadata);
}
else
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, peRef.FilePath);
_loadedProject.AddItem("Reference", relativePath, metadata);
}
}
}
private bool IsInGAC(string filePath)
{
return filePath.Contains(@"\GAC_MSIL\");
}
public void RemoveMetadataReference(MetadataReference reference, AssemblyIdentity identity)
{
var peRef = reference as PortableExecutableReference;
if (peRef != null && peRef.FilePath != null)
{
var item = FindReferenceItem(identity, peRef.FilePath);
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
}
private MSB.Evaluation.ProjectItem FindReferenceItem(AssemblyIdentity identity, string filePath)
{
var references = _loadedProject.GetItems("Reference");
MSB.Evaluation.ProjectItem item = null;
if (identity != null)
{
var shortAssemblyName = identity.Name;
var fullAssemblyName = identity.ToAssemblyName().FullName;
// check for short name match
item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, shortAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
// check for full name match
if (item == null)
{
item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, fullAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
}
}
// check for file path match
if (item == null)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
item = references.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, filePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath));
}
// check for partial name match
if (item == null && identity != null)
{
var partialName = identity.Name + ",";
var items = references.Where(it => it.EvaluatedInclude.StartsWith(partialName, StringComparison.OrdinalIgnoreCase)).ToList();
if (items.Count == 1)
{
item = items[0];
}
}
return item;
}
public void AddProjectReference(string projectName, ProjectFileReference reference)
{
var metadata = new Dictionary<string, string>();
metadata.Add("Name", projectName);
if (!reference.Aliases.IsEmpty)
{
metadata.Add("Aliases", string.Join(",", reference.Aliases));
}
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, reference.Path);
_loadedProject.AddItem("ProjectReference", relativePath, metadata);
}
public void RemoveProjectReference(string projectName, string projectFilePath)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);
var item = FindProjectReferenceItem(projectName, projectFilePath);
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
private MSB.Evaluation.ProjectItem FindProjectReferenceItem(string projectName, string projectFilePath)
{
var references = _loadedProject.GetItems("ProjectReference");
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);
MSB.Evaluation.ProjectItem item = null;
// find by project file path
item = references.First(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, projectFilePath));
// try to find by project name
if (item == null)
{
item = references.First(it => string.Compare(projectName, it.GetMetadataValue("Name"), StringComparison.OrdinalIgnoreCase) == 0);
}
return item;
}
public void AddAnalyzerReference(AnalyzerReference reference)
{
var fileRef = reference as AnalyzerFileReference;
if (fileRef != null)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
_loadedProject.AddItem("Analyzer", relativePath);
}
}
public void RemoveAnalyzerReference(AnalyzerReference reference)
{
var fileRef = reference as AnalyzerFileReference;
if (fileRef != null)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
var analyzers = _loadedProject.GetItems("Analyzer");
var item = analyzers.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, fileRef.FullPath));
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
}
public void Save()
{
_loadedProject.Save();
}
internal static bool TryGetOutputKind(string outputKind, out OutputKind kind)
{
if (string.Equals(outputKind, "Library", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.DynamicallyLinkedLibrary;
return true;
}
else if (string.Equals(outputKind, "Exe", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.ConsoleApplication;
return true;
}
else if (string.Equals(outputKind, "WinExe", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.WindowsApplication;
return true;
}
else if (string.Equals(outputKind, "Module", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.NetModule;
return true;
}
else if (string.Equals(outputKind, "WinMDObj", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.WindowsRuntimeMetadata;
return true;
}
else
{
kind = OutputKind.DynamicallyLinkedLibrary;
return false;
}
}
}
}
| |
//
// Copyright (c) 2012 Krueger Systems, 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.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace SQLite.Net.Async
{
public class SQLiteAsyncConnection
{
[NotNull] private readonly Func<SQLiteConnectionWithLock> _sqliteConnectionFunc;
private readonly TaskCreationOptions _taskCreationOptions;
[CanBeNull] private readonly TaskScheduler _taskScheduler;
/// <summary>
/// Create a new async connection
/// </summary>
/// <param name="sqliteConnectionFunc"></param>
/// <param name="taskScheduler">
/// If null this parameter will be TaskScheduler.Default (evaluated when used in each method,
/// not in ctor)
/// </param>
/// <param name="taskCreationOptions">Defaults to DenyChildAttach</param>
[PublicAPI]
public SQLiteAsyncConnection(
[NotNull] Func<SQLiteConnectionWithLock> sqliteConnectionFunc, [CanBeNull] TaskScheduler taskScheduler = null,
TaskCreationOptions taskCreationOptions = TaskCreationOptions.None)
{
_sqliteConnectionFunc = sqliteConnectionFunc;
_taskCreationOptions = taskCreationOptions;
_taskScheduler = taskScheduler;
}
[PublicAPI]
protected SQLiteConnectionWithLock GetConnection()
{
return _sqliteConnectionFunc();
}
[PublicAPI]
public Task<CreateTablesResult> CreateTableAsync<T>(CancellationToken cancellationToken = default (CancellationToken))
where T : class
{
return CreateTablesAsync(cancellationToken, typeof (T));
}
[PublicAPI]
public Task<CreateTablesResult> CreateTablesAsync<T, T2>(CancellationToken cancellationToken = default (CancellationToken))
where T : class
where T2 : class
{
return CreateTablesAsync(cancellationToken, typeof (T), typeof (T2));
}
[PublicAPI]
public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3>(CancellationToken cancellationToken = default (CancellationToken))
where T : class
where T2 : class
where T3 : class
{
return CreateTablesAsync(cancellationToken, typeof (T), typeof (T2), typeof (T3));
}
[PublicAPI]
public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4>(CancellationToken cancellationToken = default (CancellationToken))
where T : class
where T2 : class
where T3 : class
where T4 : class
{
return CreateTablesAsync(cancellationToken, typeof (T), typeof (T2), typeof (T3), typeof (T4));
}
[PublicAPI]
public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4, T5>(CancellationToken cancellationToken = default (CancellationToken))
where T : class
where T2 : class
where T3 : class
where T4 : class
where T5 : class
{
return CreateTablesAsync(cancellationToken, typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5));
}
[PublicAPI]
public Task<CreateTablesResult> CreateTablesAsync([NotNull] params Type[] types)
{
if (types == null)
{
throw new ArgumentNullException("types");
}
return CreateTablesAsync(CancellationToken.None, types);
}
[PublicAPI]
public Task<CreateTablesResult> CreateTablesAsync(CancellationToken cancellationToken = default(CancellationToken), [NotNull] params Type[] types)
{
if (types == null)
{
throw new ArgumentNullException("types");
}
return Task.Factory.StartNew(() =>
{
var result = new CreateTablesResult();
var conn = GetConnection();
using (conn.Lock())
{
foreach (var type in types)
{
var aResult = conn.CreateTable(type);
result.Results[type] = aResult;
}
}
return result;
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<int> DropTableAsync<T>(CancellationToken cancellationToken = default (CancellationToken))
where T : class
{
return DropTableAsync(typeof (T), cancellationToken);
}
[PublicAPI]
public Task<int> DropTableAsync(Type t, CancellationToken cancellationToken = default (CancellationToken))
{
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.DropTable(t);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<int> InsertAsync([NotNull] object item, CancellationToken cancellationToken = default (CancellationToken))
{
if (item == null)
{
throw new ArgumentNullException("item");
}
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.Insert(item);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<int> UpdateAsync([NotNull] object item, CancellationToken cancellationToken = default (CancellationToken))
{
if (item == null)
{
throw new ArgumentNullException("item");
}
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.Update(item);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<int> InsertOrReplaceAsync([NotNull] object item, CancellationToken cancellationToken = default (CancellationToken))
{
if (item == null)
{
throw new ArgumentNullException("item");
}
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.InsertOrReplace(item);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<int> DeleteAsync([NotNull] object item, CancellationToken cancellationToken = default (CancellationToken))
{
if (item == null)
{
throw new ArgumentNullException("item");
}
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.Delete(item);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<int> DeleteAllAsync<T>(CancellationToken cancellationToken = default (CancellationToken))
{
return DeleteAllAsync(typeof(T), cancellationToken);
}
[PublicAPI]
public Task<int> DeleteAllAsync(Type t, CancellationToken cancellationToken = default (CancellationToken))
{
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.DeleteAll(t);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<int> DeleteAsync<T>([NotNull] object pk, CancellationToken cancellationToken = default (CancellationToken))
{
if (pk == null)
{
throw new ArgumentNullException("pk");
}
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.Delete<T>(pk);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<T> GetAsync<T>([NotNull] object pk, CancellationToken cancellationToken = default(CancellationToken))
where T : class
{
if (pk == null)
{
throw new ArgumentNullException("pk");
}
return Task.Factory.StartNew(() =>
{
cancellationToken.ThrowIfCancellationRequested();
var conn = GetConnection();
using (conn.Lock())
{
cancellationToken.ThrowIfCancellationRequested();
return conn.Get<T>(pk);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<T> FindAsync<T>([NotNull] object pk, CancellationToken cancellationToken = default (CancellationToken))
where T : class
{
if (pk == null)
{
throw new ArgumentNullException("pk");
}
return Task.Factory.StartNew(() =>
{
cancellationToken.ThrowIfCancellationRequested();
var conn = GetConnection();
using (conn.Lock())
{
cancellationToken.ThrowIfCancellationRequested();
return conn.Find<T>(pk);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<T> GetAsync<T>([NotNull] Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default (CancellationToken))
where T : class
{
if (predicate == null)
{
throw new ArgumentNullException("predicate");
}
return Task.Factory.StartNew(() =>
{
cancellationToken.ThrowIfCancellationRequested();
var conn = GetConnection();
using (conn.Lock())
{
cancellationToken.ThrowIfCancellationRequested();
return conn.Get(predicate);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<T> FindAsync<T>([NotNull] Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default(CancellationToken))
where T : class
{
if (predicate == null)
{
throw new ArgumentNullException("predicate");
}
return Task.Factory.StartNew(() =>
{
cancellationToken.ThrowIfCancellationRequested();
var conn = GetConnection();
using (conn.Lock())
{
cancellationToken.ThrowIfCancellationRequested();
return conn.Find(predicate);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<int> ExecuteAsync([NotNull] string query, [NotNull] params object[] args)
{
return ExecuteAsync(CancellationToken.None, query, args);
}
[PublicAPI]
public Task<int> ExecuteAsync(CancellationToken cancellationToken, [NotNull] string query, [NotNull] params object[] args)
{
if (query == null)
{
throw new ArgumentNullException("query");
}
if (args == null)
{
throw new ArgumentNullException("args");
}
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.Execute(query, args);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<int> InsertAllAsync([NotNull] IEnumerable items, CancellationToken cancellationToken = default(CancellationToken))
{
if (items == null)
{
throw new ArgumentNullException("items");
}
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.InsertAll(items);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<int> InsertOrReplaceAllAsync([NotNull] IEnumerable items, CancellationToken cancellationToken = default(CancellationToken))
{
if (items == null)
{
throw new ArgumentNullException("items");
}
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.InsertOrReplaceAll(items);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<int> UpdateAllAsync([NotNull] IEnumerable items, CancellationToken cancellationToken = default(CancellationToken))
{
if (items == null)
{
throw new ArgumentNullException("items");
}
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.UpdateAll(items);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[Obsolete(
"Will cause a deadlock if any call in action ends up in a different thread. Use RunInTransactionAsync(Action<SQLiteConnection>) instead."
)]
[PublicAPI]
public Task RunInTransactionAsync([NotNull] Action<SQLiteAsyncConnection> action, CancellationToken cancellationToken = default(CancellationToken))
{
if (action == null)
{
throw new ArgumentNullException("action");
}
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
conn.BeginTransaction();
try
{
action(this);
conn.Commit();
}
catch (Exception)
{
conn.Rollback();
throw;
}
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task RunInTransactionAsync([NotNull] Action<SQLiteConnection> action, CancellationToken cancellationToken = default(CancellationToken))
{
if (action == null)
{
throw new ArgumentNullException("action");
}
return Task.Factory.StartNew(() =>
{
cancellationToken.ThrowIfCancellationRequested();
var conn = GetConnection();
using (conn.Lock())
{
cancellationToken.ThrowIfCancellationRequested();
conn.BeginTransaction();
try
{
action(conn);
conn.Commit();
}
catch (Exception)
{
conn.Rollback();
throw;
}
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public AsyncTableQuery<T> Table<T>()
where T : class
{
//
// This isn't async as the underlying connection doesn't go out to the database
// until the query is performed. The Async methods are on the query iteself.
//
var conn = GetConnection();
return new AsyncTableQuery<T>(conn.Table<T>(), _taskScheduler, _taskCreationOptions);
}
[PublicAPI]
public Task<T> ExecuteScalarAsync<T>([NotNull] string sql, [NotNull] params object[] args)
{
return ExecuteScalarAsync<T>(CancellationToken.None, sql, args);
}
[PublicAPI]
public Task<T> ExecuteScalarAsync<T>(CancellationToken cancellationToken, [NotNull] string sql, [NotNull] params object[] args)
{
if (sql == null)
{
throw new ArgumentNullException("sql");
}
if (args == null)
{
throw new ArgumentNullException("args");
}
return Task.Factory.StartNew(() =>
{
cancellationToken.ThrowIfCancellationRequested();
var conn = GetConnection();
using (conn.Lock())
{
cancellationToken.ThrowIfCancellationRequested();
var command = conn.CreateCommand(sql, args);
return command.ExecuteScalar<T>();
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
[PublicAPI]
public Task<List<T>> QueryAsync<T>([NotNull] string sql, [NotNull] params object[] args)
where T : class
{
return QueryAsync<T>(CancellationToken.None, sql, args);
}
[PublicAPI]
public Task<List<T>> QueryAsync<T>(CancellationToken cancellationToken, [NotNull] string sql, params object[] args)
where T : class
{
if (sql == null)
{
throw new ArgumentNullException("sql");
}
if (args == null)
{
throw new ArgumentNullException("args");
}
return Task.Factory.StartNew(() =>
{
cancellationToken.ThrowIfCancellationRequested();
var conn = GetConnection();
using (conn.Lock())
{
cancellationToken.ThrowIfCancellationRequested();
return conn.Query<T>(sql, args);
}
}, cancellationToken, _taskCreationOptions, _taskScheduler ?? TaskScheduler.Default);
}
}
}
| |
// Copyright (c) 2017 Jan Pluskal, Viliam Letavay
//
//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.
/**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
using System;
using System.Collections.Generic;
using System.Text;
using Thrift.Protocol;
namespace Netfox.SnooperMessenger.Protocol
{
#if !SILVERLIGHT
[Serializable]
#endif
public partial class ConnectMessage : TBase
{
private string _ClientIdentifier;
private string _WillTopic;
private string _WillMessage;
private ClientInfo _ClientInfo;
private string _Password;
private List<string> _GetDiffsRequests;
public string ClientIdentifier
{
get
{
return _ClientIdentifier;
}
set
{
__isset.ClientIdentifier = true;
this._ClientIdentifier = value;
}
}
public string WillTopic
{
get
{
return _WillTopic;
}
set
{
__isset.WillTopic = true;
this._WillTopic = value;
}
}
public string WillMessage
{
get
{
return _WillMessage;
}
set
{
__isset.WillMessage = true;
this._WillMessage = value;
}
}
public ClientInfo ClientInfo
{
get
{
return _ClientInfo;
}
set
{
__isset.ClientInfo = true;
this._ClientInfo = value;
}
}
public string Password
{
get
{
return _Password;
}
set
{
__isset.Password = true;
this._Password = value;
}
}
public List<string> GetDiffsRequests
{
get
{
return _GetDiffsRequests;
}
set
{
__isset.GetDiffsRequests = true;
this._GetDiffsRequests = value;
}
}
public Isset __isset;
#if !SILVERLIGHT
[Serializable]
#endif
public struct Isset {
public bool ClientIdentifier;
public bool WillTopic;
public bool WillMessage;
public bool ClientInfo;
public bool Password;
public bool GetDiffsRequests;
}
public ConnectMessage() {
}
public void Read (TProtocol iprot)
{
iprot.IncrementRecursionDepth();
try
{
TField field;
iprot.ReadStructBegin();
while (true)
{
field = iprot.ReadFieldBegin();
if (field.Type == TType.Stop) {
break;
}
switch (field.ID)
{
case 1:
if (field.Type == TType.String) {
ClientIdentifier = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 2:
if (field.Type == TType.String) {
WillTopic = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 3:
if (field.Type == TType.String) {
WillMessage = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 4:
if (field.Type == TType.Struct) {
ClientInfo = new ClientInfo();
ClientInfo.Read(iprot);
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 5:
if (field.Type == TType.String) {
Password = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 6:
if (field.Type == TType.List) {
{
GetDiffsRequests = new List<string>();
TList _list18 = iprot.ReadListBegin();
for( int _i19 = 0; _i19 < _list18.Count; ++_i19)
{
string _elem20;
_elem20 = iprot.ReadString();
GetDiffsRequests.Add(_elem20);
}
iprot.ReadListEnd();
}
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
default:
TProtocolUtil.Skip(iprot, field.Type);
break;
}
iprot.ReadFieldEnd();
}
iprot.ReadStructEnd();
}
finally
{
iprot.DecrementRecursionDepth();
}
}
public void Write(TProtocol oprot) {
oprot.IncrementRecursionDepth();
try
{
TStruct struc = new TStruct("ConnectMessage");
oprot.WriteStructBegin(struc);
TField field = new TField();
if (ClientIdentifier != null && __isset.ClientIdentifier) {
field.Name = "ClientIdentifier";
field.Type = TType.String;
field.ID = 1;
oprot.WriteFieldBegin(field);
oprot.WriteString(ClientIdentifier);
oprot.WriteFieldEnd();
}
if (WillTopic != null && __isset.WillTopic) {
field.Name = "WillTopic";
field.Type = TType.String;
field.ID = 2;
oprot.WriteFieldBegin(field);
oprot.WriteString(WillTopic);
oprot.WriteFieldEnd();
}
if (WillMessage != null && __isset.WillMessage) {
field.Name = "WillMessage";
field.Type = TType.String;
field.ID = 3;
oprot.WriteFieldBegin(field);
oprot.WriteString(WillMessage);
oprot.WriteFieldEnd();
}
if (ClientInfo != null && __isset.ClientInfo) {
field.Name = "ClientInfo";
field.Type = TType.Struct;
field.ID = 4;
oprot.WriteFieldBegin(field);
ClientInfo.Write(oprot);
oprot.WriteFieldEnd();
}
if (Password != null && __isset.Password) {
field.Name = "Password";
field.Type = TType.String;
field.ID = 5;
oprot.WriteFieldBegin(field);
oprot.WriteString(Password);
oprot.WriteFieldEnd();
}
if (GetDiffsRequests != null && __isset.GetDiffsRequests) {
field.Name = "GetDiffsRequests";
field.Type = TType.List;
field.ID = 6;
oprot.WriteFieldBegin(field);
{
oprot.WriteListBegin(new TList(TType.String, GetDiffsRequests.Count));
foreach (string _iter21 in GetDiffsRequests)
{
oprot.WriteString(_iter21);
}
oprot.WriteListEnd();
}
oprot.WriteFieldEnd();
}
oprot.WriteFieldStop();
oprot.WriteStructEnd();
}
finally
{
oprot.DecrementRecursionDepth();
}
}
public override string ToString() {
StringBuilder __sb = new StringBuilder("ConnectMessage(");
bool __first = true;
if (ClientIdentifier != null && __isset.ClientIdentifier) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("ClientIdentifier: ");
__sb.Append(ClientIdentifier);
}
if (WillTopic != null && __isset.WillTopic) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("WillTopic: ");
__sb.Append(WillTopic);
}
if (WillMessage != null && __isset.WillMessage) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("WillMessage: ");
__sb.Append(WillMessage);
}
if (ClientInfo != null && __isset.ClientInfo) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("ClientInfo: ");
__sb.Append(ClientInfo== null ? "<null>" : ClientInfo.ToString());
}
if (Password != null && __isset.Password) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Password: ");
__sb.Append(Password);
}
if (GetDiffsRequests != null && __isset.GetDiffsRequests) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("GetDiffsRequests: ");
__sb.Append(GetDiffsRequests);
}
__sb.Append(")");
return __sb.ToString();
}
}
}
| |
#region MIT license
//
// MIT license
//
// Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne
//
// 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.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System.Reflection;
using DbLinq;
using DbLinq.Util;
#if MONO_STRICT
namespace System.Data.Linq
#else
namespace DbLinq.Data.Linq
#endif
{
public sealed class EntitySet<TEntity> : ICollection, ICollection<TEntity>, IEnumerable, IEnumerable<TEntity>, IList, IList<TEntity>, IListSource
where TEntity : class
{
private readonly Action<TEntity> onAdd;
private readonly Action<TEntity> onRemove;
private IEnumerable<TEntity> deferredSource;
private bool deferred;
private bool assignedValues;
private List<TEntity> source;
private List<TEntity> Source
{
get
{
if (source != null)
return source;
if (deferredSource != null)
return source = deferredSource.ToList();
if (nestedQueryPredicate != null && context != null)
{
var otherTable = context.GetTable(typeof(TEntity));
var query = (IQueryable<TEntity>) context.GetOtherTableQuery(nestedQueryPredicate, nestedQueryParam, typeof(TEntity), otherTable);
return source = query.ToList();
}
return source = new List<TEntity>();
}
}
/// <summary>
/// Gets or sets a value indicating whether this instance has loaded or assigned values.
/// </summary>
/// <value>
/// <c>true</c> if this instance has loaded or assigned values; otherwise, <c>false</c>.
/// </value>
public bool HasAssignedValues
{
get { return assignedValues; }
}
public bool HasLoadedValues
{
get { return source != null; }
}
/// <summary>
/// Gets a value indicating whether this instance has loaded or assigned values.
/// </summary>
/// <value>
/// <c>true</c> if this instance has loaded or assigned values; otherwise, <c>false</c>.
/// </value>
public bool HasLoadedOrAssignedValues
{
get { return HasLoadedValues || HasAssignedValues; }
}
/// <summary>
/// Initializes a new instance of the <see cref="EntitySet<TEntity>"/> class.
/// </summary>
/// <param name="onAdd">The on add.</param>
/// <param name="onRemove">The on remove.</param>
[DbLinqToDo]
public EntitySet(Action<TEntity> onAdd, Action<TEntity> onRemove)
: this()
{
this.onAdd = onAdd;
this.onRemove = onRemove;
}
/// <summary>
/// Initializes a new instance of the <see cref="EntitySet<TEntity>"/> class.
/// </summary>
public EntitySet()
{
}
DataContext context;
internal EntitySet(DataContext context)
: this()
{
this.context = context;
}
/// <summary>
/// entry point for 'foreach' statement.
/// </summary>
public IEnumerator<TEntity> GetEnumerator()
{
deferred = false;
return Source.GetEnumerator();
}
/// <summary>
/// Enumerates all entities
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Gets the source expression (used to nest queries)
/// </summary>
/// <value>The expression.</value>
internal Expression Expression
{
get
{
if (deferred && this.deferredSource is IQueryable<TEntity>)
return (deferredSource as IQueryable<TEntity>).Expression;
else
return Expression.Constant(this);
}
}
/// <summary>
/// Adds a row
/// </summary>
public void Add(TEntity entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
if (Source.Contains (entity))
return;
Source.Add(entity);
OnAdd(entity);
ListChangedEventHandler handler = ListChanged;
if (!deferred && deferredSource != null && handler != null)
handler(this, new ListChangedEventArgs(ListChangedType.ItemAdded, Source.Count - 1));
}
ParameterExpression nestedQueryParam;
BinaryExpression nestedQueryPredicate;
internal void Add(KeyValuePair<object, MemberInfo> info)
{
var value = info.Key;
var member = info.Value;
if (nestedQueryParam == null)
nestedQueryParam = Expression.Parameter(typeof(TEntity), "other");
var propType = member.GetMemberType();
BinaryExpression comp;
if (!propType.IsNullable())
{
comp = Expression.Equal(Expression.Constant(value),
Expression.MakeMemberAccess(nestedQueryParam, member));
}
else
{
var valueProp = propType.GetProperty("Value");
comp = Expression.Equal(Expression.Constant(value),
Expression.MakeMemberAccess(
Expression.MakeMemberAccess(nestedQueryParam, member),
valueProp));
}
nestedQueryPredicate = nestedQueryPredicate == null
? comp
: Expression.And(nestedQueryPredicate, comp);
}
[DbLinqToDo]
bool IListSource.ContainsListCollection
{
get { throw new NotImplementedException(); }
}
IList IListSource.GetList()
{
//It seems that Microsoft is doing a similar thing in L2SQL, matter of fact, after doing a GetList().Add(new TEntity()), HasAssignedValues continues to be false
//This seems like a bug on their end, but we'll do the same for consistency
return this;
}
#region IList<TEntity> Members
/// <summary>
/// Returns entity's index
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns></returns>
public int IndexOf(TEntity entity)
{
deferred = false;
return Source.IndexOf(entity);
}
/// <summary>
/// Inserts entity at specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="entity">The entity.</param>
public void Insert(int index, TEntity entity)
{
if (Source.Contains(entity))
throw new ArgumentOutOfRangeException();
OnAdd(entity);
deferred = false;
Source.Insert(index, entity);
ListChangedEventHandler handler = ListChanged;
if (handler != null)
handler(this, new ListChangedEventArgs(ListChangedType.ItemAdded, index));
}
/// <summary>
/// Removes entity at specified index
/// </summary>
/// <param name="index"></param>
public void RemoveAt(int index)
{
deferred = false;
var item = Source[index];
Source.RemoveAt(index);
OnRemove(item);
ListChangedEventHandler handler = ListChanged;
if (handler != null)
handler(this, new ListChangedEventArgs(ListChangedType.ItemDeleted, index));
}
/// <summary>
/// Gets or sets the <see cref="TEntity"/> at the specified index.
/// </summary>
/// <value></value>
public TEntity this[int index]
{
get
{
deferred = false;
return Source[index];
}
set
{
OnRemove(Source[index]);
OnAdd(value);
deferred = false;
var handler = ListChanged;
if (handler != null)
{
handler(this, new ListChangedEventArgs(ListChangedType.ItemDeleted, index));
handler(this, new ListChangedEventArgs(ListChangedType.ItemAdded, index));
}
Source[index] = value;
}
}
#endregion
#region ICollection<TEntity> Members
/// <summary>
/// Removes all items in collection
/// </summary>
public void Clear()
{
ListChangedEventHandler handler = ListChanged;
deferred = false;
assignedValues = true;
if (deferredSource != null && handler != null)
{
foreach (var item in Source)
handler(this, new ListChangedEventArgs(ListChangedType.ItemDeleted, 0));
}
if (handler != null)
handler(this, new ListChangedEventArgs(ListChangedType.Reset, 0));
Source.Clear();
}
/// <summary>
/// Determines whether [contains] [the specified entity].
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>
/// <c>true</c> if [contains] [the specified entity]; otherwise, <c>false</c>.
/// </returns>
[DbLinqToDo]
public bool Contains(TEntity entity)
{
deferred = false;
return Source.Contains(entity);
}
/// <summary>
/// Copies items to target array
/// </summary>
/// <param name="array"></param>
/// <param name="arrayIndex"></param>
public void CopyTo(TEntity[] array, int arrayIndex)
{
deferred = false;
Source.CopyTo(array, arrayIndex);
}
/// <summary>
/// Returns entities count
/// </summary>
public int Count
{
get
{
deferred = false;
return Source.Count;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </summary>
/// <value></value>
/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
/// </returns>
bool ICollection<TEntity>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Removes the specified entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns></returns>
public bool Remove(TEntity entity)
{
int i = Source.IndexOf(entity);
if(i < 0)
return false;
deferred = false;
Source.Remove(entity);
OnRemove(entity);
ListChangedEventHandler handler = ListChanged;
if (deferredSource != null && handler != null)
handler(this, new ListChangedEventArgs(ListChangedType.ItemDeleted, i));
return true;
}
#endregion
#region IList Members
int IList.Add(object value)
{
var v = value as TEntity;
if (v != null && !Contains(v))
{
Add(v);
return Count - 1;
}
throw new ArgumentOutOfRangeException("value");
}
void IList.Clear()
{
this.Clear();
}
bool IList.Contains(object value)
{
var v = value as TEntity;
if (v != null)
return Contains(v);
return false;
}
int IList.IndexOf(object value)
{
return this.IndexOf(value as TEntity);
}
void IList.Insert(int index, object value)
{
this.Insert(index, value as TEntity);
}
bool IList.IsFixedSize
{
get { return false; }
}
bool IList.IsReadOnly
{
get { return false; }
}
void IList.Remove(object value)
{
this.Remove(value as TEntity);
}
void IList.RemoveAt(int index)
{
this.RemoveAt(index);
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
this[index] = value as TEntity;
}
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
for (int i = 0; i < Source.Count; ++i)
{
array.SetValue(this[i], index + i);
}
}
int ICollection.Count
{
get { return this.Count; }
}
[DbLinqToDo]
bool ICollection.IsSynchronized
{
get { throw new NotImplementedException(); }
}
[DbLinqToDo]
object ICollection.SyncRoot
{
get { throw new NotImplementedException(); }
}
#endregion
/// <summary>
/// Gets a value indicating whether this instance is deferred.
/// </summary>
/// <value>
/// <c>true</c> if this instance is deferred; otherwise, <c>false</c>.
/// </value>
public bool IsDeferred
{
get { return deferred; }
}
/// <summary>
/// Adds the range.
/// </summary>
/// <param name="collection">The collection.</param>
public void AddRange(IEnumerable<TEntity> collection)
{
foreach (var entity in collection)
{
Add(entity);
}
}
/// <summary>
/// Assigns the specified entity source.
/// </summary>
/// <param name="entitySource">The entity source.</param>
public void Assign(IEnumerable<TEntity> entitySource)
{
// notifies removals and adds
Clear();
foreach (var entity in entitySource)
{
OnAdd(entity);
}
this.source = entitySource.ToList();
// this.SourceInUse = sourceAsList;
}
/// <summary>
/// Sets the entity source.
/// </summary>
/// <param name="entitySource">The entity source.</param>
public void SetSource(IEnumerable<TEntity> entitySource)
{
#if false
Console.WriteLine("# EntitySet<{0}>.SetSource: HashCode={1}; Stack={2}", typeof(TEntity).Name,
GetHashCode(), new System.Diagnostics.StackTrace());
#endif
if(HasLoadedOrAssignedValues)
throw new InvalidOperationException("The EntitySet is already loaded and the source cannot be changed.");
deferred = true;
deferredSource = entitySource;
}
/// <summary>
/// Loads all entities.
/// </summary>
public void Load()
{
deferred = false;
var _ = Source;
}
/// <summary>
/// Gets a new binding list.
/// </summary>
/// <returns></returns>
public IBindingList GetNewBindingList()
{
return new BindingList<TEntity>(Source.ToList());
}
// TODO: implement handler call
public event ListChangedEventHandler ListChanged;
/// <summary>
/// Called when entity is added.
/// </summary>
/// <param name="entity">The entity.</param>
private void OnAdd(TEntity entity)
{
assignedValues = true;
if (onAdd != null)
onAdd(entity);
}
/// <summary>
/// Called when entity is removed
/// </summary>
/// <param name="entity">The entity.</param>
private void OnRemove(TEntity entity)
{
assignedValues = true;
if (onRemove != null)
onRemove(entity);
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmKeyboardGet
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmKeyboardGet() : base()
{
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_Command1;
public System.Windows.Forms.Button Command1 {
get { return withEventsField_Command1; }
set {
if (withEventsField_Command1 != null) {
withEventsField_Command1.Click -= Command1_Click;
}
withEventsField_Command1 = value;
if (withEventsField_Command1 != null) {
withEventsField_Command1.Click += Command1_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdAccept;
public System.Windows.Forms.Button cmdAccept {
get { return withEventsField_cmdAccept; }
set {
if (withEventsField_cmdAccept != null) {
withEventsField_cmdAccept.Click -= cmdAccept_Click;
}
withEventsField_cmdAccept = value;
if (withEventsField_cmdAccept != null) {
withEventsField_cmdAccept.Click += cmdAccept_Click;
}
}
}
private System.Windows.Forms.TextBox withEventsField_Text1;
public System.Windows.Forms.TextBox Text1 {
get { return withEventsField_Text1; }
set {
if (withEventsField_Text1 != null) {
withEventsField_Text1.KeyDown -= Text1_KeyDown;
withEventsField_Text1.KeyPress -= Text1_KeyPress;
}
withEventsField_Text1 = value;
if (withEventsField_Text1 != null) {
withEventsField_Text1.KeyDown += Text1_KeyDown;
withEventsField_Text1.KeyPress += Text1_KeyPress;
}
}
}
public System.Windows.Forms.Label lblName;
public System.Windows.Forms.Label Label1;
public System.Windows.Forms.Label lblKey;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmKeyboardGet));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.Command1 = new System.Windows.Forms.Button();
this.cmdAccept = new System.Windows.Forms.Button();
this.Text1 = new System.Windows.Forms.TextBox();
this.lblName = new System.Windows.Forms.Label();
this.Label1 = new System.Windows.Forms.Label();
this.lblKey = new System.Windows.Forms.Label();
this.SuspendLayout();
this.ToolTip1.Active = true;
this.ControlBox = false;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.ClientSize = new System.Drawing.Size(250, 76);
this.Location = new System.Drawing.Point(3, 3);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.KeyPreview = false;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmKeyboardGet";
this.Command1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.Command1.Text = "Decline";
this.Command1.Size = new System.Drawing.Size(73, 22);
this.Command1.Location = new System.Drawing.Point(174, 42);
this.Command1.TabIndex = 3;
this.Command1.TabStop = false;
this.Command1.BackColor = System.Drawing.SystemColors.Control;
this.Command1.CausesValidation = true;
this.Command1.Enabled = true;
this.Command1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Command1.Cursor = System.Windows.Forms.Cursors.Default;
this.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Command1.Name = "Command1";
this.cmdAccept.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdAccept.Text = "Accept";
this.cmdAccept.Size = new System.Drawing.Size(73, 22);
this.cmdAccept.Location = new System.Drawing.Point(99, 42);
this.cmdAccept.TabIndex = 2;
this.cmdAccept.TabStop = false;
this.cmdAccept.BackColor = System.Drawing.SystemColors.Control;
this.cmdAccept.CausesValidation = true;
this.cmdAccept.Enabled = true;
this.cmdAccept.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdAccept.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdAccept.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdAccept.Name = "cmdAccept";
this.Text1.AutoSize = false;
this.Text1.Size = new System.Drawing.Size(149, 25);
this.Text1.Location = new System.Drawing.Point(0, 108);
this.Text1.TabIndex = 0;
this.Text1.Text = "Text1";
this.Text1.AcceptsReturn = true;
this.Text1.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.Text1.BackColor = System.Drawing.SystemColors.Window;
this.Text1.CausesValidation = true;
this.Text1.Enabled = true;
this.Text1.ForeColor = System.Drawing.SystemColors.WindowText;
this.Text1.HideSelection = true;
this.Text1.ReadOnly = false;
this.Text1.MaxLength = 0;
this.Text1.Cursor = System.Windows.Forms.Cursors.IBeam;
this.Text1.Multiline = false;
this.Text1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Text1.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.Text1.TabStop = true;
this.Text1.Visible = true;
this.Text1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Text1.Name = "Text1";
this.lblName.Text = "...";
this.lblName.Size = new System.Drawing.Size(241, 16);
this.lblName.Location = new System.Drawing.Point(3, 21);
this.lblName.TabIndex = 5;
this.lblName.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblName.BackColor = System.Drawing.Color.Transparent;
this.lblName.Enabled = true;
this.lblName.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblName.Cursor = System.Windows.Forms.Cursors.Default;
this.lblName.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblName.UseMnemonic = true;
this.lblName.Visible = true;
this.lblName.AutoSize = false;
this.lblName.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lblName.Name = "lblName";
this.Label1.Text = "Press the desired Key combination";
this.Label1.Size = new System.Drawing.Size(241, 16);
this.Label1.Location = new System.Drawing.Point(3, 0);
this.Label1.TabIndex = 4;
this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label1.BackColor = System.Drawing.SystemColors.Control;
this.Label1.Enabled = true;
this.Label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.UseMnemonic = true;
this.Label1.Visible = true;
this.Label1.AutoSize = false;
this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label1.Name = "Label1";
this.lblKey.Text = "Label1";
this.lblKey.Size = new System.Drawing.Size(86, 20);
this.lblKey.Location = new System.Drawing.Point(6, 42);
this.lblKey.TabIndex = 1;
this.lblKey.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblKey.BackColor = System.Drawing.SystemColors.Control;
this.lblKey.Enabled = true;
this.lblKey.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblKey.Cursor = System.Windows.Forms.Cursors.Default;
this.lblKey.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblKey.UseMnemonic = true;
this.lblKey.Visible = true;
this.lblKey.AutoSize = false;
this.lblKey.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblKey.Name = "lblKey";
this.Controls.Add(Command1);
this.Controls.Add(cmdAccept);
this.Controls.Add(Text1);
this.Controls.Add(lblName);
this.Controls.Add(Label1);
this.Controls.Add(lblKey);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace SimpleDispatcher.Present.API.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Configuration;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComProduction.WorkOrder.DS
{
public class PRO_IssuePurposeDS
{
public PRO_IssuePurposeDS()
{
}
private const string THIS = "PCSComProduction.WorkOrder.DS.PRO_IssuePurposeDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to PRO_IssuePurpose
/// </Description>
/// <Inputs>
/// PRO_IssuePurposeVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, October 27, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
PRO_IssuePurposeVO objObject = (PRO_IssuePurposeVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO PRO_IssuePurpose("
+ PRO_IssuePurposeTable.DESCRIPTION_FLD + ")"
+ "VALUES(?)";
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssuePurposeTable.DESCRIPTION_FLD, OleDbType.WChar));
ocmdPCS.Parameters[PRO_IssuePurposeTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from PRO_IssuePurpose
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + PRO_IssuePurposeTable.TABLE_NAME + " WHERE " + "IssuePurposeID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from PRO_IssuePurpose
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// PRO_IssuePurposeVO
/// </Outputs>
/// <Returns>
/// PRO_IssuePurposeVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, October 27, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ PRO_IssuePurposeTable.ISSUEPURPOSEID_FLD + ","
+ PRO_IssuePurposeTable.DESCRIPTION_FLD
+ " FROM " + PRO_IssuePurposeTable.TABLE_NAME
+" WHERE " + PRO_IssuePurposeTable.ISSUEPURPOSEID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
PRO_IssuePurposeVO objObject = new PRO_IssuePurposeVO();
while (odrPCS.Read())
{
objObject.IssuePurposeID = int.Parse(odrPCS[PRO_IssuePurposeTable.ISSUEPURPOSEID_FLD].ToString().Trim());
objObject.Description = odrPCS[PRO_IssuePurposeTable.DESCRIPTION_FLD].ToString().Trim();
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to PRO_IssuePurpose
/// </Description>
/// <Inputs>
/// PRO_IssuePurposeVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
PRO_IssuePurposeVO objObject = (PRO_IssuePurposeVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE PRO_IssuePurpose SET "
+ PRO_IssuePurposeTable.DESCRIPTION_FLD + "= ?"
+" WHERE " + PRO_IssuePurposeTable.ISSUEPURPOSEID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssuePurposeTable.DESCRIPTION_FLD, OleDbType.WChar));
ocmdPCS.Parameters[PRO_IssuePurposeTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_IssuePurposeTable.ISSUEPURPOSEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_IssuePurposeTable.ISSUEPURPOSEID_FLD].Value = objObject.IssuePurposeID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from PRO_IssuePurpose
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, October 27, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ PRO_IssuePurposeTable.ISSUEPURPOSEID_FLD + ","
+ PRO_IssuePurposeTable.DESCRIPTION_FLD
+ " FROM " + PRO_IssuePurposeTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,PRO_IssuePurposeTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, October 27, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ PRO_IssuePurposeTable.ISSUEPURPOSEID_FLD + ","
+ PRO_IssuePurposeTable.DESCRIPTION_FLD
+ " FROM " + PRO_IssuePurposeTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,PRO_IssuePurposeTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
// 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 Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ApplicationSecurityGroupsOperations.
/// </summary>
public static partial class ApplicationSecurityGroupsOperationsExtensions
{
/// <summary>
/// Deletes the specified application security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationSecurityGroupName'>
/// The name of the application security group.
/// </param>
public static void Delete(this IApplicationSecurityGroupsOperations operations, string resourceGroupName, string applicationSecurityGroupName)
{
operations.DeleteAsync(resourceGroupName, applicationSecurityGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified application security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationSecurityGroupName'>
/// The name of the application security group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IApplicationSecurityGroupsOperations operations, string resourceGroupName, string applicationSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, applicationSecurityGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets information about the specified application security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationSecurityGroupName'>
/// The name of the application security group.
/// </param>
public static ApplicationSecurityGroup Get(this IApplicationSecurityGroupsOperations operations, string resourceGroupName, string applicationSecurityGroupName)
{
return operations.GetAsync(resourceGroupName, applicationSecurityGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the specified application security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationSecurityGroupName'>
/// The name of the application security group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ApplicationSecurityGroup> GetAsync(this IApplicationSecurityGroupsOperations operations, string resourceGroupName, string applicationSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, applicationSecurityGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates an application security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationSecurityGroupName'>
/// The name of the application security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update ApplicationSecurityGroup
/// operation.
/// </param>
public static ApplicationSecurityGroup CreateOrUpdate(this IApplicationSecurityGroupsOperations operations, string resourceGroupName, string applicationSecurityGroupName, ApplicationSecurityGroup parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, applicationSecurityGroupName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an application security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationSecurityGroupName'>
/// The name of the application security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update ApplicationSecurityGroup
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ApplicationSecurityGroup> CreateOrUpdateAsync(this IApplicationSecurityGroupsOperations operations, string resourceGroupName, string applicationSecurityGroupName, ApplicationSecurityGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, applicationSecurityGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all application security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<ApplicationSecurityGroup> ListAll(this IApplicationSecurityGroupsOperations operations)
{
return operations.ListAllAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all application security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ApplicationSecurityGroup>> ListAllAsync(this IApplicationSecurityGroupsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the application security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<ApplicationSecurityGroup> List(this IApplicationSecurityGroupsOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the application security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ApplicationSecurityGroup>> ListAsync(this IApplicationSecurityGroupsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified application security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationSecurityGroupName'>
/// The name of the application security group.
/// </param>
public static void BeginDelete(this IApplicationSecurityGroupsOperations operations, string resourceGroupName, string applicationSecurityGroupName)
{
operations.BeginDeleteAsync(resourceGroupName, applicationSecurityGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified application security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationSecurityGroupName'>
/// The name of the application security group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IApplicationSecurityGroupsOperations operations, string resourceGroupName, string applicationSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, applicationSecurityGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates an application security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationSecurityGroupName'>
/// The name of the application security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update ApplicationSecurityGroup
/// operation.
/// </param>
public static ApplicationSecurityGroup BeginCreateOrUpdate(this IApplicationSecurityGroupsOperations operations, string resourceGroupName, string applicationSecurityGroupName, ApplicationSecurityGroup parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, applicationSecurityGroupName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an application security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationSecurityGroupName'>
/// The name of the application security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update ApplicationSecurityGroup
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ApplicationSecurityGroup> BeginCreateOrUpdateAsync(this IApplicationSecurityGroupsOperations operations, string resourceGroupName, string applicationSecurityGroupName, ApplicationSecurityGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, applicationSecurityGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all application security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ApplicationSecurityGroup> ListAllNext(this IApplicationSecurityGroupsOperations operations, string nextPageLink)
{
return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all application security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ApplicationSecurityGroup>> ListAllNextAsync(this IApplicationSecurityGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the application security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ApplicationSecurityGroup> ListNext(this IApplicationSecurityGroupsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the application security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ApplicationSecurityGroup>> ListNextAsync(this IApplicationSecurityGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace PriorityQueue
{
/// <summary>
/// Represent a data type where elements with higher priority are "served" before elements with lower priority.
/// Elements of same priority are served with random order.
/// </summary>
/// <typeparam name="T"></typeparam>
public class MinPriorityQueue<T>
{
private List<T> dataHeap;
private readonly Comparer<T> comp;
/// <summary>
/// Initializes a new instance of the Priority Queue that is empty.
/// Declares an explicit default Comparer to handle comparisons between classes.
/// </summary>
public MinPriorityQueue() : this(Comparer<T>.Default) {}
public MinPriorityQueue(Comparer<T> comp)
{
this.dataHeap = new List<T>();
this.comp = comp;
}
/// <summary>
/// Adds an element to the queue and then heapifies so that the element with highest priority is at front.
/// </summary>
/// <param name="value">The element to enqueue.</param>
public void Enqueue(T value)
{
this.dataHeap.Add(value);
BubbleUp();
}
/// <summary>
/// Removes the element at the front and returns it.
/// </summary>
/// <returns>The element that is removed from the queue front.</returns>
/// <exception cref="InvalidOperationException">The Queue is empty.</exception>
public T Dequeue()
{
if (this.dataHeap.Count <= 0)
{
throw new InvalidOperationException("Cannot Dequeue from empty queue!");
}
T result = dataHeap[0];
int count = this.dataHeap.Count - 1;
dataHeap[0] = dataHeap[count];
dataHeap.RemoveAt(count);
ShiftDown();
return result;
}
/// <summary>
/// A method to maintain the heap order of the elements after enqueue. If the parent of the newly added
/// element is with less priority - swap them.
/// </summary>
private void BubbleUp()
{
int childIndex = dataHeap.Count - 1;
while (childIndex > 0)
{
int parentIndex = (childIndex - 1) / 2;
if (comp.Compare(dataHeap[childIndex], dataHeap[parentIndex]) >= 0)
{
break;
}
SwapAt(childIndex, parentIndex);
childIndex = parentIndex;
}
}
/// <summary>
/// A method to maintain the heap order of the elements after denqueue. We check priorities of both children and parent node.
/// </summary>
private void ShiftDown()
{
int count = this.dataHeap.Count - 1;
int parentIndex = 0;
while (true)
{
int childIndex = parentIndex * 2 + 1;
if (childIndex > count)
{
break;
}
int rightChild = childIndex + 1;
if (rightChild <= count && comp.Compare(dataHeap[rightChild], dataHeap[childIndex]) < 0)
{
childIndex = rightChild;
}
if (comp.Compare(dataHeap[parentIndex], dataHeap[childIndex]) <= 0)
{
break;
}
SwapAt(parentIndex, childIndex);
parentIndex = childIndex;
}
}
/// <summary>Returns the element at the front of the Priority Queue without removing it.</summary>
/// <returns>The element at the front of the queue.</returns>
/// <exception cref="InvalidOperationException">The Queue is empty.</exception>
public T Peek()
{
if (this.dataHeap.Count == 0)
{
throw new InvalidOperationException("Queue is empty.");
}
T frontItem = dataHeap[0];
return frontItem;
}
/// <summary>
/// Gets the number of elements currently contained in the <see cref="PriorityQueue"/>
/// </summary>
/// <returns>The number of elements contained in the <see cref="PriorityQueue"/></returns>
public int Count()
{
return dataHeap.Count;
}
/// <summary>Removes all elements from the queue.</summary>
public void Clear()
{
this.dataHeap.Clear();
}
/// <summary>Copies the queue elements to an existing array, starting at the specified index.</summary>
/// <exception cref="ArgumentNullException">Array is null. </exception>
/// <exception cref="IndexOutOfRangeException">Index is less than zero or bigger than array length. </exception>
/// <exception cref="ArgumentException">The number of elements int the source is greater than the available space.</exception>
public void CopyToArray(T[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException("Array");
}
int length = array.Length;
if (index < 0 || index >= length)
{
throw new IndexOutOfRangeException("Index must be between zero and array length.");
}
if (length - index < this.dataHeap.Count-1)
{
throw new ArgumentException("Queue is bigger than array");
}
T[] data = this.dataHeap.ToArray();
Array.Copy(data, 0, array, index, data.Length);
}
/// <summary>
/// Checks the consistency of the heap.
/// </summary>
/// <returns>True if the heap property is ok.</returns>
public bool IsConsistent()
{
if (dataHeap.Count == 0)
{
return true;
}
int lastIndex = dataHeap.Count - 1;
for (int parentIndex = 0; parentIndex < dataHeap.Count; ++parentIndex)
{
int leftChildIndex = 2 * parentIndex + 1;
int rightChildIndex = 2 * parentIndex + 2;
if (leftChildIndex <= lastIndex && comp.Compare(dataHeap[parentIndex], dataHeap[leftChildIndex]) > 0)
{
return false;
}
if (rightChildIndex <= lastIndex && comp.Compare(dataHeap[parentIndex], dataHeap[rightChildIndex]) > 0)
{
return false;
}
}
return true;
}
/// <summary>
/// A method that swaps the elements at the given indices of the heap.
/// </summary>
/// <param name="first">The first element index.</param>
/// <param name="second">The second element index.</param>
private void SwapAt(int first,int second)
{
T value = dataHeap[first];
dataHeap[first] = dataHeap[second];
dataHeap[second] = value;
}
public override string ToString()
{
string queueString = string.Join("\n", dataHeap.ToArray());
return queueString;
}
}
}
| |
/***************************************************************************
* AsyncWebClient.cs
*
* Copyright (C) 2007 Michael C. Urbanski
* Written by Mike Urbanski <michael.c.urbanski@gmail.com>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.ComponentModel;
namespace Migo.Net
{
enum DownloadType
{
None = 0,
Data = 1,
File = 2,
String = 3
};
public sealed class AsyncWebClient
{
private int range = 0;
private int timeout = (120 * 1000); // 2 minutes
private DateTime ifModifiedSince = DateTime.MinValue;
private static Regex encoding_regexp = new Regex (@"encoding=[""']([^""']+)[""']",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
private string fileName;
private Exception error;
private Uri uri;
private object userState;
private DownloadType type;
private IWebProxy proxy;
private string user_agent;
private Encoding encoding;
private ICredentials credentials;
private HttpWebRequest request;
private HttpWebResponse response;
private WebHeaderCollection headers;
private WebHeaderCollection responseHeaders;
private byte[] result;
private Stream localFile;
private MemoryStream memoryStream;
private TransferStatusManager tsm;
private AutoResetEvent readTimeoutHandle;
private RegisteredWaitHandle registeredTimeoutHandle;
private bool busy;
private bool completed;
private bool cancelled;
private readonly object cancelBusySync = new object ();
public event EventHandler<EventArgs> ResponseReceived;
public event EventHandler<DownloadProgressChangedEventArgs> DownloadProgressChanged;
public event EventHandler<TransferRateUpdatedEventArgs> TransferRateUpdated;
public event EventHandler<AsyncCompletedEventArgs> DownloadFileCompleted;
public event EventHandler<DownloadDataCompletedEventArgs> DownloadDataCompleted;
public event EventHandler<DownloadStringCompletedEventArgs> DownloadStringCompleted;
public ICredentials Credentials {
get { return credentials; }
set { credentials = value; }
}
public Encoding Encoding {
get { return encoding; }
set {
if (value == null) {
throw new ArgumentNullException ("encoding");
} else {
encoding = Encoding.Default;
}
}
}
public WebHeaderCollection Headers {
get { return headers; }
set {
if (value == null) {
headers = new WebHeaderCollection ();
} else {
headers = value;
}
}
}
public DateTime IfModifiedSince {
get { return ifModifiedSince; }
set { ifModifiedSince = value; }
}
public bool IsBusy {
get {
lock (cancelBusySync) {
return busy;
}
}
}
public IWebProxy Proxy {
get { return proxy; }
set { proxy = value; }
}
public int Range {
get { return range; }
set {
if (range > -1) {
range = value;
} else {
throw new ArgumentOutOfRangeException ("Range");
}
}
}
public HttpWebResponse Response {
get { return response; }
}
public WebHeaderCollection ResponseHeaders {
get { return responseHeaders; }
}
public AsyncWebClientStatus Status {
get {
if (type == DownloadType.String) {
throw new InvalidOperationException (
"Status cannot be reported for string downloads"
);
}
lock (tsm.SyncRoot) {
return new AsyncWebClientStatus (
tsm.Progress, tsm.BytesReceived,
tsm.TotalBytes, tsm.TotalBytesReceived
);
}
}
}
public int Timeout {
get { return timeout; }
set {
if (value < -1) {
throw new ArgumentOutOfRangeException (
"Value must be greater than or equal to -1"
);
}
timeout = value;
}
}
private static string default_user_agent;
public static string DefaultUserAgent {
get { return default_user_agent; }
set { default_user_agent = value; }
}
public string UserAgent {
get { return user_agent ?? DefaultUserAgent; }
set { user_agent = value; }
}
private bool Cancelled {
get {
lock (cancelBusySync) {
return cancelled;
}
}
}
public AsyncWebClient ()
{
encoding = Encoding.Default;
tsm = new TransferStatusManager ();
tsm.ProgressChanged += OnDownloadProgressChangedHandler;
}
public void DownloadDataAsync (Uri address)
{
DownloadDataAsync (address, null);
}
public void DownloadDataAsync (Uri address, object userState)
{
if (address == null) {
throw new ArgumentNullException ("address");
}
SetBusy ();
DownloadAsync (address, DownloadType.Data, userState);
}
public void DownloadFileAsync (Uri address, string fileName)
{
DownloadFileAsync (address, fileName, null, null);
}
public void DownloadFileAsync (Uri address, Stream file)
{
DownloadFileAsync (address, null, file, null);
}
public void DownloadFileAsync (Uri address, string file, object userState)
{
DownloadFileAsync (address, file, null, userState);
}
public void DownloadFileAsync (Uri address, Stream file, object userState)
{
DownloadFileAsync (address, null, file, userState);
}
private void DownloadFileAsync (Uri address,
string filePath,
Stream fileStream,
object userState)
{
if (String.IsNullOrEmpty (filePath) &&
fileStream == null || fileStream == Stream.Null) {
throw new ArgumentNullException ("file");
} else if (address == null) {
throw new ArgumentNullException ("address");
} else if (fileStream != null) {
if (!fileStream.CanWrite) {
throw new ArgumentException ("Cannot write to stream");
} else {
localFile = fileStream;
}
} else {
this.fileName = filePath;
}
SetBusy ();
DownloadAsync (address, DownloadType.File, userState);
}
public void DownloadStringAsync (Uri address)
{
DownloadStringAsync (address, null);
}
public void DownloadStringAsync (Uri address, object userState)
{
if (address == null) {
throw new ArgumentNullException ("address");
}
SetBusy ();
DownloadAsync (address, DownloadType.String, userState);
}
public void CancelAsync ()
{
CancelAsync (true);
}
public void CancelAsync (bool deleteFile)
{
if (SetCancelled ()) {
AbortDownload ();
}
}
private void AbortDownload ()
{
AbortDownload (null);
}
private void AbortDownload (Exception e)
{
error = e;
try {
HttpWebRequest req = request;
if (req != null) {
req.Abort();
}
} catch (Exception ae) {
Console.WriteLine ("Abort Download Error: {0}", ae.Message);
}
}
private void Completed ()
{
Completed (null);
}
private void Completed (Exception e)
{
Exception err = (SetCompleted ()) ? e : error;
object statePtr = userState;
byte[] resultPtr = result;
bool cancelledCpy = Cancelled;
CleanUp ();
DownloadCompleted (resultPtr, err, cancelledCpy, statePtr);
Reset ();
}
private void CleanUp ()
{
if (localFile != null) {
localFile.Close ();
localFile = null;
}
if (memoryStream != null) {
memoryStream.Close ();
memoryStream = null;
}
if (response != null) {
response.Close ();
response = null;
}
result = null;
request = null;
CleanUpHandles ();
}
private void CleanUpHandles ()
{
if (registeredTimeoutHandle != null) {
registeredTimeoutHandle.Unregister (readTimeoutHandle);
readTimeoutHandle = null;
}
if (readTimeoutHandle != null) {
readTimeoutHandle.Close ();
readTimeoutHandle = null;
}
}
private bool SetBusy ()
{
bool ret = false;
lock (cancelBusySync) {
if (busy) {
throw new InvalidOperationException (
"Concurrent transfer operations are not supported."
);
} else {
ret = busy = true;
}
}
return ret;
}
private bool SetCancelled ()
{
bool ret = false;
lock (cancelBusySync) {
if (busy && !completed && !cancelled) {
ret = cancelled = true;
}
}
return ret;
}
private bool SetCompleted ()
{
bool ret = false;
lock (cancelBusySync) {
if (busy && !completed && !cancelled) {
ret = completed = true;
}
}
return ret;
}
private void DownloadAsync (Uri uri, DownloadType type, object state)
{
this.uri = uri;
this.type = type;
this.userState = state;
ImplDownloadAsync ();
}
private void ImplDownloadAsync ()
{
try {
tsm.Reset ();
request = PrepRequest (uri);
IAsyncResult ar = request.BeginGetResponse (
OnResponseCallback, null
);
ThreadPool.RegisterWaitForSingleObject (
ar.AsyncWaitHandle,
new WaitOrTimerCallback (OnTimeout),
request, timeout, true
);
} catch (Exception e) {
Completed (e);
}
}
private HttpWebRequest PrepRequest (Uri address)
{
responseHeaders = null;
HttpWebRequest req = HttpWebRequest.Create (address) as HttpWebRequest;
req.AllowAutoRedirect = true;
req.Credentials = credentials;
if (proxy != null) {
req.Proxy = proxy;
}
if (headers != null && headers.Count != 0) {
int rangeHdr = -1;
string expect = headers ["Expect"];
string contentType = headers ["Content-Type"];
string accept = headers ["Accept"];
string connection = headers ["Connection"];
string userAgent = headers ["User-Agent"];
string referer = headers ["Referer"];
string rangeStr = headers ["Range"];
string ifModifiedSince = headers ["If-Modified-Since"];
if (!String.IsNullOrEmpty (rangeStr)) {
Int32.TryParse (rangeStr, out rangeHdr);
}
headers.Remove ("Expect");
headers.Remove ("Content-Type");
headers.Remove ("Accept");
headers.Remove ("Connection");
headers.Remove ("Referer");
headers.Remove ("User-Agent");
headers.Remove ("Range");
headers.Remove ("If-Modified-Since");
req.Headers = headers;
if (!String.IsNullOrEmpty (expect)) {
req.Expect = expect;
}
if (!String.IsNullOrEmpty (accept)) {
req.Accept = accept;
}
if (!String.IsNullOrEmpty (contentType)) {
req.ContentType = contentType;
}
if (!String.IsNullOrEmpty (connection)) {
req.Connection = connection;
}
if (!String.IsNullOrEmpty (userAgent)) {
req.UserAgent = userAgent;
}
if (!String.IsNullOrEmpty (referer)) {
req.Referer = referer;
}
if (rangeHdr > 0) {
req.AddRange (range);
}
if (!String.IsNullOrEmpty (ifModifiedSince)) {
DateTime modDate;
if (DateTime.TryParse (ifModifiedSince, out modDate)) {
req.IfModifiedSince = modDate;
}
}
} else {
if (!String.IsNullOrEmpty (UserAgent)) {
req.UserAgent = UserAgent;
}
if (this.range > 0) {
req.AddRange (this.range);
}
if (this.ifModifiedSince > DateTime.MinValue) {
req.IfModifiedSince = this.ifModifiedSince;
}
}
responseHeaders = null;
return req;
}
private void OnResponseCallback (IAsyncResult ar)
{
Exception err = null;
bool redirect_workaround = false;
try {
response = request.EndGetResponse (ar) as HttpWebResponse;
responseHeaders = response.Headers;
OnResponseReceived ();
Download (response.GetResponseStream ());
} catch (ObjectDisposedException) {
} catch (WebException we) {
if (we.Status != WebExceptionStatus.RequestCanceled) {
err = we;
HttpWebResponse response = we.Response as HttpWebResponse;
if (response != null && response.StatusCode == HttpStatusCode.BadRequest && response.ResponseUri != request.RequestUri) {
Hyena.Log.DebugFormat ("Identified Content-Length: 0 redirection bug for {0}; trying to get {1} directly", request.RequestUri, response.ResponseUri);
redirect_workaround = true;
uri = response.ResponseUri;
ImplDownloadAsync ();
}
}
} catch (Exception e) {
err = e;
} finally {
if (!redirect_workaround) {
Completed (err);
}
}
}
// All of this download code could be abstracted
// and put in a helper class.
private void Download (Stream st)
{
long cLength = (response.ContentLength + range);
if (cLength == 0) {
return;
}
int nread = -1;
int offset = 0;
int length = (cLength == -1 || cLength > 8192) ? 8192 : (int) cLength;
Stream dest = null;
readTimeoutHandle = new AutoResetEvent (false);
byte[] buffer = null;
bool dataDownload = false;
bool writeToStream = false;
if (type != DownloadType.String) {
tsm.TotalBytes = cLength;
tsm.BytesReceivedPreviously = range;
}
switch (type) {
case DownloadType.String:
case DownloadType.Data:
dataDownload = true;
if (cLength != -1) {
length = (int) cLength;
buffer = new byte[cLength];
} else {
writeToStream = true;
buffer = new byte[length];
dest = OpenMemoryStream ();
}
break;
case DownloadType.File:
writeToStream = true;
buffer = new byte [length];
if (localFile == null) {
dest = OpenLocalFile (fileName);
} else {
dest = localFile;
}
break;
}
registeredTimeoutHandle = ThreadPool.RegisterWaitForSingleObject (
readTimeoutHandle, new WaitOrTimerCallback (OnTimeout), null, timeout, false
);
IAsyncResult ar;
while (nread != 0) {
// <hack>
// Yeah, Yeah, Yeah, I'll change this later,
// it's here to get around abort issues.
ar = st.BeginRead (buffer, offset, length, null, null);
nread = st.EndRead (ar);
// need an auxiliary downloader class to replace this.
// </hack>
readTimeoutHandle.Set ();
if (writeToStream) {
dest.Write (buffer, 0, nread);
} else {
offset += nread;
length -= nread;
}
if (type != DownloadType.String) {
tsm.AddBytes (nread);
}
}
CleanUpHandles ();
if (type != DownloadType.String) {
if (tsm.TotalBytes == -1) {
tsm.TotalBytes = tsm.BytesReceived;
}
}
if (dataDownload) {
if (writeToStream) {
result = memoryStream.ToArray ();
} else {
result = buffer;
}
}
}
private Stream OpenLocalFile (string filePath)
{
return File.Open (
filePath, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None
);
}
private MemoryStream OpenMemoryStream ()
{
return memoryStream = new MemoryStream ();
}
private void Reset ()
{
lock (cancelBusySync) {
busy = false;
cancelled = false;
completed = false;
error = null;
fileName = String.Empty;
ifModifiedSince = DateTime.MinValue;
range = 0;
type = DownloadType.None;
uri = null;
userState = null;
}
}
private void DownloadCompleted (byte[] resultPtr,
Exception errPtr,
bool cancelledCpy,
object userStatePtr)
{
switch (type) {
case DownloadType.Data:
OnDownloadDataCompleted (
resultPtr, errPtr, cancelledCpy, userStatePtr
);
break;
case DownloadType.File:
OnDownloadFileCompleted (errPtr, cancelledCpy, userStatePtr);
break;
case DownloadType.String:
string s = null;
if (resultPtr != null) {
try {
s = Encoding.GetString (resultPtr).TrimStart ();
// Workaround if the string is a XML to set the encoding from it
if (s.StartsWith("<?xml")) {
Match match = encoding_regexp.Match (s);
if (match.Success && match.Groups.Count > 0) {
string encodingStr = match.Groups[1].Value;
try {
Encoding enc = Encoding.GetEncoding (encodingStr);
if (!enc.Equals (Encoding)) {
s = enc.GetString (resultPtr);
}
} catch (ArgumentException) {}
}
}
} catch (Exception ex) {
Hyena.Log.DebugException (ex);
s = String.Empty;
}
}
OnDownloadStringCompleted (
s ?? "", errPtr, cancelledCpy, userStatePtr
);
break;
}
}
private void OnTimeout (object state, bool timedOut)
{
if (timedOut) {
if (SetCompleted ()) {
try {
AbortDownload (new WebException (
"The operation timed out", null,
WebExceptionStatus.Timeout, response
));
} finally {
Completed ();
}
}
}
}
private void OnResponseReceived ()
{
EventHandler<EventArgs> handler = ResponseReceived;
if (handler != null) {
handler (this, new EventArgs ());
}
}
private void OnDownloadProgressChanged (long bytesReceived,
long BytesToReceive,
int progressPercentage,
object userState)
{
OnDownloadProgressChanged (
new DownloadProgressChangedEventArgs (
progressPercentage, userState,
bytesReceived, BytesToReceive
)
);
}
private void OnDownloadProgressChanged (DownloadProgressChangedEventArgs args)
{
EventHandler <DownloadProgressChangedEventArgs>
handler = DownloadProgressChanged;
if (handler != null) {
handler (this, args);
}
}
private void OnDownloadProgressChangedHandler (object sender,
DownloadProgressChangedEventArgs e)
{
OnDownloadProgressChanged (
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage,
userState
);
}
private void OnDownloadDataCompleted (byte[] bytes,
Exception error,
bool cancelled,
object userState)
{
OnDownloadDataCompleted (
new DownloadDataCompletedEventArgs (
bytes, error, cancelled, userState
)
);
}
private void OnDownloadDataCompleted (DownloadDataCompletedEventArgs args)
{
EventHandler <DownloadDataCompletedEventArgs>
handler = DownloadDataCompleted;
if (handler != null) {
handler (this, args);
}
}
private void OnDownloadFileCompleted (Exception error,
bool cancelled,
object userState)
{
OnDownloadFileCompleted (
new AsyncCompletedEventArgs (error, cancelled, userState)
);
}
private void OnDownloadFileCompleted (AsyncCompletedEventArgs args)
{
EventHandler <AsyncCompletedEventArgs>
handler = DownloadFileCompleted;
if (handler != null) {
handler (this, args);
}
}
private void OnDownloadStringCompleted (string resultStr,
Exception error,
bool cancelled,
object userState)
{
OnDownloadStringCompleted (
new DownloadStringCompletedEventArgs (
resultStr, error, cancelled, userState
)
);
}
private void OnDownloadStringCompleted (DownloadStringCompletedEventArgs args)
{
EventHandler <DownloadStringCompletedEventArgs>
handler = DownloadStringCompleted;
if (handler != null) {
handler (this, args);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text;
namespace System.Diagnostics
{
/// <summary>
/// Provides version information for a physical file on disk.
/// </summary>
public sealed partial class FileVersionInfo
{
private readonly string _fileName;
private string _companyName;
private string _fileDescription;
private string _fileVersion;
private string _internalName;
private string _legalCopyright;
private string _originalFilename;
private string _productName;
private string _productVersion;
private string _comments;
private string _legalTrademarks;
private string _privateBuild;
private string _specialBuild;
private string _language;
private int _fileMajor;
private int _fileMinor;
private int _fileBuild;
private int _filePrivate;
private int _productMajor;
private int _productMinor;
private int _productBuild;
private int _productPrivate;
private bool _isDebug;
private bool _isPatched;
private bool _isPrivateBuild;
private bool _isPreRelease;
private bool _isSpecialBuild;
/// <summary>
/// Gets the comments associated with the file.
/// </summary>
public string Comments
{
get { return _comments; }
}
/// <summary>
/// Gets the name of the company that produced the file.
/// </summary>
public string CompanyName
{
get { return _companyName; }
}
/// <summary>
/// Gets the build number of the file.
/// </summary>
public int FileBuildPart
{
get { return _fileBuild; }
}
/// <summary>
/// Gets the description of the file.
/// </summary>
public string FileDescription
{
get { return _fileDescription; }
}
/// <summary>
/// Gets the major part of the version number.
/// </summary>
public int FileMajorPart
{
get { return _fileMajor; }
}
/// <summary>
/// Gets the minor part of the version number of the file.
/// </summary>
public int FileMinorPart
{
get { return _fileMinor; }
}
/// <summary>
/// Gets the name of the file that this instance of <see cref="FileVersionInfo" /> describes.
/// </summary>
public string FileName
{
get { return _fileName; }
}
/// <summary>
/// Gets the file private part number.
/// </summary>
public int FilePrivatePart
{
get { return _filePrivate; }
}
/// <summary>
/// Gets the file version number.
/// </summary>
public string FileVersion
{
get { return _fileVersion; }
}
/// <summary>
/// Gets the internal name of the file, if one exists.
/// </summary>
public string InternalName
{
get { return _internalName; }
}
/// <summary>
/// Gets a value that specifies whether the file contains debugging information
/// or is compiled with debugging features enabled.
/// </summary>
public bool IsDebug
{
get { return _isDebug; }
}
/// <summary>
/// Gets a value that specifies whether the file has been modified and is not identical to
/// the original shipping file of the same version number.
/// </summary>
public bool IsPatched
{
get { return _isPatched; }
}
/// <summary>
/// Gets a value that specifies whether the file was built using standard release procedures.
/// </summary>
public bool IsPrivateBuild
{
get { return _isPrivateBuild; }
}
/// <summary>
/// Gets a value that specifies whether the file
/// is a development version, rather than a commercially released product.
/// </summary>
public bool IsPreRelease
{
get { return _isPreRelease; }
}
/// <summary>
/// Gets a value that specifies whether the file is a special build.
/// </summary>
public bool IsSpecialBuild
{
get { return _isSpecialBuild; }
}
/// <summary>
/// Gets the default language string for the version info block.
/// </summary>
public string Language
{
get { return _language; }
}
/// <summary>
/// Gets all copyright notices that apply to the specified file.
/// </summary>
public string LegalCopyright
{
get { return _legalCopyright; }
}
/// <summary>
/// Gets the trademarks and registered trademarks that apply to the file.
/// </summary>
public string LegalTrademarks
{
get { return _legalTrademarks; }
}
/// <summary>
/// Gets the name the file was created with.
/// </summary>
public string OriginalFilename
{
get { return _originalFilename; }
}
/// <summary>
/// Gets information about a private version of the file.
/// </summary>
public string PrivateBuild
{
get { return _privateBuild; }
}
/// <summary>
/// Gets the build number of the product this file is associated with.
/// </summary>
public int ProductBuildPart
{
get { return _productBuild; }
}
/// <summary>
/// Gets the major part of the version number for the product this file is associated with.
/// </summary>
public int ProductMajorPart
{
get { return _productMajor; }
}
/// <summary>
/// Gets the minor part of the version number for the product the file is associated with.
/// </summary>
public int ProductMinorPart
{
get { return _productMinor; }
}
/// <summary>
/// Gets the name of the product this file is distributed with.
/// </summary>
public string ProductName
{
get { return _productName; }
}
/// <summary>
/// Gets the private part number of the product this file is associated with.
/// </summary>
public int ProductPrivatePart
{
get { return _productPrivate; }
}
/// <summary>
/// Gets the version of the product this file is distributed with.
/// </summary>
public string ProductVersion
{
get { return _productVersion; }
}
/// <summary>
/// Gets the special build information for the file.
/// </summary>
public string SpecialBuild
{
get { return _specialBuild; }
}
/// <summary>
/// Returns a <see cref="FileVersionInfo" /> representing the version information associated with the specified file.
/// </summary>
public static FileVersionInfo GetVersionInfo(string fileName)
{
// Check for the existence of the file. File.Exists returns false if Read permission is denied.
if (!File.Exists(fileName))
{
throw new FileNotFoundException(fileName);
}
return new FileVersionInfo(fileName);
}
/// <summary>
/// Returns a partial list of properties in <see cref="FileVersionInfo" />
/// and their values.
/// </summary>
public override string ToString()
{
// An initial capacity of 512 was chosen because it is large enough to cover
// the size of the static strings with enough capacity left over to cover
// average length property values.
var sb = new StringBuilder(512);
sb.Append("File: ").AppendLine(FileName);
sb.Append("InternalName: ").AppendLine(InternalName);
sb.Append("OriginalFilename: ").AppendLine(OriginalFilename);
sb.Append("FileVersion: ").AppendLine(FileVersion);
sb.Append("FileDescription: ").AppendLine(FileDescription);
sb.Append("Product: ").AppendLine(ProductName);
sb.Append("ProductVersion: ").AppendLine(ProductVersion);
sb.Append("Debug: ").AppendLine(IsDebug.ToString());
sb.Append("Patched: ").AppendLine(IsPatched.ToString());
sb.Append("PreRelease: ").AppendLine(IsPreRelease.ToString());
sb.Append("PrivateBuild: ").AppendLine(IsPrivateBuild.ToString());
sb.Append("SpecialBuild: ").AppendLine(IsSpecialBuild.ToString());
sb.Append("Language: ").AppendLine(Language);
return sb.ToString();
}
}
}
| |
// 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 Internal.IL.Stubs;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
using Interlocked = System.Threading.Interlocked;
namespace Internal.IL
{
/// <summary>
/// Represents a delegate and provides access to compiler-generated methods on the delegate type.
/// </summary>
public class DelegateInfo
{
private readonly TypeDesc _delegateType;
private readonly DelegateFeature _supportedFeatures;
private MethodSignature _signature;
private MethodDesc _getThunkMethod;
private DelegateThunkCollection _thunks;
public static bool SupportsDynamicInvoke(TypeSystemContext context)
{
return DynamicInvokeMethodThunk.SupportsDynamicInvoke(context);
}
/// <summary>
/// Gets the synthetic methods that support this delegate type.
/// </summary>
public IEnumerable<MethodDesc> Methods
{
get
{
if (_getThunkMethod == null)
{
Interlocked.CompareExchange(ref _getThunkMethod, new DelegateGetThunkMethodOverride(this), null);
}
yield return _getThunkMethod;
DelegateThunkCollection thunks = Thunks;
for (DelegateThunkKind kind = 0; kind < DelegateThunkCollection.MaxThunkKind; kind++)
{
MethodDesc thunk = thunks[kind];
if (thunk != null)
yield return thunk;
}
}
}
/// <summary>
/// Gets the collection of delegate invocation thunks.
/// </summary>
public DelegateThunkCollection Thunks
{
get
{
if (_thunks == null)
{
Interlocked.CompareExchange(ref _thunks, new DelegateThunkCollection(this), null);
}
return _thunks;
}
}
/// <summary>
/// Gets the signature of the delegate type.
/// </summary>
public MethodSignature Signature
{
get
{
if (_signature == null)
{
_signature = _delegateType.GetKnownMethod("Invoke", null).Signature;
}
return _signature;
}
}
public DelegateFeature SupportedFeatures
{
get
{
return _supportedFeatures;
}
}
/// <summary>
/// Gets the type of the delegate.
/// </summary>
public TypeDesc Type
{
get
{
return _delegateType;
}
}
public DelegateInfo(TypeDesc delegateType, DelegateFeature features)
{
Debug.Assert(delegateType.IsDelegate);
Debug.Assert(delegateType.IsTypeDefinition);
_delegateType = delegateType;
_supportedFeatures = features;
}
}
/// <summary>
/// Represents a collection of delegate invocation thunks.
/// </summary>
public class DelegateThunkCollection
{
public const DelegateThunkKind MaxThunkKind = DelegateThunkKind.ObjectArrayThunk + 1;
private MethodDesc _openStaticThunk;
private MethodDesc _multicastThunk;
private MethodDesc _closedStaticThunk;
private MethodDesc _closedInstanceOverGeneric;
private MethodDesc _reversePInvokeThunk;
private MethodDesc _invokeObjectArrayThunk;
private MethodDesc _openInstanceThunk;
internal DelegateThunkCollection(DelegateInfo owningDelegate)
{
_openStaticThunk = new DelegateInvokeOpenStaticThunk(owningDelegate);
_multicastThunk = new DelegateInvokeMulticastThunk(owningDelegate);
_closedStaticThunk = new DelegateInvokeClosedStaticThunk(owningDelegate);
_closedInstanceOverGeneric = new DelegateInvokeInstanceClosedOverGenericMethodThunk(owningDelegate);
// Methods that have a byref-like type in the signature cannot be invoked with the object array thunk.
// We would need to box the parameter and these can't be boxed.
// Neither can be methods that have pointers in the signature.
MethodSignature delegateSignature = owningDelegate.Signature;
bool generateObjectArrayThunk = true;
for (int i = 0; i < delegateSignature.Length; i++)
{
TypeDesc paramType = delegateSignature[i];
if (paramType.IsByRef)
paramType = ((ByRefType)paramType).ParameterType;
if (!paramType.IsSignatureVariable && paramType.IsByRefLike)
{
generateObjectArrayThunk = false;
break;
}
if (paramType.IsPointer || paramType.IsFunctionPointer)
{
generateObjectArrayThunk = false;
break;
}
}
TypeDesc normalizedReturnType = delegateSignature.ReturnType;
if (normalizedReturnType.IsByRef)
normalizedReturnType = ((ByRefType)normalizedReturnType).ParameterType;
if (!normalizedReturnType.IsSignatureVariable && normalizedReturnType.IsByRefLike)
generateObjectArrayThunk = false;
if (normalizedReturnType.IsPointer || normalizedReturnType.IsFunctionPointer)
generateObjectArrayThunk = false;
if ((owningDelegate.SupportedFeatures & DelegateFeature.ObjectArrayThunk) != 0 && generateObjectArrayThunk)
_invokeObjectArrayThunk = new DelegateInvokeObjectArrayThunk(owningDelegate);
//
// Check whether we have a reverse p/invoke thunk
//
if (!owningDelegate.Type.HasInstantiation && IsNativeCallingConventionCompatible(delegateSignature))
_reversePInvokeThunk = new DelegateReversePInvokeThunk(owningDelegate);
//
// Check whether we have an open instance thunk
//
if (delegateSignature.Length > 0)
{
TypeDesc firstParam = delegateSignature[0];
bool generateOpenInstanceMethod;
switch (firstParam.Category)
{
case TypeFlags.Pointer:
case TypeFlags.FunctionPointer:
generateOpenInstanceMethod = false;
break;
case TypeFlags.ByRef:
firstParam = ((ByRefType)firstParam).ParameterType;
generateOpenInstanceMethod = firstParam.IsSignatureVariable || firstParam.IsValueType;
break;
case TypeFlags.Array:
case TypeFlags.SzArray:
case TypeFlags.SignatureTypeVariable:
generateOpenInstanceMethod = true;
break;
default:
Debug.Assert(firstParam.IsDefType);
generateOpenInstanceMethod = !firstParam.IsValueType;
break;
}
if (generateOpenInstanceMethod)
{
_openInstanceThunk = new DelegateInvokeOpenInstanceThunk(owningDelegate);
}
}
}
#region Temporary interop logic
// TODO: interop should provide a way to query this
private static bool IsNativeCallingConventionCompatible(MethodSignature delegateSignature)
{
if (!IsNativeCallingConventionCompatible(delegateSignature.ReturnType))
return false;
else
{
for (int i = 0; i < delegateSignature.Length; i++)
{
if (!IsNativeCallingConventionCompatible(delegateSignature[i]))
{
return false;
}
}
}
return true;
}
private static bool IsNativeCallingConventionCompatible(TypeDesc type)
{
if (type.IsPointer)
return true;
if (type.IsByRef)
return IsNativeCallingConventionCompatible(((ParameterizedType)type).ParameterType);
if (!type.IsValueType)
return false;
if (type.IsPrimitive)
{
if (type.IsWellKnownType(WellKnownType.Boolean))
return false;
return true;
}
foreach (FieldDesc field in type.GetFields())
{
if (!field.IsStatic && !IsNativeCallingConventionCompatible(field.FieldType))
return false;
}
return true;
}
#endregion
public MethodDesc this[DelegateThunkKind kind]
{
get
{
switch (kind)
{
case DelegateThunkKind.OpenStaticThunk:
return _openStaticThunk;
case DelegateThunkKind.MulticastThunk:
return _multicastThunk;
case DelegateThunkKind.ClosedStaticThunk:
return _closedStaticThunk;
case DelegateThunkKind.ClosedInstanceThunkOverGenericMethod:
return _closedInstanceOverGeneric;
case DelegateThunkKind.ReversePinvokeThunk:
return _reversePInvokeThunk;
case DelegateThunkKind.ObjectArrayThunk:
return _invokeObjectArrayThunk;
case DelegateThunkKind.OpenInstanceThunk:
return _openInstanceThunk;
default:
return null;
}
}
}
}
// TODO: Unify with the consts used in Delegate.cs within the class library.
public enum DelegateThunkKind
{
MulticastThunk = 0,
ClosedStaticThunk = 1,
OpenStaticThunk = 2,
ClosedInstanceThunkOverGenericMethod = 3, // This may not exist
DelegateInvokeThunk = 4,
OpenInstanceThunk = 5, // This may not exist
ReversePinvokeThunk = 6, // This may not exist
ObjectArrayThunk = 7, // This may not exist
}
[Flags]
public enum DelegateFeature
{
DynamicInvoke = 0x1,
ObjectArrayThunk = 0x2,
}
}
| |
using AllReady.Areas.Admin.Features.Itineraries;
using AllReady.Models;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AllReady.Services.Mapping.Routing;
using Shouldly;
using Xunit;
using Microsoft.Extensions.Caching.Memory;
using AllReady.Caching;
namespace AllReady.UnitTest.Areas.Admin.Features.Itineraries
{
public class OptimizeRouteCommandHandlerShould : InMemoryContextTest
{
private const string EncodedFullAddress = "1%20Some%20Road,%20A%20town,%20A%20state,%20postalcode,%20United%20Kingdom";
private static readonly Guid Request1Id = new Guid("de4f4639-86ea-419f-96c8-509defa4d9a3");
private static readonly Guid Request2Id = new Guid("602b3f58-c8e0-4f59-82b0-f940c1aa1caa");
private static readonly Guid Request3Id = new Guid("602b3f58-c8e0-4f59-82b0-f940c1aa1e4a");
private static readonly Guid Request4Id = new Guid("602b3f58-c8e0-4f59-82b0-f940c1aa1111");
protected override void LoadTestData()
{
var location = new Location
{
Address1 = "1 Some Road",
City = "A town",
State = "A state",
PostalCode = "postalcode",
Country = "United Kingdom"
};
var itinerary1 = new Itinerary
{
Id = 1,
Name = "Test Itinerary 1",
StartLocation = location,
EndLocation = location
};
var itinerary2 = new Itinerary
{
Id = 2,
Name = "Test Itinerary 2"
};
var itinerary3 = new Itinerary
{
Id = 3,
Name = "Test Itinerary 3",
StartLocation = location,
UseStartAddressAsEndAddress = false
};
var request1 = new Request
{
RequestId = Request1Id,
Name = "Request 1",
Latitude = 50.8225,
Longitude = -0.1372
};
var request2 = new Request
{
RequestId = Request2Id,
Name = "Request 2",
Latitude = 10.0000,
Longitude = -5.0000
};
var request3 = new Request
{
RequestId = Request3Id,
Name = "Request 3",
Latitude = 10.0000,
Longitude = -5.0000
};
var request4 = new Request
{
RequestId = Request4Id,
Name = "Request 4",
Latitude = 10.0000,
Longitude = -5.0000
};
var itineraryRequest1 = new ItineraryRequest
{
Request = request1,
Itinerary = itinerary1,
OrderIndex = 1
};
var itineraryRequest2 = new ItineraryRequest
{
Request = request2,
Itinerary = itinerary2
};
var itineraryRequest3 = new ItineraryRequest
{
Request = request3,
Itinerary = itinerary3
};
var itineraryRequest4 = new ItineraryRequest
{
Request = request4,
Itinerary = itinerary1,
OrderIndex = 2
};
Context.Locations.Add(location);
Context.Itineraries.Add(itinerary1);
Context.Itineraries.Add(itinerary2);
Context.Itineraries.Add(itinerary3);
Context.Requests.Add(request1);
Context.Requests.Add(request2);
Context.Requests.Add(request3);
Context.Requests.Add(request4);
Context.SaveChanges();
Context.Add(itineraryRequest1);
Context.Add(itineraryRequest2);
Context.Add(itineraryRequest3);
Context.Add(itineraryRequest4);
Context.SaveChanges();
}
[Fact]
public async Task NotCallOptimizeRouteService_WhenItineraryNotFound()
{
var optimizeRouteService = new Mock<IOptimizeRouteService>();
optimizeRouteService.Setup(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>())).Verifiable();
var sut = new OptimizeRouteCommandHandler(Context, optimizeRouteService.Object, Mock.Of<IMemoryCache>());
await sut.Handle(new OptimizeRouteCommand { ItineraryId = 200 });
optimizeRouteService.Verify(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>()), Times.Never);
}
[Fact]
public async Task NotCallOptimizeRouteService_WhenItineraryHasNoStartAddress()
{
var optimizeRouteService = new Mock<IOptimizeRouteService>();
optimizeRouteService.Setup(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>())).Verifiable();
var sut = new OptimizeRouteCommandHandler(Context, optimizeRouteService.Object, Mock.Of<IMemoryCache>());
await sut.Handle(new OptimizeRouteCommand { ItineraryId = 2 });
optimizeRouteService.Verify(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>()), Times.Never);
}
[Fact]
public async Task NotCallOptimizeRouteService_WhenItineraryHasNoEndAddress_AndNotSetToUseStartAddressAsEndAddress()
{
var optimizeRouteService = new Mock<IOptimizeRouteService>();
optimizeRouteService.Setup(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>())).Verifiable();
var sut = new OptimizeRouteCommandHandler(Context, optimizeRouteService.Object, Mock.Of<IMemoryCache>());
await sut.Handle(new OptimizeRouteCommand { ItineraryId = 3 });
optimizeRouteService.Verify(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>()), Times.Never);
}
[Fact]
public async Task CallOptimizeRouteService_WhenStartAndEndAddressPresent_WithCorrectCriteria()
{
OptimizeRouteCriteria criteria = null;
var optimizeRouteService = new Mock<IOptimizeRouteService>();
optimizeRouteService.Setup(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>()))
.ReturnsAsync(new OptimizeRouteResult())
.Callback<OptimizeRouteCriteria>(x => criteria = x)
.Verifiable();
var sut = new OptimizeRouteCommandHandler(Context, optimizeRouteService.Object, Mock.Of<IMemoryCache>());
await sut.Handle(new OptimizeRouteCommand { ItineraryId = 1 });
optimizeRouteService.Verify(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>()), Times.Once);
criteria.StartAddress.ShouldBe(EncodedFullAddress);
criteria.EndAddress.ShouldBe(EncodedFullAddress);
criteria.Waypoints.Count.ShouldBe(2);
}
[Fact]
public async Task NotChangeRequestOrder_WhenOptimizeRouteResultIsNotSuccess()
{
var optimizeRouteService = new Mock<IOptimizeRouteService>();
optimizeRouteService.Setup(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>()))
.ReturnsAsync(OptimizeRouteResult.FailedOptimizeRouteResult("failure"));
var sut = new OptimizeRouteCommandHandler(Context, optimizeRouteService.Object, Mock.Of<IMemoryCache>());
await sut.Handle(new OptimizeRouteCommand { ItineraryId = 1 });
var requests = Context.ItineraryRequests.Where(x => x.ItineraryId == 1).OrderBy(x => x.OrderIndex).ToList();
requests[0].Request.Name.ShouldBe("Request 1");
requests[1].Request.Name.ShouldBe("Request 4");
}
[Fact]
public async Task NotChangeRequestOrder_WhenOptimizeRouteResultRequestIdCountDoesNotMatchWaypointCount()
{
var optimizeRouteService = new Mock<IOptimizeRouteService>();
optimizeRouteService.Setup(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>()))
.ReturnsAsync(new OptimizeRouteResult { Distance = 10, Duration = 10, RequestIds = new List<Guid> { Guid.NewGuid() } });
var sut = new OptimizeRouteCommandHandler(Context, optimizeRouteService.Object, Mock.Of<IMemoryCache>());
await sut.Handle(new OptimizeRouteCommand { ItineraryId = 1 });
var requests = Context.ItineraryRequests.Where(x => x.ItineraryId == 1).OrderBy(x => x.OrderIndex).ToList();
requests[0].Request.Name.ShouldBe("Request 1");
requests[1].Request.Name.ShouldBe("Request 4");
}
[Fact]
public async Task NotChangeRequestOrder_WhenOptimizeRouteResultDoesNotReturnMatchingRequestIds()
{
var optimizeRouteService = new Mock<IOptimizeRouteService>();
optimizeRouteService.Setup(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>()))
.ReturnsAsync(new OptimizeRouteResult { Distance = 10, Duration = 10, RequestIds = new List<Guid> { Request4Id, Guid.Empty } });
var sut = new OptimizeRouteCommandHandler(Context, optimizeRouteService.Object, Mock.Of<IMemoryCache>());
await sut.Handle(new OptimizeRouteCommand { ItineraryId = 1 });
var requests = Context.ItineraryRequests.Where(x => x.ItineraryId == 1).OrderBy(x => x.OrderIndex).ToList();
requests.First(x => x.RequestId == Request1Id).OrderIndex.ShouldBe(1);
requests.First(x => x.RequestId == Request4Id).OrderIndex.ShouldBe(2);
}
[Fact]
public async Task ChangeRequestOrder_WhenOptimizeRouteResultReturnsUpdatedWaypointsOrder()
{
var optimizeRouteService = new Mock<IOptimizeRouteService>();
optimizeRouteService.Setup(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>()))
.ReturnsAsync(new OptimizeRouteResult { Distance = 10, Duration = 10, RequestIds = new List<Guid> { Request4Id, Request1Id } });
var sut = new OptimizeRouteCommandHandler(Context, optimizeRouteService.Object, Mock.Of<IMemoryCache>());
await sut.Handle(new OptimizeRouteCommand { ItineraryId = 1 });
var requests = Context.ItineraryRequests.Where(x => x.ItineraryId == 1).OrderBy(x => x.OrderIndex).ToList();
requests[0].Request.Name.ShouldBe("Request 4");
requests[1].Request.Name.ShouldBe("Request 1");
}
[Fact]
public async Task SetsCorrectCacheEntry_WhenOptimizeRouteResultIsNotSuccess()
{
const string statusMsg = "failure";
var optimizeRouteService = new Mock<IOptimizeRouteService>();
optimizeRouteService.Setup(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>()))
.ReturnsAsync(OptimizeRouteResult.FailedOptimizeRouteResult(statusMsg));
var cache = new MemoryCache(new MemoryCacheOptions());
var sut = new OptimizeRouteCommandHandler(Context, optimizeRouteService.Object, cache);
await sut.Handle(new OptimizeRouteCommand { ItineraryId = 1, UserId = "123" });
var expectedCacheKey = CacheKeyBuilder.BuildOptimizeRouteCacheKey("123", 1);
OptimizeRouteResultStatus cachedStatus = null;
var keyExists = cache.TryGetValue(expectedCacheKey, out cachedStatus);
keyExists.ShouldBeTrue();
cachedStatus.IsSuccess.ShouldBeFalse();
cachedStatus.StatusMessage.ShouldBe(statusMsg);
}
[Fact]
public async Task SetsCorrectCacheEntry_WhenOptimizeRouteResultValidationFails()
{
var optimizeRouteService = new Mock<IOptimizeRouteService>();
optimizeRouteService.Setup(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>()))
.ReturnsAsync(new OptimizeRouteResult { Distance = 10, Duration = 10, RequestIds = new List<Guid> { Guid.NewGuid() } });
var cache = new MemoryCache(new MemoryCacheOptions());
var sut = new OptimizeRouteCommandHandler(Context, optimizeRouteService.Object, cache);
await sut.Handle(new OptimizeRouteCommand { ItineraryId = 1, UserId = "123" });
var expectedCacheKey = CacheKeyBuilder.BuildOptimizeRouteCacheKey("123", 1);
OptimizeRouteResultStatus cachedStatus = null;
var keyExists = cache.TryGetValue(expectedCacheKey, out cachedStatus);
keyExists.ShouldBeTrue();
cachedStatus.IsSuccess.ShouldBeFalse();
cachedStatus.StatusMessage.ShouldBe(OptimizeRouteStatusMessages.GeneralOptimizeFailure);
}
[Fact]
public async Task SetsCorrectCacheEntry_WhenOptimizeRouteResultIsSuccess_AndRequestOrderDoesNotChange()
{
var optimizeRouteService = new Mock<IOptimizeRouteService>();
optimizeRouteService.Setup(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>()))
.ReturnsAsync(new OptimizeRouteResult { Distance = 10, Duration = 10, RequestIds = new List<Guid> { Request1Id, Request4Id } });
var cache = new MemoryCache(new MemoryCacheOptions());
var sut = new OptimizeRouteCommandHandler(Context, optimizeRouteService.Object, cache);
await sut.Handle(new OptimizeRouteCommand { ItineraryId = 1, UserId = "123" });
var expectedCacheKey = CacheKeyBuilder.BuildOptimizeRouteCacheKey("123", 1);
OptimizeRouteResultStatus cachedStatus = null;
var keyExists = cache.TryGetValue(expectedCacheKey, out cachedStatus);
keyExists.ShouldBeTrue();
cachedStatus.IsSuccess.ShouldBeTrue();
cachedStatus.StatusMessage.ShouldBe(OptimizeRouteStatusMessages.AlreadyOptimized);
}
[Fact]
public async Task SetsCorrectCacheEntry_WhenOptimizeRouteResultIsSuccess_AndRequestOrderIsUpdated()
{
var optimizeRouteService = new Mock<IOptimizeRouteService>();
optimizeRouteService.Setup(x => x.OptimizeRoute(It.IsAny<OptimizeRouteCriteria>()))
.ReturnsAsync(new OptimizeRouteResult { Distance = 10, Duration = 10, RequestIds = new List<Guid> { Request4Id, Request1Id } });
var cache = new MemoryCache(new MemoryCacheOptions());
var sut = new OptimizeRouteCommandHandler(Context, optimizeRouteService.Object, cache);
await sut.Handle(new OptimizeRouteCommand { ItineraryId = 1, UserId = "123" });
var expectedCacheKey = CacheKeyBuilder.BuildOptimizeRouteCacheKey("123", 1);
OptimizeRouteResultStatus cachedStatus = null;
var keyExists = cache.TryGetValue(expectedCacheKey, out cachedStatus);
keyExists.ShouldBeTrue();
cachedStatus.IsSuccess.ShouldBeTrue();
cachedStatus.StatusMessage.ShouldBe(OptimizeRouteStatusMessages.OptimizeSucess);
}
}
}
| |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ThisToThat;
namespace ThisToThatTests
{
[TestClass]
public class ToInt16Tests
{
/*
SByte to Int16: Test omitted
There is a predefined implicit conversion from SByte to Int16
*/
/*
Byte to Int16: Test omitted
There is a predefined implicit conversion from Byte to Int16
*/
/// <summary>
/// Makes multiple UInt16 to Int16 or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt16 tests")]
public void TestUInt16ToInt16OrDefault()
{
// Test conversion of source type minimum value
UInt16 source = UInt16.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt16));
Int16? result = source.ToInt16OrDefault((short)86);
Assert.AreEqual((short)0, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type value 42 to target type
source = (ushort)42;
Assert.IsInstanceOfType(source, typeof(UInt16));
result = source.ToInt16OrDefault((short)86);
Assert.AreEqual((short)42, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type maximum value
source = UInt16.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt16));
result = source.ToInt16OrDefault((short)86);
// Here we would expect this conversion to fail (and return the default value of (short)86),
// since the source type's maximum value (65535) is greater than the target type's maximum value (32767).
Assert.AreEqual((short)86, result);
Assert.IsInstanceOfType(result, typeof(Int16));
}
/// <summary>
/// Makes multiple UInt16 to nullable Int16 conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt16 tests")]
public void TestUInt16ToInt16Nullable()
{
// Test conversion of source type minimum value
UInt16 source = UInt16.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt16));
Int16? result = source.ToInt16Nullable();
Assert.AreEqual((short)0, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type value 42 to target type
source = (ushort)42;
Assert.IsInstanceOfType(source, typeof(UInt16));
result = source.ToInt16Nullable();
Assert.AreEqual((short)42, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type maximum value
source = UInt16.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt16));
result = source.ToInt16Nullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's maximum value (65535) is greater than the target type's maximum value (32767).
Assert.IsNull(result);
}
/// <summary>
/// Makes multiple Int32 to Int16 or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt16 tests")]
public void TestInt32ToInt16OrDefault()
{
// Test conversion of source type minimum value
Int32 source = Int32.MinValue;
Assert.IsInstanceOfType(source, typeof(Int32));
Int16? result = source.ToInt16OrDefault((short)86);
// Here we would expect this conversion to fail (and return the default value of (short)86),
// since the source type's minimum value (-2147483648) is less than the target type's minimum value (-32768).
Assert.AreEqual((short)86, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type value 42 to target type
source = 42;
Assert.IsInstanceOfType(source, typeof(Int32));
result = source.ToInt16OrDefault((short)86);
Assert.AreEqual((short)42, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type maximum value
source = Int32.MaxValue;
Assert.IsInstanceOfType(source, typeof(Int32));
result = source.ToInt16OrDefault((short)86);
// Here we would expect this conversion to fail (and return the default value of (short)86),
// since the source type's maximum value (2147483647) is greater than the target type's maximum value (32767).
Assert.AreEqual((short)86, result);
Assert.IsInstanceOfType(result, typeof(Int16));
}
/// <summary>
/// Makes multiple Int32 to nullable Int16 conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt16 tests")]
public void TestInt32ToInt16Nullable()
{
// Test conversion of source type minimum value
Int32 source = Int32.MinValue;
Assert.IsInstanceOfType(source, typeof(Int32));
Int16? result = source.ToInt16Nullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's minimum value (-2147483648) is less than the target type's minimum value (-32768).
Assert.IsNull(result);
// Test conversion of source type value 42 to target type
source = 42;
Assert.IsInstanceOfType(source, typeof(Int32));
result = source.ToInt16Nullable();
Assert.AreEqual((short)42, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type maximum value
source = Int32.MaxValue;
Assert.IsInstanceOfType(source, typeof(Int32));
result = source.ToInt16Nullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's maximum value (2147483647) is greater than the target type's maximum value (32767).
Assert.IsNull(result);
}
/// <summary>
/// Makes multiple UInt32 to Int16 or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt16 tests")]
public void TestUInt32ToInt16OrDefault()
{
// Test conversion of source type minimum value
UInt32 source = UInt32.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt32));
Int16? result = source.ToInt16OrDefault((short)86);
Assert.AreEqual((short)0, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type value 42 to target type
source = 42u;
Assert.IsInstanceOfType(source, typeof(UInt32));
result = source.ToInt16OrDefault((short)86);
Assert.AreEqual((short)42, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type maximum value
source = UInt32.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt32));
result = source.ToInt16OrDefault((short)86);
// Here we would expect this conversion to fail (and return the default value of (short)86),
// since the source type's maximum value (4294967295) is greater than the target type's maximum value (32767).
Assert.AreEqual((short)86, result);
Assert.IsInstanceOfType(result, typeof(Int16));
}
/// <summary>
/// Makes multiple UInt32 to nullable Int16 conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt16 tests")]
public void TestUInt32ToInt16Nullable()
{
// Test conversion of source type minimum value
UInt32 source = UInt32.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt32));
Int16? result = source.ToInt16Nullable();
Assert.AreEqual((short)0, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type value 42 to target type
source = 42u;
Assert.IsInstanceOfType(source, typeof(UInt32));
result = source.ToInt16Nullable();
Assert.AreEqual((short)42, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type maximum value
source = UInt32.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt32));
result = source.ToInt16Nullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's maximum value (4294967295) is greater than the target type's maximum value (32767).
Assert.IsNull(result);
}
/// <summary>
/// Makes multiple Int64 to Int16 or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt16 tests")]
public void TestInt64ToInt16OrDefault()
{
// Test conversion of source type minimum value
Int64 source = Int64.MinValue;
Assert.IsInstanceOfType(source, typeof(Int64));
Int16? result = source.ToInt16OrDefault((short)86);
// Here we would expect this conversion to fail (and return the default value of (short)86),
// since the source type's minimum value (-9223372036854775808) is less than the target type's minimum value (-32768).
Assert.AreEqual((short)86, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type value 42 to target type
source = 42L;
Assert.IsInstanceOfType(source, typeof(Int64));
result = source.ToInt16OrDefault((short)86);
Assert.AreEqual((short)42, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type maximum value
source = Int64.MaxValue;
Assert.IsInstanceOfType(source, typeof(Int64));
result = source.ToInt16OrDefault((short)86);
// Here we would expect this conversion to fail (and return the default value of (short)86),
// since the source type's maximum value (9223372036854775807) is greater than the target type's maximum value (32767).
Assert.AreEqual((short)86, result);
Assert.IsInstanceOfType(result, typeof(Int16));
}
/// <summary>
/// Makes multiple Int64 to nullable Int16 conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt16 tests")]
public void TestInt64ToInt16Nullable()
{
// Test conversion of source type minimum value
Int64 source = Int64.MinValue;
Assert.IsInstanceOfType(source, typeof(Int64));
Int16? result = source.ToInt16Nullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's minimum value (-9223372036854775808) is less than the target type's minimum value (-32768).
Assert.IsNull(result);
// Test conversion of source type value 42 to target type
source = 42L;
Assert.IsInstanceOfType(source, typeof(Int64));
result = source.ToInt16Nullable();
Assert.AreEqual((short)42, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type maximum value
source = Int64.MaxValue;
Assert.IsInstanceOfType(source, typeof(Int64));
result = source.ToInt16Nullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's maximum value (9223372036854775807) is greater than the target type's maximum value (32767).
Assert.IsNull(result);
}
/// <summary>
/// Makes multiple UInt64 to Int16 or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt16 tests")]
public void TestUInt64ToInt16OrDefault()
{
// Test conversion of source type minimum value
UInt64 source = UInt64.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt64));
Int16? result = source.ToInt16OrDefault((short)86);
Assert.AreEqual((short)0, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type value 42 to target type
source = 42UL;
Assert.IsInstanceOfType(source, typeof(UInt64));
result = source.ToInt16OrDefault((short)86);
Assert.AreEqual((short)42, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type maximum value
source = UInt64.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt64));
result = source.ToInt16OrDefault((short)86);
// Here we would expect this conversion to fail (and return the default value of (short)86),
// since the source type's maximum value (18446744073709551615) is greater than the target type's maximum value (32767).
Assert.AreEqual((short)86, result);
Assert.IsInstanceOfType(result, typeof(Int16));
}
/// <summary>
/// Makes multiple UInt64 to nullable Int16 conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt16 tests")]
public void TestUInt64ToInt16Nullable()
{
// Test conversion of source type minimum value
UInt64 source = UInt64.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt64));
Int16? result = source.ToInt16Nullable();
Assert.AreEqual((short)0, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type value 42 to target type
source = 42UL;
Assert.IsInstanceOfType(source, typeof(UInt64));
result = source.ToInt16Nullable();
Assert.AreEqual((short)42, result);
Assert.IsInstanceOfType(result, typeof(Int16));
// Test conversion of source type maximum value
source = UInt64.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt64));
result = source.ToInt16Nullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's maximum value (18446744073709551615) is greater than the target type's maximum value (32767).
Assert.IsNull(result);
}
/*
Single to Int16: Method omitted.
Int16 is an integral type. Single is non-integral (can contain fractions).
Conversions involving possible rounding or truncation are not currently provided by this library.
*/
/*
Double to Int16: Method omitted.
Int16 is an integral type. Double is non-integral (can contain fractions).
Conversions involving possible rounding or truncation are not currently provided by this library.
*/
/*
Decimal to Int16: Method omitted.
Int16 is an integral type. Decimal is non-integral (can contain fractions).
Conversions involving possible rounding or truncation are not currently provided by this library.
*/
/// <summary>
/// Makes multiple String to Int16 or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt16 tests")]
public void TestStringToInt16OrDefault()
{
// Test conversion of target type minimum value
Int16 resultMin = "-32768".ToInt16OrDefault();
Assert.AreEqual((short)-32768, resultMin);
// Test conversion of fixed value (42)
Int16 result42 = "42".ToInt16OrDefault();
Assert.AreEqual((short)42, result42);
// Test conversion of target type maximum value
Int16 resultMax = "32767".ToInt16OrDefault();
Assert.AreEqual((short)32767, resultMax);
// Test conversion of "foo"
Int16 resultFoo = "foo".ToInt16OrDefault((short)86);
Assert.AreEqual((short)86, resultFoo);
}
/// <summary>
/// Makes multiple String to Int16Nullable conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt16 tests")]
public void TestStringToInt16Nullable()
{
// Test conversion of target type minimum value
Int16? resultMin = "-32768".ToInt16Nullable();
Assert.AreEqual((short)-32768, resultMin);
// Test conversion of fixed value (42)
Int16? result42 = "42".ToInt16Nullable();
Assert.AreEqual((short)42, result42);
// Test conversion of target type maximum value
Int16? resultMax = "32767".ToInt16Nullable();
Assert.AreEqual((short)32767, resultMax);
// Test conversion of "foo"
Int16? resultFoo = "foo".ToInt16Nullable();
Assert.IsNull(resultFoo);
}
}
}
| |
// 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.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using FileStaging;
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// An Azure Batch task. A task is a piece of work that is associated with a job and runs on a compute node.
/// </summary>
/// <remarks>
/// Batch will retry tasks when a recovery operation is triggered on a compute node. Examples of recovery operations
/// include (but are not limited to) when an unhealthy compute node is rebooted or a compute node disappeared due to
/// host failure. Retries due to recovery operations are independent of and are not counted against the <see cref="TaskConstraints.MaxTaskRetryCount"
/// />. Even if the <see cref="TaskConstraints.MaxTaskRetryCount" /> is 0, an internal retry due to a recovery operation
/// may occur. Because of this, all tasks should be idempotent. This means tasks need to tolerate being interrupted and
/// restarted without causing any corruption or duplicate data. The best practice for long running tasks is to use some
/// form of checkpointing. The maximum lifetime of a task from addition to completion is 180 days. If a task has not
/// completed within 180 days of being added it will be terminated by the Batch service and left in whatever state it
/// was in at that time.
/// </remarks>
public partial class CloudTask : ITransportObjectProvider<Models.TaskAddParameter>, IInheritedBehaviors, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<AffinityInformation> AffinityInformationProperty;
public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty;
public readonly PropertyAccessor<AuthenticationTokenSettings> AuthenticationTokenSettingsProperty;
public readonly PropertyAccessor<string> CommandLineProperty;
public readonly PropertyAccessor<ComputeNodeInformation> ComputeNodeInformationProperty;
public readonly PropertyAccessor<TaskConstraints> ConstraintsProperty;
public readonly PropertyAccessor<TaskContainerSettings> ContainerSettingsProperty;
public readonly PropertyAccessor<DateTime?> CreationTimeProperty;
public readonly PropertyAccessor<TaskDependencies> DependsOnProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<IList<EnvironmentSetting>> EnvironmentSettingsProperty;
public readonly PropertyAccessor<string> ETagProperty;
public readonly PropertyAccessor<TaskExecutionInformation> ExecutionInformationProperty;
public readonly PropertyAccessor<ExitConditions> ExitConditionsProperty;
public readonly PropertyAccessor<IList<IFileStagingProvider>> FilesToStageProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<DateTime?> LastModifiedProperty;
public readonly PropertyAccessor<MultiInstanceSettings> MultiInstanceSettingsProperty;
public readonly PropertyAccessor<IList<OutputFile>> OutputFilesProperty;
public readonly PropertyAccessor<Common.TaskState?> PreviousStateProperty;
public readonly PropertyAccessor<DateTime?> PreviousStateTransitionTimeProperty;
public readonly PropertyAccessor<int?> RequiredSlotsProperty;
public readonly PropertyAccessor<IList<ResourceFile>> ResourceFilesProperty;
public readonly PropertyAccessor<Common.TaskState?> StateProperty;
public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty;
public readonly PropertyAccessor<TaskStatistics> StatisticsProperty;
public readonly PropertyAccessor<string> UrlProperty;
public readonly PropertyAccessor<UserIdentity> UserIdentityProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.AffinityInformationProperty = this.CreatePropertyAccessor<AffinityInformation>(nameof(AffinityInformation), BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write);
this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor<AuthenticationTokenSettings>(nameof(AuthenticationTokenSettings), BindingAccess.Read | BindingAccess.Write);
this.CommandLineProperty = this.CreatePropertyAccessor<string>(nameof(CommandLine), BindingAccess.Read | BindingAccess.Write);
this.ComputeNodeInformationProperty = this.CreatePropertyAccessor<ComputeNodeInformation>(nameof(ComputeNodeInformation), BindingAccess.None);
this.ConstraintsProperty = this.CreatePropertyAccessor<TaskConstraints>(nameof(Constraints), BindingAccess.Read | BindingAccess.Write);
this.ContainerSettingsProperty = this.CreatePropertyAccessor<TaskContainerSettings>(nameof(ContainerSettings), BindingAccess.Read | BindingAccess.Write);
this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(CreationTime), BindingAccess.None);
this.DependsOnProperty = this.CreatePropertyAccessor<TaskDependencies>(nameof(DependsOn), BindingAccess.Read | BindingAccess.Write);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>(nameof(EnvironmentSettings), BindingAccess.Read | BindingAccess.Write);
this.ETagProperty = this.CreatePropertyAccessor<string>(nameof(ETag), BindingAccess.None);
this.ExecutionInformationProperty = this.CreatePropertyAccessor<TaskExecutionInformation>(nameof(ExecutionInformation), BindingAccess.None);
this.ExitConditionsProperty = this.CreatePropertyAccessor<ExitConditions>(nameof(ExitConditions), BindingAccess.Read | BindingAccess.Write);
this.FilesToStageProperty = this.CreatePropertyAccessor<IList<IFileStagingProvider>>(nameof(FilesToStage), BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write);
this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>(nameof(LastModified), BindingAccess.None);
this.MultiInstanceSettingsProperty = this.CreatePropertyAccessor<MultiInstanceSettings>(nameof(MultiInstanceSettings), BindingAccess.Read | BindingAccess.Write);
this.OutputFilesProperty = this.CreatePropertyAccessor<IList<OutputFile>>(nameof(OutputFiles), BindingAccess.Read | BindingAccess.Write);
this.PreviousStateProperty = this.CreatePropertyAccessor<Common.TaskState?>(nameof(PreviousState), BindingAccess.None);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(PreviousStateTransitionTime), BindingAccess.None);
this.RequiredSlotsProperty = this.CreatePropertyAccessor<int?>(nameof(RequiredSlots), BindingAccess.Read | BindingAccess.Write);
this.ResourceFilesProperty = this.CreatePropertyAccessor<IList<ResourceFile>>(nameof(ResourceFiles), BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor<Common.TaskState?>(nameof(State), BindingAccess.None);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(StateTransitionTime), BindingAccess.None);
this.StatisticsProperty = this.CreatePropertyAccessor<TaskStatistics>(nameof(Statistics), BindingAccess.None);
this.UrlProperty = this.CreatePropertyAccessor<string>(nameof(Url), BindingAccess.None);
this.UserIdentityProperty = this.CreatePropertyAccessor<UserIdentity>(nameof(UserIdentity), BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.CloudTask protocolObject) : base(BindingState.Bound)
{
this.AffinityInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AffinityInfo, o => new AffinityInformation(o).Freeze()),
nameof(AffinityInformation),
BindingAccess.Read);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor(
ApplicationPackageReference.ConvertFromProtocolCollectionAndFreeze(protocolObject.ApplicationPackageReferences),
nameof(ApplicationPackageReferences),
BindingAccess.Read);
this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AuthenticationTokenSettings, o => new AuthenticationTokenSettings(o).Freeze()),
nameof(AuthenticationTokenSettings),
BindingAccess.Read);
this.CommandLineProperty = this.CreatePropertyAccessor(
protocolObject.CommandLine,
nameof(CommandLine),
BindingAccess.Read);
this.ComputeNodeInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NodeInfo, o => new ComputeNodeInformation(o).Freeze()),
nameof(ComputeNodeInformation),
BindingAccess.Read);
this.ConstraintsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new TaskConstraints(o)),
nameof(Constraints),
BindingAccess.Read | BindingAccess.Write);
this.ContainerSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ContainerSettings, o => new TaskContainerSettings(o).Freeze()),
nameof(ContainerSettings),
BindingAccess.Read);
this.CreationTimeProperty = this.CreatePropertyAccessor(
protocolObject.CreationTime,
nameof(CreationTime),
BindingAccess.Read);
this.DependsOnProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.DependsOn, o => new TaskDependencies(o).Freeze()),
nameof(DependsOn),
BindingAccess.Read);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
nameof(DisplayName),
BindingAccess.Read);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor(
EnvironmentSetting.ConvertFromProtocolCollectionAndFreeze(protocolObject.EnvironmentSettings),
nameof(EnvironmentSettings),
BindingAccess.Read);
this.ETagProperty = this.CreatePropertyAccessor(
protocolObject.ETag,
nameof(ETag),
BindingAccess.Read);
this.ExecutionInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExecutionInfo, o => new TaskExecutionInformation(o).Freeze()),
nameof(ExecutionInformation),
BindingAccess.Read);
this.ExitConditionsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExitConditions, o => new ExitConditions(o).Freeze()),
nameof(ExitConditions),
BindingAccess.Read);
this.FilesToStageProperty = this.CreatePropertyAccessor<IList<IFileStagingProvider>>(
nameof(FilesToStage),
BindingAccess.None);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
nameof(Id),
BindingAccess.Read);
this.LastModifiedProperty = this.CreatePropertyAccessor(
protocolObject.LastModified,
nameof(LastModified),
BindingAccess.Read);
this.MultiInstanceSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.MultiInstanceSettings, o => new MultiInstanceSettings(o).Freeze()),
nameof(MultiInstanceSettings),
BindingAccess.Read);
this.OutputFilesProperty = this.CreatePropertyAccessor(
OutputFile.ConvertFromProtocolCollectionAndFreeze(protocolObject.OutputFiles),
nameof(OutputFiles),
BindingAccess.Read);
this.PreviousStateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.TaskState, Common.TaskState>(protocolObject.PreviousState),
nameof(PreviousState),
BindingAccess.Read);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.PreviousStateTransitionTime,
nameof(PreviousStateTransitionTime),
BindingAccess.Read);
this.RequiredSlotsProperty = this.CreatePropertyAccessor(
protocolObject.RequiredSlots,
nameof(RequiredSlots),
BindingAccess.Read);
this.ResourceFilesProperty = this.CreatePropertyAccessor(
ResourceFile.ConvertFromProtocolCollectionAndFreeze(protocolObject.ResourceFiles),
nameof(ResourceFiles),
BindingAccess.Read);
this.StateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.TaskState, Common.TaskState>(protocolObject.State),
nameof(State),
BindingAccess.Read);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.StateTransitionTime,
nameof(StateTransitionTime),
BindingAccess.Read);
this.StatisticsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new TaskStatistics(o).Freeze()),
nameof(Statistics),
BindingAccess.Read);
this.UrlProperty = this.CreatePropertyAccessor(
protocolObject.Url,
nameof(Url),
BindingAccess.Read);
this.UserIdentityProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.UserIdentity, o => new UserIdentity(o).Freeze()),
nameof(UserIdentity),
BindingAccess.Read);
}
}
private PropertyContainer propertyContainer;
private readonly BatchClient parentBatchClient;
private readonly string parentJobId;
internal string ParentJobId
{
get
{
return this.parentJobId;
}
}
#region Constructors
/// <summary>
/// Default constructor to support mocking the <see cref="CloudTask"/> class.
/// </summary>
protected CloudTask()
{
this.propertyContainer = new PropertyContainer();
}
internal CloudTask(
BatchClient parentBatchClient,
string parentJobId,
Models.CloudTask protocolObject,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.parentJobId = parentJobId;
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region IInheritedBehaviors
/// <summary>
/// Gets or sets a list of behaviors that modify or customize requests to the Batch service
/// made via this <see cref="CloudTask"/>.
/// </summary>
/// <remarks>
/// <para>These behaviors are inherited by child objects.</para>
/// <para>Modifications are applied in the order of the collection. The last write wins.</para>
/// </remarks>
public IList<BatchClientBehavior> CustomBehaviors { get; set; }
#endregion IInheritedBehaviors
#region CloudTask
/// <summary>
/// Gets or sets a locality hint that can be used by the Batch service to select a node on which to start the task.
/// </summary>
public AffinityInformation AffinityInformation
{
get { return this.propertyContainer.AffinityInformationProperty.Value; }
set { this.propertyContainer.AffinityInformationProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of application packages that the Batch service will deploy to the compute node before running
/// the command line.
/// </summary>
public IList<ApplicationPackageReference> ApplicationPackageReferences
{
get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; }
set
{
this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the settings for an authentication token that the task can use to perform Batch service operations.
/// </summary>
/// <remarks>
/// If this property is set, the Batch service provides the task with an authentication token which can be used to
/// authenticate Batch service operations without requiring an account access key. The token is provided via the
/// AZ_BATCH_AUTHENTICATION_TOKEN environment variable. The operations that the task can carry out using the token
/// depend on the settings. For example, a task can request job permissions in order to add other tasks to the job,
/// or check the status of the job or of other tasks.
/// </remarks>
public AuthenticationTokenSettings AuthenticationTokenSettings
{
get { return this.propertyContainer.AuthenticationTokenSettingsProperty.Value; }
set { this.propertyContainer.AuthenticationTokenSettingsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the command line of the task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment
/// variable expansion. If you want to take advantage of such features, you should invoke the shell in the command
/// line, for example using \"cmd /c MyCommand\" in Windows or \"/bin/sh -c MyCommand\" in Linux. If the command
/// line refers to file paths, it should use a relative path (relative to the task working directory), or use the
/// Batch provided environment variables (https://docs.microsoft.com/en-us/azure/batch/batch-compute-node-environment-variables).
/// </remarks>
public string CommandLine
{
get { return this.propertyContainer.CommandLineProperty.Value; }
set { this.propertyContainer.CommandLineProperty.Value = value; }
}
/// <summary>
/// Gets information about the compute node on which the task ran.
/// </summary>
public ComputeNodeInformation ComputeNodeInformation
{
get { return this.propertyContainer.ComputeNodeInformationProperty.Value; }
}
/// <summary>
/// Gets or sets the execution constraints that apply to this task.
/// </summary>
public TaskConstraints Constraints
{
get { return this.propertyContainer.ConstraintsProperty.Value; }
set { this.propertyContainer.ConstraintsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the settings for the container under which the task runs.
/// </summary>
/// <remarks>
/// If the pool that will run this task has <see cref="VirtualMachineConfiguration.ContainerConfiguration"/> set,
/// this must be set as well. If the pool that will run this task doesn't have <see cref="VirtualMachineConfiguration.ContainerConfiguration"/>
/// set, this must not be set. When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR
/// (the root of Azure Batch directories on the node) are mapped into the container, all task environment variables
/// are mapped into the container, and the task command line is executed in the container. Files produced in the
/// container outside of AZ_BATCH_NODE_ROOT_DIR might not be reflected to the host disk, meaning that Batch file
/// APIs will not be able to access them.
/// </remarks>
public TaskContainerSettings ContainerSettings
{
get { return this.propertyContainer.ContainerSettingsProperty.Value; }
set { this.propertyContainer.ContainerSettingsProperty.Value = value; }
}
/// <summary>
/// Gets the creation time of the task.
/// </summary>
public DateTime? CreationTime
{
get { return this.propertyContainer.CreationTimeProperty.Value; }
}
/// <summary>
/// Gets or sets any other tasks that this <see cref="CloudTask"/> depends on. The task will not be scheduled until
/// all depended-on tasks have completed successfully.
/// </summary>
/// <remarks>
/// The job must set <see cref="CloudJob.UsesTaskDependencies"/> to true in order to use task dependencies. If UsesTaskDependencies
/// is false (the default), adding a task with dependencies will fail with an error.
/// </remarks>
public TaskDependencies DependsOn
{
get { return this.propertyContainer.DependsOnProperty.Value; }
set { this.propertyContainer.DependsOnProperty.Value = value; }
}
/// <summary>
/// Gets or sets the display name of the task.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of environment variable settings for the task.
/// </summary>
public IList<EnvironmentSetting> EnvironmentSettings
{
get { return this.propertyContainer.EnvironmentSettingsProperty.Value; }
set
{
this.propertyContainer.EnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets the ETag for the task.
/// </summary>
public string ETag
{
get { return this.propertyContainer.ETagProperty.Value; }
}
/// <summary>
/// Gets the execution information for the task.
/// </summary>
public TaskExecutionInformation ExecutionInformation
{
get { return this.propertyContainer.ExecutionInformationProperty.Value; }
}
/// <summary>
/// Gets or sets how the Batch service should respond when the task completes.
/// </summary>
public ExitConditions ExitConditions
{
get { return this.propertyContainer.ExitConditionsProperty.Value; }
set { this.propertyContainer.ExitConditionsProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of files to be staged for the task.
/// </summary>
public IList<IFileStagingProvider> FilesToStage
{
get { return this.propertyContainer.FilesToStageProperty.Value; }
set
{
this.propertyContainer.FilesToStageProperty.Value = ConcurrentChangeTrackedList<IFileStagingProvider>.TransformEnumerableToConcurrentList(value);
}
}
/// <summary>
/// Gets or sets the id of the task.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets the last modified time of the task.
/// </summary>
public DateTime? LastModified
{
get { return this.propertyContainer.LastModifiedProperty.Value; }
}
/// <summary>
/// Gets or sets information about how to run the multi-instance task.
/// </summary>
public MultiInstanceSettings MultiInstanceSettings
{
get { return this.propertyContainer.MultiInstanceSettingsProperty.Value; }
set { this.propertyContainer.MultiInstanceSettingsProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of files that the Batch service will upload from the compute node after running the command
/// line.
/// </summary>
public IList<OutputFile> OutputFiles
{
get { return this.propertyContainer.OutputFilesProperty.Value; }
set
{
this.propertyContainer.OutputFilesProperty.Value = ConcurrentChangeTrackedModifiableList<OutputFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets the previous state of the task.
/// </summary>
/// <remarks>
/// If the task is in its initial <see cref="Common.TaskState.Active"/> state, the PreviousState property is not
/// defined.
/// </remarks>
public Common.TaskState? PreviousState
{
get { return this.propertyContainer.PreviousStateProperty.Value; }
}
/// <summary>
/// Gets the time at which the task entered its previous state.
/// </summary>
/// <remarks>
/// If the task is in its initial <see cref="Common.TaskState.Active"/> state, the PreviousStateTransitionTime property
/// is not defined.
/// </remarks>
public DateTime? PreviousStateTransitionTime
{
get { return this.propertyContainer.PreviousStateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets or sets the number of scheduling slots that the Task required to run.
/// </summary>
/// <remarks>
/// The default is 1. A Task can only be scheduled to run on a compute node if the node has enough free scheduling
/// slots available. For multi-instance Tasks, this must be 1.
/// </remarks>
public int? RequiredSlots
{
get { return this.propertyContainer.RequiredSlotsProperty.Value; }
set { this.propertyContainer.RequiredSlotsProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of files that the Batch service will download to the compute node before running the command
/// line.
/// </summary>
/// <remarks>
/// There is a maximum size for the list of resource files. When the max size is exceeded, the request will fail
/// and the response error code will be RequestEntityTooLarge. If this occurs, the collection of resource files must
/// be reduced in size. This can be achieved using .zip files, Application Packages, or Docker Containers.
/// </remarks>
public IList<ResourceFile> ResourceFiles
{
get { return this.propertyContainer.ResourceFilesProperty.Value; }
set
{
this.propertyContainer.ResourceFilesProperty.Value = ConcurrentChangeTrackedModifiableList<ResourceFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets the current state of the task.
/// </summary>
public Common.TaskState? State
{
get { return this.propertyContainer.StateProperty.Value; }
}
/// <summary>
/// Gets the time at which the task entered its current state.
/// </summary>
public DateTime? StateTransitionTime
{
get { return this.propertyContainer.StateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets resource usage statistics for the task.
/// </summary>
/// <remarks>
/// This property is populated only if the <see cref="CloudTask"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/>
/// including the 'stats' attribute; otherwise it is null.
/// </remarks>
public TaskStatistics Statistics
{
get { return this.propertyContainer.StatisticsProperty.Value; }
}
/// <summary>
/// Gets the URL of the task.
/// </summary>
public string Url
{
get { return this.propertyContainer.UrlProperty.Value; }
}
/// <summary>
/// Gets or sets the user identity under which the task runs.
/// </summary>
/// <remarks>
/// If omitted, the task runs as a non-administrative user unique to the task.
/// </remarks>
public UserIdentity UserIdentity
{
get { return this.propertyContainer.UserIdentityProperty.Value; }
set { this.propertyContainer.UserIdentityProperty.Value = value; }
}
#endregion // CloudTask
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.TaskAddParameter ITransportObjectProvider<Models.TaskAddParameter>.GetTransportObject()
{
Models.TaskAddParameter result = new Models.TaskAddParameter()
{
AffinityInfo = UtilitiesInternal.CreateObjectWithNullCheck(this.AffinityInformation, (o) => o.GetTransportObject()),
ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences),
AuthenticationTokenSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.AuthenticationTokenSettings, (o) => o.GetTransportObject()),
CommandLine = this.CommandLine,
Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()),
ContainerSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.ContainerSettings, (o) => o.GetTransportObject()),
DependsOn = UtilitiesInternal.CreateObjectWithNullCheck(this.DependsOn, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
EnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.EnvironmentSettings),
ExitConditions = UtilitiesInternal.CreateObjectWithNullCheck(this.ExitConditions, (o) => o.GetTransportObject()),
Id = this.Id,
MultiInstanceSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.MultiInstanceSettings, (o) => o.GetTransportObject()),
OutputFiles = UtilitiesInternal.ConvertToProtocolCollection(this.OutputFiles),
RequiredSlots = this.RequiredSlots,
ResourceFiles = UtilitiesInternal.ConvertToProtocolCollection(this.ResourceFiles),
UserIdentity = UtilitiesInternal.CreateObjectWithNullCheck(this.UserIdentity, (o) => o.GetTransportObject()),
};
return result;
}
#endregion // Internal/private methods
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// 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.
//
#if !SILVERLIGHT
namespace NLog.UnitTests.Targets
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Globalization;
using NUnit.Framework;
#if !NUNIT
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
#endif
using NLog.Targets;
[TestFixture]
public class DatabaseTargetTests : NLogTestBase
{
#if !NET_CF && !MONO
static DatabaseTargetTests()
{
var data = (DataSet)ConfigurationManager.GetSection("system.data");
var providerFactories = data.Tables["DBProviderFactories"];
providerFactories.Rows.Add("MockDb Provider", "MockDb Provider", "MockDb", typeof(MockDbFactory).AssemblyQualifiedName);
providerFactories.AcceptChanges();
}
#endif
[Test]
public void SimpleDatabaseTest()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES('${message}')",
ConnectionString = "FooBar",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
};
dt.Initialize(null);
Assert.AreSame(typeof(MockDbConnection), dt.ConnectionType);
List<Exception> exceptions = new List<Exception>();
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add));
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add));
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add));
foreach (var ex in exceptions)
{
Assert.IsNull(ex, Convert.ToString(ex));
}
string expectedLog = @"Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
Close()
Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
Close()
Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
Close()
";
AssertLog(expectedLog);
}
[Test]
public void SimpleBatchedDatabaseTest()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES('${message}')",
ConnectionString = "FooBar",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
};
dt.Initialize(null);
Assert.AreSame(typeof(MockDbConnection), dt.ConnectionType);
List<Exception> exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add),
};
dt.WriteAsyncLogEvents(events);
foreach (var ex in exceptions)
{
Assert.IsNull(ex, Convert.ToString(ex));
}
string expectedLog = @"Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
Close()
";
AssertLog(expectedLog);
}
[Test]
public void KeepConnectionOpenTest()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES('${message}')",
ConnectionString = "FooBar",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
KeepConnection = true,
};
dt.Initialize(null);
Assert.AreSame(typeof(MockDbConnection), dt.ConnectionType);
List<Exception> exceptions = new List<Exception>();
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add));
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add));
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add));
foreach (var ex in exceptions)
{
Assert.IsNull(ex, Convert.ToString(ex));
}
string expectedLog = @"Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
";
AssertLog(expectedLog);
MockDbConnection.ClearLog();
dt.Close();
expectedLog = @"Close()
";
AssertLog(expectedLog);
}
[Test]
public void KeepConnectionOpenBatchedTest()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES('${message}')",
ConnectionString = "FooBar",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
KeepConnection = true,
};
dt.Initialize(null);
Assert.AreSame(typeof(MockDbConnection), dt.ConnectionType);
var exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add),
};
dt.WriteAsyncLogEvents(events);
foreach (var ex in exceptions)
{
Assert.IsNull(ex, Convert.ToString(ex));
}
string expectedLog = @"Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
";
AssertLog(expectedLog);
MockDbConnection.ClearLog();
dt.Close();
expectedLog = @"Close()
";
AssertLog(expectedLog);
}
[Test]
public void KeepConnectionOpenTest2()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES('${message}')",
ConnectionString = "Database=${logger}",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
KeepConnection = true,
};
dt.Initialize(null);
Assert.AreSame(typeof(MockDbConnection), dt.ConnectionType);
List<Exception> exceptions = new List<Exception>();
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add));
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add));
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger2", "msg3").WithContinuation(exceptions.Add));
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg4").WithContinuation(exceptions.Add));
foreach (var ex in exceptions)
{
Assert.IsNull(ex, Convert.ToString(ex));
}
string expectedLog = @"Open('Database=MyLogger').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
Close()
Open('Database=MyLogger2').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
Close()
Open('Database=MyLogger').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg4')
";
AssertLog(expectedLog);
MockDbConnection.ClearLog();
dt.Close();
expectedLog = @"Close()
";
AssertLog(expectedLog);
}
[Test]
public void KeepConnectionOpenBatchedTest2()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES('${message}')",
ConnectionString = "Database=${logger}",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
KeepConnection = true,
};
dt.Initialize(null);
Assert.AreSame(typeof(MockDbConnection), dt.ConnectionType);
// when we pass multiple log events in an array, the target will bucket-sort them by
// connection string and group all commands for the same connection string together
// to minimize number of db open/close operations
// in this case msg1, msg2 and msg4 will be written together to MyLogger database
// and msg3 will be written to MyLogger2 database
List<Exception> exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "MyLogger2", "msg3").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "MyLogger", "msg4").WithContinuation(exceptions.Add),
};
dt.WriteAsyncLogEvents(events);
foreach (var ex in exceptions)
{
Assert.IsNull(ex, Convert.ToString(ex));
}
string expectedLog = @"Open('Database=MyLogger').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg4')
Close()
Open('Database=MyLogger2').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
";
AssertLog(expectedLog);
MockDbConnection.ClearLog();
dt.Close();
expectedLog = @"Close()
";
AssertLog(expectedLog);
}
[Test]
public void ParameterTest()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES(@msg, @lvl, @lg)",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
KeepConnection = true,
Parameters =
{
new DatabaseParameterInfo("msg", "${message}"),
new DatabaseParameterInfo("lvl", "${level}"),
new DatabaseParameterInfo("lg", "${logger}")
}
};
dt.Initialize(null);
Assert.AreSame(typeof(MockDbConnection), dt.ConnectionType);
// when we pass multiple log events in an array, the target will bucket-sort them by
// connection string and group all commands for the same connection string together
// to minimize number of db open/close operations
// in this case msg1, msg2 and msg4 will be written together to MyLogger database
// and msg3 will be written to MyLogger2 database
List<Exception> exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "msg3").WithContinuation(exceptions.Add),
};
dt.WriteAsyncLogEvents(events);
foreach (var ex in exceptions)
{
Assert.IsNull(ex, Convert.ToString(ex));
}
string expectedLog = @"Open('Server=.;Trusted_Connection=SSPI;').
CreateParameter(0)
Parameter #0 Direction=Input
Parameter #0 Name=msg
Parameter #0 Value=msg1
Add Parameter Parameter #0
CreateParameter(1)
Parameter #1 Direction=Input
Parameter #1 Name=lvl
Parameter #1 Value=Info
Add Parameter Parameter #1
CreateParameter(2)
Parameter #2 Direction=Input
Parameter #2 Name=lg
Parameter #2 Value=MyLogger
Add Parameter Parameter #2
ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg)
CreateParameter(0)
Parameter #0 Direction=Input
Parameter #0 Name=msg
Parameter #0 Value=msg3
Add Parameter Parameter #0
CreateParameter(1)
Parameter #1 Direction=Input
Parameter #1 Name=lvl
Parameter #1 Value=Debug
Add Parameter Parameter #1
CreateParameter(2)
Parameter #2 Direction=Input
Parameter #2 Name=lg
Parameter #2 Value=MyLogger2
Add Parameter Parameter #2
ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg)
";
AssertLog(expectedLog);
MockDbConnection.ClearLog();
dt.Close();
expectedLog = @"Close()
";
AssertLog(expectedLog);
}
[Test]
public void ParameterFacetTest()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES(@msg, @lvl, @lg)",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
KeepConnection = true,
Parameters =
{
new DatabaseParameterInfo("msg", "${message}")
{
Precision = 3,
Scale = 7,
Size = 9,
},
new DatabaseParameterInfo("lvl", "${level}")
{
Scale = 7
},
new DatabaseParameterInfo("lg", "${logger}")
{
Precision = 0
},
}
};
dt.Initialize(null);
Assert.AreSame(typeof(MockDbConnection), dt.ConnectionType);
// when we pass multiple log events in an array, the target will bucket-sort them by
// connection string and group all commands for the same connection string together
// to minimize number of db open/close operations
// in this case msg1, msg2 and msg4 will be written together to MyLogger database
// and msg3 will be written to MyLogger2 database
var exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "msg3").WithContinuation(exceptions.Add),
};
dt.WriteAsyncLogEvents(events);
dt.Close();
foreach (var ex in exceptions)
{
Assert.IsNull(ex, Convert.ToString(ex));
}
string expectedLog = @"Open('Server=.;Trusted_Connection=SSPI;').
CreateParameter(0)
Parameter #0 Direction=Input
Parameter #0 Name=msg
Parameter #0 Size=9
Parameter #0 Precision=3
Parameter #0 Scale=7
Parameter #0 Value=msg1
Add Parameter Parameter #0
CreateParameter(1)
Parameter #1 Direction=Input
Parameter #1 Name=lvl
Parameter #1 Scale=7
Parameter #1 Value=Info
Add Parameter Parameter #1
CreateParameter(2)
Parameter #2 Direction=Input
Parameter #2 Name=lg
Parameter #2 Value=MyLogger
Add Parameter Parameter #2
ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg)
CreateParameter(0)
Parameter #0 Direction=Input
Parameter #0 Name=msg
Parameter #0 Size=9
Parameter #0 Precision=3
Parameter #0 Scale=7
Parameter #0 Value=msg3
Add Parameter Parameter #0
CreateParameter(1)
Parameter #1 Direction=Input
Parameter #1 Name=lvl
Parameter #1 Scale=7
Parameter #1 Value=Debug
Add Parameter Parameter #1
CreateParameter(2)
Parameter #2 Direction=Input
Parameter #2 Name=lg
Parameter #2 Value=MyLogger2
Add Parameter Parameter #2
ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg)
Close()
";
AssertLog(expectedLog);
}
[Test]
public void ConnectionStringBuilderTest1()
{
DatabaseTarget dt;
dt = new DatabaseTarget();
Assert.AreEqual("Server=.;Trusted_Connection=SSPI;", this.GetConnectionString(dt));
dt = new DatabaseTarget();
dt.DBHost = "${logger}";
Assert.AreEqual("Server=Logger1;Trusted_Connection=SSPI;", this.GetConnectionString(dt));
dt = new DatabaseTarget();
dt.DBHost = "HOST1";
dt.DBDatabase= "${logger}";
Assert.AreEqual("Server=HOST1;Trusted_Connection=SSPI;Database=Logger1", this.GetConnectionString(dt));
dt = new DatabaseTarget();
dt.DBHost = "HOST1";
dt.DBDatabase = "${logger}";
dt.DBUserName = "user1";
dt.DBPassword = "password1";
Assert.AreEqual("Server=HOST1;User id=user1;Password=password1;Database=Logger1", this.GetConnectionString(dt));
dt = new DatabaseTarget();
dt.ConnectionString = "customConnectionString42";
dt.DBHost = "HOST1";
dt.DBDatabase = "${logger}";
dt.DBUserName = "user1";
dt.DBPassword = "password1";
Assert.AreEqual("customConnectionString42", this.GetConnectionString(dt));
}
[Test]
public void DatabaseExceptionTest1()
{
MockDbConnection.ClearLog();
var exceptions = new List<Exception>();
var db = new DatabaseTarget();
db.CommandText = "not important";
db.ConnectionString = "cannotconnect";
db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName;
db.Initialize(null);
db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
db.Close();
Assert.AreEqual(1, exceptions.Count);
Assert.IsNotNull(exceptions[0]);
Assert.AreEqual("Cannot open fake database.", exceptions[0].Message);
Assert.AreEqual("Open('cannotconnect').\r\n", MockDbConnection.Log);
}
[Test]
public void DatabaseExceptionTest2()
{
MockDbConnection.ClearLog();
var exceptions = new List<Exception>();
var db = new DatabaseTarget();
db.CommandText = "not important";
db.ConnectionString = "cannotexecute";
db.KeepConnection = true;
db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName;
db.Initialize(null);
db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
db.Close();
Assert.AreEqual(3, exceptions.Count);
Assert.IsNotNull(exceptions[0]);
Assert.IsNotNull(exceptions[1]);
Assert.IsNotNull(exceptions[2]);
Assert.AreEqual("Failure during ExecuteNonQuery", exceptions[0].Message);
Assert.AreEqual("Failure during ExecuteNonQuery", exceptions[1].Message);
Assert.AreEqual("Failure during ExecuteNonQuery", exceptions[2].Message);
string expectedLog = @"Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Open('cannotexecute').
ExecuteNonQuery: not important
Close()
";
AssertLog(expectedLog);
}
[Test]
public void DatabaseExceptionTest3()
{
MockDbConnection.ClearLog();
var exceptions = new List<Exception>();
var db = new DatabaseTarget();
db.CommandText = "not important";
db.ConnectionString = "cannotexecute";
db.KeepConnection = true;
db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName;
db.Initialize(null);
db.WriteAsyncLogEvents(
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
db.Close();
Assert.AreEqual(3, exceptions.Count);
Assert.IsNotNull(exceptions[0]);
Assert.IsNotNull(exceptions[1]);
Assert.IsNotNull(exceptions[2]);
Assert.AreEqual("Failure during ExecuteNonQuery", exceptions[0].Message);
Assert.AreEqual("Failure during ExecuteNonQuery", exceptions[1].Message);
Assert.AreEqual("Failure during ExecuteNonQuery", exceptions[2].Message);
string expectedLog = @"Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Open('cannotexecute').
ExecuteNonQuery: not important
Close()
";
AssertLog(expectedLog);
}
#if !NET_CF
[Test]
public void ConnectionStringNameInitTest()
{
var dt = new DatabaseTarget
{
ConnectionStringName = "MyConnectionString",
CommandText = "notimportant",
};
Assert.AreSame(ConfigurationManager.ConnectionStrings, dt.ConnectionStringsSettings);
dt.ConnectionStringsSettings = new ConnectionStringSettingsCollection()
{
new ConnectionStringSettings("MyConnectionString", "cs1", "MockDb"),
};
dt.Initialize(null);
Assert.AreSame(MockDbFactory.Instance, dt.ProviderFactory);
Assert.AreEqual("cs1", dt.ConnectionString.Render(LogEventInfo.CreateNullEvent()));
}
[Test]
public void ConnectionStringNameNegativeTest()
{
var dt = new DatabaseTarget
{
ConnectionStringName = "MyConnectionString",
CommandText = "notimportant",
ConnectionStringsSettings = new ConnectionStringSettingsCollection(),
};
try
{
dt.Initialize(null);
Assert.Fail("Exception expected.");
}
catch (NLogConfigurationException configurationException)
{
Assert.AreEqual("Connection string 'MyConnectionString' is not declared in <connectionStrings /> section.", configurationException.Message);
}
}
[Test]
public void ProviderFactoryInitTest()
{
var dt = new DatabaseTarget();
dt.DBProvider = "MockDb";
dt.CommandText = "Notimportant";
dt.Initialize(null);
Assert.AreSame(MockDbFactory.Instance, dt.ProviderFactory);
dt.OpenConnection("myConnectionString");
Assert.AreEqual(1, MockDbConnection2.OpenCount);
Assert.AreEqual("myConnectionString", MockDbConnection2.LastOpenConnectionString);
}
[Test]
public void SqlServerShorthandNotationTest()
{
foreach (string provName in new[] { "microsoft", "msde", "mssql", "sqlserver" })
{
var dt = new DatabaseTarget()
{
Name = "myTarget",
DBProvider = provName,
ConnectionString = "notimportant",
CommandText = "notimportant",
};
dt.Initialize(null);
Assert.AreEqual(typeof(System.Data.SqlClient.SqlConnection), dt.ConnectionType);
}
}
[Test]
public void OleDbShorthandNotationTest()
{
var dt = new DatabaseTarget()
{
Name = "myTarget",
DBProvider = "oledb",
ConnectionString = "notimportant",
CommandText = "notimportant",
};
dt.Initialize(null);
Assert.AreEqual(typeof(System.Data.OleDb.OleDbConnection), dt.ConnectionType);
}
[Test]
public void OdbcShorthandNotationTest()
{
var dt = new DatabaseTarget()
{
Name = "myTarget",
DBProvider = "odbc",
ConnectionString = "notimportant",
CommandText = "notimportant",
};
dt.Initialize(null);
Assert.AreEqual(typeof(System.Data.Odbc.OdbcConnection), dt.ConnectionType);
}
#endif
private static void AssertLog(string expectedLog)
{
Assert.AreEqual(expectedLog.Replace("\r", ""), MockDbConnection.Log.Replace("\r", ""));
}
private string GetConnectionString(DatabaseTarget dt)
{
MockDbConnection.ClearLog();
dt.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName;
dt.CommandText = "NotImportant";
var exceptions = new List<Exception>();
dt.Initialize(null);
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "msg1").WithContinuation(exceptions.Add));
dt.Close();
return MockDbConnection.LastConnectionString;
}
public class MockDbConnection : IDbConnection
{
public static string Log { get; private set; }
public static string LastConnectionString { get; private set; }
public MockDbConnection()
{
}
public MockDbConnection(string connectionString)
{
this.ConnectionString = connectionString;
}
public IDbTransaction BeginTransaction(IsolationLevel il)
{
throw new NotImplementedException();
}
public IDbTransaction BeginTransaction()
{
throw new NotImplementedException();
}
public void ChangeDatabase(string databaseName)
{
throw new NotImplementedException();
}
public void Close()
{
AddToLog("Close()");
}
public string ConnectionString { get; set; }
public int ConnectionTimeout
{
get { throw new NotImplementedException(); }
}
public IDbCommand CreateCommand()
{
return new MockDbCommand() { Connection = this };
}
public string Database
{
get { throw new NotImplementedException(); }
}
public void Open()
{
LastConnectionString = this.ConnectionString;
AddToLog("Open('{0}').", this.ConnectionString);
if (this.ConnectionString == "cannotconnect")
{
throw new InvalidOperationException("Cannot open fake database.");
}
}
public ConnectionState State
{
get { throw new NotImplementedException(); }
}
public void Dispose()
{
AddToLog("Dispose()");
}
public static void ClearLog()
{
Log = string.Empty;
}
public void AddToLog(string message, params object[] args)
{
if (args.Length > 0)
{
message = string.Format(CultureInfo.InvariantCulture, message, args);
}
Log += message + "\r\n";
}
}
private class MockDbCommand : IDbCommand
{
private int paramCount;
private IDataParameterCollection parameters;
public MockDbCommand()
{
this.parameters = new MockParameterCollection(this);
}
public void Cancel()
{
throw new NotImplementedException();
}
public string CommandText { get; set; }
public int CommandTimeout { get; set; }
public CommandType CommandType { get; set; }
public IDbConnection Connection { get; set; }
public IDbDataParameter CreateParameter()
{
((MockDbConnection)this.Connection).AddToLog("CreateParameter({0})", this.paramCount);
return new MockDbParameter(this, paramCount++);
}
public int ExecuteNonQuery()
{
((MockDbConnection)this.Connection).AddToLog("ExecuteNonQuery: {0}", this.CommandText);
if (this.Connection.ConnectionString == "cannotexecute")
{
throw new InvalidOperationException("Failure during ExecuteNonQuery");
}
return 0;
}
public IDataReader ExecuteReader(CommandBehavior behavior)
{
throw new NotImplementedException();
}
public IDataReader ExecuteReader()
{
throw new NotImplementedException();
}
public object ExecuteScalar()
{
throw new NotImplementedException();
}
public IDataParameterCollection Parameters
{
get { return parameters; }
}
public void Prepare()
{
throw new NotImplementedException();
}
public IDbTransaction Transaction { get; set; }
public UpdateRowSource UpdatedRowSource
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public void Dispose()
{
throw new NotImplementedException();
}
}
private class MockDbParameter : IDbDataParameter
{
private readonly MockDbCommand mockDbCommand;
private readonly int paramId;
private string parameterName;
private object parameterValue;
private DbType parameterType;
public MockDbParameter(MockDbCommand mockDbCommand, int paramId)
{
this.mockDbCommand = mockDbCommand;
this.paramId = paramId;
}
public DbType DbType
{
get { return this.parameterType; }
set { this.parameterType = value; }
}
public ParameterDirection Direction
{
get { throw new NotImplementedException(); }
set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Direction={1}", paramId, value); }
}
public bool IsNullable
{
get { throw new NotImplementedException(); }
}
public string ParameterName
{
get { return this.parameterName; }
set
{
((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Name={1}", paramId, value);
this.parameterName = value;
}
}
public string SourceColumn
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public DataRowVersion SourceVersion
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public object Value
{
get { return this.parameterValue; }
set
{
((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Value={1}", paramId, value);
this.parameterValue = value;
}
}
public byte Precision
{
get { throw new NotImplementedException(); }
set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Precision={1}", paramId, value); }
}
public byte Scale
{
get { throw new NotImplementedException(); }
set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Scale={1}", paramId, value); }
}
public int Size
{
get { throw new NotImplementedException(); }
set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Size={1}", paramId, value); }
}
public override string ToString()
{
return "Parameter #" + this.paramId;
}
}
private class MockParameterCollection : IDataParameterCollection
{
private readonly MockDbCommand command;
public MockParameterCollection(MockDbCommand command)
{
this.command = command;
}
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
public int Count
{
get { throw new NotImplementedException(); }
}
public object SyncRoot
{
get { throw new NotImplementedException(); }
}
public bool IsSynchronized
{
get { throw new NotImplementedException(); }
}
public int Add(object value)
{
((MockDbConnection)command.Connection).AddToLog("Add Parameter {0}", value);
return 0;
}
public bool Contains(object value)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public int IndexOf(object value)
{
throw new NotImplementedException();
}
public void Insert(int index, object value)
{
throw new NotImplementedException();
}
public void Remove(object value)
{
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
object IList.this[int index]
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public bool IsReadOnly
{
get { throw new NotImplementedException(); }
}
public bool IsFixedSize
{
get { throw new NotImplementedException(); }
}
public bool Contains(string parameterName)
{
throw new NotImplementedException();
}
public int IndexOf(string parameterName)
{
throw new NotImplementedException();
}
public void RemoveAt(string parameterName)
{
throw new NotImplementedException();
}
object IDataParameterCollection.this[string parameterName]
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
}
#if !NET_CF
public class MockDbFactory : DbProviderFactory
{
public static readonly MockDbFactory Instance = new MockDbFactory();
public override DbConnection CreateConnection()
{
return new MockDbConnection2();
}
}
public class MockDbConnection2 : DbConnection
{
public static int OpenCount { get; private set; }
public static string LastOpenConnectionString { get; private set; }
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
throw new NotImplementedException();
}
public override void ChangeDatabase(string databaseName)
{
throw new NotImplementedException();
}
public override void Close()
{
throw new NotImplementedException();
}
public override string ConnectionString { get; set; }
protected override DbCommand CreateDbCommand()
{
throw new NotImplementedException();
}
public override string DataSource
{
get { throw new NotImplementedException(); }
}
public override string Database
{
get { throw new NotImplementedException(); }
}
public override void Open()
{
LastOpenConnectionString = this.ConnectionString;
OpenCount++;
}
public override string ServerVersion
{
get { throw new NotImplementedException(); }
}
public override ConnectionState State
{
get { throw new NotImplementedException(); }
}
}
#endif
}
}
#endif
| |
//
// Copyright 2012, Xamarin 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.Net;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
using System.Globalization;
using System.Json;
namespace Xamarin.Utilities
{
public static class WebEx
{
public static string GetCookie (this CookieContainer containers, Uri domain, string name)
{
var c = containers
.GetCookies (domain)
.Cast<Cookie> ()
.FirstOrDefault (x => x.Name == name);
return c != null ? c.Value : "";
}
public static Encoding GetEncodingFromContentType (string contentType)
{
//
// TODO: Parse the Content-Type
//
return Encoding.UTF8;
}
public static string GetResponseText (this WebResponse response)
{
var httpResponse = response as HttpWebResponse;
var encoding = Encoding.UTF8;
if (httpResponse != null) {
encoding = GetEncodingFromContentType (response.ContentType);
}
using (var s = response.GetResponseStream ()) {
using (var r = new StreamReader (s, encoding)) {
return r.ReadToEnd ();
}
}
}
public static Task<WebResponse> GetResponseAsync (this WebRequest request)
{
return Task
.Factory
.FromAsync<WebResponse> (request.BeginGetResponse, request.EndGetResponse, null);
}
static char[] AmpersandChars = new char[] { '&' };
static char[] EqualsChars = new char[] { '=' };
public static IDictionary<string, string> FormDecode (string encodedString)
{
# region
///-------------------------------------------------------------------------------------------------
/// Pull Request - manually added/fixed
/// bug fix in SslCertificateEqualityComparer #76
/// https://github.com/xamarin/Xamarin.Auth/pull/76
/*
var inputs = new Dictionary<string, string> ();
if (encodedString.StartsWith ("?") || encodedString.StartsWith ("#")) {
encodedString = encodedString.Substring (1);
}
var parts = encodedString.Split (AmpersandChars);
foreach (var p in parts) {
var kv = p.Split (EqualsChars);
var k = Uri.UnescapeDataString (kv[0]);
var v = kv.Length > 1 ? Uri.UnescapeDataString (kv[1]) : "";
inputs[k] = v;
}
*/
var inputs = new Dictionary<string, string>();
if (encodedString.Length > 0)
{
char firstChar = encodedString[0];
if (firstChar == '?' || firstChar == '#')
{
encodedString = encodedString.Substring(1);
}
if (encodedString.Length > 0)
{
var parts = encodedString.Split(AmpersandChars, StringSplitOptions.RemoveEmptyEntries);
foreach (var part in parts)
{
var equalsIndex = part.IndexOf('=');
string key;
string value;
if (equalsIndex >= 0)
{
key = Uri.UnescapeDataString(part.Substring(0, equalsIndex));
value = Uri.UnescapeDataString(part.Substring(equalsIndex + 1));
}
else
{
key = Uri.UnescapeDataString(part);
value = string.Empty;
}
inputs[key] = value;
}
}
}
///-------------------------------------------------------------------------------------------------
# endregion
return inputs;
}
public static Dictionary<string, string> JsonDecode (string encodedString)
{
var inputs = new Dictionary<string, string> ();
var json = JsonValue.Parse (encodedString) as JsonObject;
foreach (var kv in json) {
var v = kv.Value as JsonValue;
if (v != null) {
if (v.JsonType != JsonType.String)
inputs[kv.Key] = v.ToString();
else
inputs[kv.Key] = (string)v;
}
}
return inputs;
}
public static string HtmlEncode (string text)
{
if (string.IsNullOrEmpty (text)) {
return "";
}
var sb = new StringBuilder(text.Length);
int len = text.Length;
for (int i = 0; i < len; i++) {
switch (text[i]) {
case '<':
sb.Append("<");
break;
case '>':
sb.Append(">");
break;
case '"':
sb.Append(""");
break;
case '&':
sb.Append("&");
break;
default:
if (text[i] > 159) {
sb.Append ("&#");
sb.Append (((int)text[i]).ToString (CultureInfo.InvariantCulture));
sb.Append (";");
}
else {
sb.Append(text[i]);
}
break;
}
}
return sb.ToString();
}
public static string GetValueFromJson (string json, string key)
{
var p = json.IndexOf ("\"" + key + "\"");
if (p < 0) return "";
var c = json.IndexOf (":", p);
if (c < 0) return "";
var q = json.IndexOf ("\"", c);
if (q < 0) return "";
var b = q + 1;
var e = b;
for (; e < json.Length && json[e] != '\"'; e++) {
}
var r = json.Substring (b, e - b);
return r;
}
}
}
| |
//
// ParserOptions.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.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.
//
using System;
using System.Text;
using System.Reflection;
using System.Collections.Generic;
#if PORTABLE
using Encoding = Portable.Text.Encoding;
#endif
#if ENABLE_CRYPTO
using MimeKit.Cryptography;
#endif
using MimeKit.Tnef;
using MimeKit.Utils;
namespace MimeKit {
/// <summary>
/// Parser options as used by <see cref="MimeParser"/> as well as various Parse and TryParse methods in MimeKit.
/// </summary>
/// <remarks>
/// <see cref="ParserOptions"/> allows you to change and/or override default parsing options used by methods such
/// as <see cref="MimeMessage.Load(ParserOptions,System.IO.Stream,System.Threading.CancellationToken)"/> and others.
/// </remarks>
public class ParserOptions
{
readonly Dictionary<string, ConstructorInfo> mimeTypes = new Dictionary<string, ConstructorInfo> ();
static readonly Type[] ConstructorArgTypes = { typeof (MimeEntityConstructorArgs) };
/// <summary>
/// The default parser options.
/// </summary>
/// <remarks>
/// If a <see cref="ParserOptions"/> is not supplied to <see cref="MimeParser"/> or other Parse and TryParse
/// methods throughout MimeKit, <see cref="ParserOptions.Default"/> will be used.
/// </remarks>
public static readonly ParserOptions Default = new ParserOptions ();
/// <summary>
/// Gets or sets the compliance mode that should be used when parsing rfc822 addresses.
/// </summary>
/// <remarks>
/// <para>In general, you'll probably want this value to be <see cref="RfcComplianceMode.Loose"/>
/// (the default) as it allows maximum interoperability with existing (broken) mail clients
/// and other mail software such as sloppily written perl scripts (aka spambots).</para>
/// <para><alert class="tip">Even in <see cref="RfcComplianceMode.Strict"/> mode, the address
/// parser is fairly liberal in what it accepts. Setting it to <see cref="RfcComplianceMode.Loose"/>
/// just makes it try harder to deal with garbage input.</alert></para>
/// </remarks>
/// <value>The RFC compliance mode.</value>
public RfcComplianceMode AddressParserComplianceMode { get; set; }
/// <summary>
/// Gets or sets the compliance mode that should be used when parsing Content-Type and Content-Disposition parameters.
/// </summary>
/// <remarks>
/// <para>In general, you'll probably want this value to be <see cref="RfcComplianceMode.Loose"/>
/// (the default) as it allows maximum interoperability with existing (broken) mail clients
/// and other mail software such as sloppily written perl scripts (aka spambots).</para>
/// <para><alert class="tip">Even in <see cref="RfcComplianceMode.Strict"/> mode, the parameter
/// parser is fairly liberal in what it accepts. Setting it to <see cref="RfcComplianceMode.Loose"/>
/// just makes it try harder to deal with garbage input.</alert></para>
/// </remarks>
/// <value>The RFC compliance mode.</value>
public RfcComplianceMode ParameterComplianceMode { get; set; }
/// <summary>
/// Gets or sets the compliance mode that should be used when decoding rfc2047 encoded words.
/// </summary>
/// <remarks>
/// In general, you'll probably want this value to be <see cref="RfcComplianceMode.Loose"/>
/// (the default) as it allows maximum interoperability with existing (broken) mail clients
/// and other mail software such as sloppily written perl scripts (aka spambots).
/// </remarks>
/// <value>The RFC compliance mode.</value>
public RfcComplianceMode Rfc2047ComplianceMode { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the Content-Length value should be
/// respected when parsing mbox streams.
/// </summary>
/// <remarks>
/// For more details about why this may be useful, you can find more information
/// at <a href="http://www.jwz.org/doc/content-length.html">
/// http://www.jwz.org/doc/content-length.html</a>.
/// </remarks>
/// <value><c>true</c> if the Content-Length value should be respected;
/// otherwise, <c>false</c>.</value>
public bool RespectContentLength { get; set; }
/// <summary>
/// Gets or sets the charset encoding to use as a fallback for 8bit headers.
/// </summary>
/// <remarks>
/// <see cref="MimeKit.Utils.Rfc2047.DecodeText(ParserOptions, byte[])"/> and
/// <see cref="MimeKit.Utils.Rfc2047.DecodePhrase(ParserOptions, byte[])"/>
/// use this charset encoding as a fallback when decoding 8bit text into unicode. The first
/// charset encoding attempted is UTF-8, followed by this charset encoding, before finally
/// falling back to iso-8859-1.
/// </remarks>
/// <value>The charset encoding.</value>
public Encoding CharsetEncoding { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.ParserOptions"/> class.
/// </summary>
/// <remarks>
/// By default, new instances of <see cref="ParserOptions"/> enable rfc2047 work-arounds
/// (which are needed for maximum interoperability with mail software used in the wild)
/// and do not respect the Content-Length header value.
/// </remarks>
public ParserOptions ()
{
AddressParserComplianceMode = RfcComplianceMode.Loose;
ParameterComplianceMode = RfcComplianceMode.Loose;
Rfc2047ComplianceMode = RfcComplianceMode.Loose;
CharsetEncoding = CharsetUtils.UTF8;
RespectContentLength = false;
}
/// <summary>
/// Clones an instance of <see cref="MimeKit.ParserOptions"/>.
/// </summary>
/// <remarks>
/// Clones a set of options, allowing you to change a specific option
/// without requiring you to change the original.
/// </remarks>
/// <returns>An identical copy of the current instance.</returns>
public ParserOptions Clone ()
{
var options = new ParserOptions ();
options.AddressParserComplianceMode = AddressParserComplianceMode;
options.ParameterComplianceMode = ParameterComplianceMode;
options.Rfc2047ComplianceMode = Rfc2047ComplianceMode;
options.RespectContentLength = RespectContentLength;
options.CharsetEncoding = CharsetEncoding;
foreach (var mimeType in mimeTypes)
options.mimeTypes.Add (mimeType.Key, mimeType.Value);
return options;
}
#if PORTABLE
static ConstructorInfo GetConstructor (TypeInfo type, Type[] argTypes)
{
foreach (var ctor in type.DeclaredConstructors) {
var args = ctor.GetParameters ();
if (args.Length != ConstructorArgTypes.Length)
continue;
bool matched = true;
for (int i = 0; i < argTypes.Length && matched; i++)
matched = matched && args[i].ParameterType == argTypes[i];
if (matched)
return ctor;
}
return null;
}
#endif
/// <summary>
/// Registers the <see cref="MimeEntity"/> subclass for the specified mime-type.
/// </summary>
/// <param name="mimeType">The MIME type.</param>
/// <param name="type">A custom subclass of <see cref="MimeEntity"/>.</param>
/// <remarks>
/// Your custom <see cref="MimeEntity"/> class should not subclass
/// <see cref="MimeEntity"/> directly, but rather it should subclass
/// <see cref="Multipart"/>, <see cref="MimePart"/>,
/// <see cref="MessagePart"/>, or one of their derivatives.
/// </remarks>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="mimeType"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="type"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="type"/> is not a subclass of <see cref="Multipart"/>,
/// <see cref="MimePart"/>, or <see cref="MessagePart"/>.</para>
/// <para>-or-</para>
/// <para><paramref name="type"/> does not have a constructor that takes
/// only a <see cref="MimeEntityConstructorArgs"/> argument.</para>
/// </exception>
public void RegisterMimeType (string mimeType, Type type)
{
if (mimeType == null)
throw new ArgumentNullException ("mimeType");
if (type == null)
throw new ArgumentNullException ("type");
mimeType = mimeType.ToLowerInvariant ();
#if PORTABLE || COREFX
var info = type.GetTypeInfo ();
#else
var info = type;
#endif
if (!info.IsSubclassOf (typeof (MessagePart)) &&
!info.IsSubclassOf (typeof (Multipart)) &&
!info.IsSubclassOf (typeof (MimePart)))
throw new ArgumentException ("The specified type must be a subclass of MessagePart, Multipart, or MimePart.", "type");
#if PORTABLE
var ctor = GetConstructor (info, ConstructorArgTypes);
#else
var ctor = type.GetConstructor (ConstructorArgTypes);
#endif
if (ctor == null)
throw new ArgumentException ("The specified type must have a constructor that takes a MimeEntityConstructorArgs argument.", "type");
mimeTypes[mimeType] = ctor;
}
static bool IsEncoded (IList<Header> headers)
{
ContentEncoding encoding;
for (int i = 0; i < headers.Count; i++) {
if (headers[i].Id != HeaderId.ContentTransferEncoding)
continue;
MimeUtils.TryParse (headers[i].Value, out encoding);
switch (encoding) {
case ContentEncoding.SevenBit:
case ContentEncoding.EightBit:
case ContentEncoding.Binary:
return false;
default:
return true;
}
}
return false;
}
internal MimeEntity CreateEntity (ContentType contentType, IList<Header> headers, bool toplevel)
{
var args = new MimeEntityConstructorArgs (this, contentType, headers, toplevel);
var subtype = contentType.MediaSubtype.ToLowerInvariant ();
var type = contentType.MediaType.ToLowerInvariant ();
if (mimeTypes.Count > 0) {
var mimeType = string.Format ("{0}/{1}", type, subtype);
ConstructorInfo ctor;
if (mimeTypes.TryGetValue (mimeType, out ctor))
return (MimeEntity) ctor.Invoke (new object[] { args });
}
// Note: message/rfc822 and message/partial are not allowed to be encoded according to rfc2046
// (sections 5.2.1 and 5.2.2, respectively). Since some broken clients will encode them anyway,
// it is necessary for us to treat those as opaque blobs instead, and thus the parser should
// parse them as normal MimeParts instead of MessageParts.
//
// Technically message/disposition-notification is only allowed to have use the 7bit encoding
// as well, but since MessageDispositionNotification is a MImePart subclass rather than a
// MessagePart subclass, it means that the content won't be parsed until later and so we can
// actually handle that w/o any problems.
if (type == "message") {
switch (subtype) {
case "disposition-notification":
return new MessageDispositionNotification (args);
case "delivery-status":
return new MessageDeliveryStatus (args);
case "partial":
if (!IsEncoded (headers))
return new MessagePartial (args);
break;
case "external-body":
case "rfc2822":
case "rfc822":
case "news":
if (!IsEncoded (headers))
return new MessagePart (args);
break;
}
}
if (type == "multipart") {
switch (subtype) {
case "alternative":
return new MultipartAlternative (args);
case "related":
return new MultipartRelated (args);
case "report":
return new MultipartReport (args);
#if ENABLE_CRYPTO
case "encrypted":
return new MultipartEncrypted (args);
case "signed":
return new MultipartSigned (args);
#endif
default:
return new Multipart (args);
}
}
if (type == "application") {
switch (subtype) {
#if ENABLE_CRYPTO
case "x-pkcs7-signature":
case "pkcs7-signature":
return new ApplicationPkcs7Signature (args);
case "x-pgp-encrypted":
case "pgp-encrypted":
return new ApplicationPgpEncrypted (args);
case "x-pgp-signature":
case "pgp-signature":
return new ApplicationPgpSignature (args);
case "x-pkcs7-mime":
case "pkcs7-mime":
return new ApplicationPkcs7Mime (args);
#endif
case "vnd.ms-tnef":
case "ms-tnef":
return new TnefPart (args);
case "rtf":
return new TextPart (args);
}
}
if (type == "text")
return new TextPart (args);
return new MimePart (args);
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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
// http://code.google.com/p/swfupload/
using System;
using System.Text;
using System.Web.UI;
namespace Contoso.Web.UI.ClientShapes
{
/// <summary>
/// SwfUploadShape
/// </summary>
public class SwfUploadShape : ClientScriptItemBase
{
/// <summary>
/// Initializes a new instance of the <see cref="SwfUploadShape"/> class.
/// </summary>
public SwfUploadShape()
: this(null) { }
/// <summary>
/// Initializes a new instance of the <see cref="SwfUploadShape"/> class.
/// </summary>
/// <param name="settings">The settings.</param>
public SwfUploadShape(object settings)
: this(Nparams.Parse(settings)) { }
/// <summary>
/// Initializes a new instance of the <see cref="SwfUploadShape"/> class.
/// </summary>
/// <param name="settings">The settings.</param>
public SwfUploadShape(Nparams settings)
{
var registrar = ClientScriptRegistrarSwfUploadShape.AssertRegistered();
Settings = settings;
// set defaults
UploadUrl = DefaultValues.UploadUrl;
FilePostName = DefaultValues.FilePostName;
FileTypes = DefaultValues.FileTypes;
FileTypesDescription = DefaultValues.FileTypesDescription;
FileSizeLimit = DefaultValues.FileSizeLimit;
FlashUrl = DefaultValues.FlashUrl;
PreventSwfCaching = DefaultValues.PreventSwfCaching;
ButtonPlaceholderID = DefaultValues.ButtonPlaceholderID;
ButtonImageUrl = DefaultValues.ButtonImageUrl;
ButtonWidth = DefaultValues.ButtonWidth;
ButtonHeight = DefaultValues.ButtonHeight;
ButtonText = DefaultValues.ButtonText;
ButtonTextStyle = DefaultValues.ButtonTextStyle;
ButtonAction = DefaultValues.ButtonAction;
//
FlashUrl = registrar.SwfUploadFlashUrl;
}
/// <summary>
/// Gets or sets the registrar.
/// </summary>
/// <value>
/// The registrar.
/// </value>
protected ClientScriptRegistrarSwfUploadShape Registrar { get; set; }
/// <summary>
/// Renders the specified b.
/// </summary>
/// <param name="b">The b.</param>
public override void Render(StringBuilder b)
{
var options = MakeOptions();
if (Settings != null)
foreach (var setting in Settings.Values)
{
var optionBuilder = (setting as IClientScriptItemOption);
if (optionBuilder != null)
options.AddRange(optionBuilder.MakeOption());
}
var optionsAsText = ClientScript.EncodeDictionary(options, true);
b.AppendLine("new SWFUpload(" + (optionsAsText.Length > 2 ? optionsAsText : ClientScript.EmptyObject) + ");");
}
/// <summary>
/// Gets or sets the settings.
/// </summary>
/// <value>
/// The settings.
/// </value>
public Nparams Settings { get; set; }
#region Options
/// <summary>
///
/// </summary>
public enum Action
{
/// <summary>
/// SelectFile
/// </summary>
SelectFile,
/// <summary>
/// SelectFiles
/// </summary>
SelectFiles,
/// <summary>
/// StartUpload
/// </summary>
StartUpload,
}
/// <summary>
///
/// </summary>
public enum Cursor
{
/// <summary>
/// Arrow
/// </summary>
Arrow,
/// <summary>
/// Hand
/// </summary>
Hand,
}
/// <summary>
/// WindowMode
/// </summary>
public enum WindowMode
{
/// <summary>
/// Window
/// </summary>
Window,
/// <summary>
/// Transparent
/// </summary>
Transparent,
/// <summary>
/// Opaque
/// </summary>
Opaque,
}
/// <summary>
/// DefaultValues
/// </summary>
public static class DefaultValues
{
// UPLOAD BACKEND SETTINGS
/// <summary>
/// UploadUrl
/// </summary>
public static readonly string UploadUrl = string.Empty;
/// <summary>
/// PreserveRelativeUrls
/// </summary>
public static readonly bool PreserveRelativeUrls = false;
/// <summary>
/// FilePostName
/// </summary>
public static readonly string FilePostName = "Filedata";
/// <summary>
/// PostParams
/// </summary>
public static readonly object PostParams = null;
/// <summary>
/// UseQueryString
/// </summary>
public static readonly bool UseQueryString = false;
/// <summary>
/// RequeueOnError
/// </summary>
public static readonly bool RequeueOnError = false;
/// <summary>
/// HttpSuccess
/// </summary>
public static readonly string[] HttpSuccess = null;
/// <summary>
/// AssumeSuccessTimeout
/// </summary>
public static readonly int AssumeSuccessTimeout = 0;
// FILE SETTINGS
/// <summary>
/// FileTypes
/// </summary>
public static readonly string FileTypes = "*.*";
/// <summary>
/// FileTypesDescription
/// </summary>
public static readonly string FileTypesDescription = "All Files";
/// <summary>
/// FileSizeLimit
/// </summary>
public static readonly string FileSizeLimit = "0"; //- default zero means "unlimited"
/// <summary>
/// FileUploadLimit
/// </summary>
public static readonly int FileUploadLimit = 0;
/// <summary>
/// FileQueueLimit
/// </summary>
public static readonly int FileQueueLimit = 0;
// FLASH SETTINGS
/// <summary>
/// FlashUrl
/// </summary>
public static readonly string FlashUrl = "swfupload.swf";
/// <summary>
/// PreventSwfCaching
/// </summary>
public static readonly bool PreventSwfCaching = true;
/// <summary>
/// Debug
/// </summary>
public static readonly bool Debug = false;
// BUTTON SETTINGS
/// <summary>
/// ButtonImageUrl
/// </summary>
public static readonly string ButtonImageUrl = string.Empty;
/// <summary>
/// ButtonWidth
/// </summary>
public static readonly int ButtonWidth = 1;
/// <summary>
/// ButtonHeight
/// </summary>
public static readonly int ButtonHeight = 1;
/// <summary>
/// ButtonText
/// </summary>
public static readonly string ButtonText = string.Empty;
/// <summary>
/// ButtonTextStyle
/// </summary>
public static readonly string ButtonTextStyle = "color: #000000; font-size: 16pt;";
/// <summary>
/// ButtonTextTopPadding
/// </summary>
public static readonly int ButtonTextTopPadding = 0;
/// <summary>
/// ButtonTextLeftPadding
/// </summary>
public static readonly int ButtonTextLeftPadding = 0;
/// <summary>
/// ButtonAction
/// </summary>
public static readonly Action ButtonAction = Action.SelectFiles;
/// <summary>
/// ButtonDisabled
/// </summary>
public static readonly bool ButtonDisabled = false;
/// <summary>
/// ButtonPlaceholderID
/// </summary>
public static readonly string ButtonPlaceholderID = string.Empty;
/// <summary>
/// ButtonPlaceholder
/// </summary>
public static readonly string ButtonPlaceholder = null;
/// <summary>
/// ButtonCursor
/// </summary>
public static readonly Cursor ButtonCursor = Cursor.Arrow;
/// <summary>
/// ButtonWindowMode
/// </summary>
public static readonly WindowMode ButtonWindowMode = WindowMode.Window;
// EVENT HANDLERS
/// <summary>
/// SwfUploadLoadedHandler
/// </summary>
public static readonly string SwfUploadLoadedHandler = null;
/// <summary>
/// FileDialogStartHandler
/// </summary>
public static readonly string FileDialogStartHandler = null;
/// <summary>
/// FileQueuedHandler
/// </summary>
public static readonly string FileQueuedHandler = null;
/// <summary>
/// FileQueueErrorHandler
/// </summary>
public static readonly string FileQueueErrorHandler = null;
/// <summary>
/// FileDialogCompleteHandler
/// </summary>
public static readonly string FileDialogCompleteHandler = null;
/// <summary>
/// UploadStartHandler
/// </summary>
public static readonly string UploadStartHandler = null;
/// <summary>
/// UploadProgressHandler
/// </summary>
public static readonly string UploadProgressHandler = null;
/// <summary>
/// UploadErrorHandler
/// </summary>
public static readonly string UploadErrorHandler = null;
/// <summary>
/// UploadSuccessHandler
/// </summary>
public static readonly string UploadSuccessHandler = null;
/// <summary>
/// UploadCompleteHandler
/// </summary>
public static readonly string UploadCompleteHandler = null;
/// <summary>
/// DebugHandler
/// </summary>
public static readonly string DebugHandler = null;
// CUSTOM SETTINGS
/// <summary>
/// CustomSettings
/// </summary>
public static readonly object CustomSettings = null;
}
/// <summary>
/// Makes the options.
/// </summary>
/// <returns></returns>
protected virtual Nparams MakeOptions()
{
var options = Nparams.Create();
// UPLOAD BACKEND SETTINGS
if (UploadUrl != DefaultValues.UploadUrl)
options["upload_url"] = ClientScript.EncodeText(UploadUrl);
if (FilePostName != DefaultValues.FilePostName)
options["file_post_name"] = ClientScript.EncodeText(FilePostName);
if (PostParams != DefaultValues.PostParams)
options["post_params"] = ClientScript.EncodeDictionary(Nparams.Parse(PostParams));
if (UseQueryString != DefaultValues.UseQueryString)
options["use_query_string"] = ClientScript.EncodeBool(UseQueryString);
if (PreserveRelativeUrls != DefaultValues.PreserveRelativeUrls)
options["preserve_relative_urls"] = ClientScript.EncodeBool(PreserveRelativeUrls);
if (RequeueOnError != DefaultValues.RequeueOnError)
options["requeue_on_error"] = ClientScript.EncodeBool(RequeueOnError);
if (HttpSuccess != DefaultValues.HttpSuccess)
options["http_success"] = ClientScript.EncodeArray(HttpSuccess);
if (AssumeSuccessTimeout != DefaultValues.AssumeSuccessTimeout)
options["assume_success_timeout"] = ClientScript.EncodeInt32(AssumeSuccessTimeout);
// FILE SETTINGS
if (FileTypes != DefaultValues.FileTypes)
options["file_types"] = ClientScript.EncodeText(FileTypes);
if (FileTypesDescription != DefaultValues.FileTypesDescription)
options["file_types_description"] = ClientScript.EncodeText(FileTypesDescription);
if (FileSizeLimit != DefaultValues.FileSizeLimit)
options["file_size_limit"] = ClientScript.EncodeText(FileSizeLimit);
if (FileUploadLimit != DefaultValues.FileUploadLimit)
options["file_upload_limit"] = ClientScript.EncodeInt32(FileUploadLimit);
if (FileQueueLimit != DefaultValues.FileQueueLimit)
options["file_queue_limit"] = ClientScript.EncodeInt32(FileQueueLimit);
// FLASH SETTINGS
if (FlashUrl != DefaultValues.FlashUrl)
options["flash_url"] = ClientScript.EncodeText(FlashUrl);
if (FlashWidth != null)
options["flash_width"] = ClientScript.EncodeText(FlashWidth);
if (FlashHeight != null)
options["flash_height"] = ClientScript.EncodeText(FlashHeight);
if (FlashColor != null)
options["flash_color"] = ClientScript.EncodeText(FlashColor);
if (PreventSwfCaching != DefaultValues.PreventSwfCaching)
options["prevent_swf_caching"] = ClientScript.EncodeBool(PreventSwfCaching);
if (Debug != DefaultValues.Debug)
options["debug"] = ClientScript.EncodeBool(Debug);
// BUTTON SETTINGS
if (ButtonPlaceholderID != DefaultValues.ButtonPlaceholderID)
options["button_placeholder_id"] = ClientScript.EncodeText(ButtonPlaceholderID);
if (ButtonPlaceholder != DefaultValues.ButtonPlaceholder)
options["button_placeholder"] = ClientScript.EncodeExpression(ButtonPlaceholder);
if (ButtonImageUrl != DefaultValues.ButtonImageUrl)
options["button_image_url"] = ClientScript.EncodeText(ButtonImageUrl);
if (ButtonWidth != DefaultValues.ButtonWidth)
options["button_width"] = ClientScript.EncodeInt32(ButtonWidth);
if (ButtonHeight != DefaultValues.ButtonHeight)
options["button_height"] = ClientScript.EncodeInt32(ButtonHeight);
if (ButtonText != DefaultValues.ButtonText)
options["button_text"] = ClientScript.EncodeText(ButtonText);
if (ButtonTextStyle != DefaultValues.ButtonTextStyle)
options["button_text_style"] = ClientScript.EncodeText(ButtonTextStyle);
if (ButtonTextTopPadding != DefaultValues.ButtonTextTopPadding)
options["button_text_top_padding"] = ClientScript.EncodeInt32(ButtonTextTopPadding);
if (ButtonTextLeftPadding != DefaultValues.ButtonTextLeftPadding)
options["button_text_left_padding"] = ClientScript.EncodeInt32(ButtonTextLeftPadding);
if (ButtonAction != DefaultValues.ButtonAction)
switch (ButtonAction)
{
case Action.SelectFile:
options["button_action"] = "SWFUpload.BUTTON_ACTION.SELECT_FILE";
break;
case Action.SelectFiles:
options["button_action"] = "SWFUpload.BUTTON_ACTION.SELECT_FILES";
break;
case Action.StartUpload:
options["button_action"] = "SWFUpload.BUTTON_ACTION.START_UPLOAD";
break;
default:
throw new InvalidOperationException();
}
if (ButtonDisabled != DefaultValues.ButtonDisabled)
options["button_disabled"] = ClientScript.EncodeBool(ButtonDisabled);
if (ButtonCursor != DefaultValues.ButtonCursor)
switch (ButtonCursor)
{
case Cursor.Arrow:
options["button_cursor"] = "SWFUpload.CURSOR.ARROW";
break;
case Cursor.Hand:
options["button_cursor"] = "SWFUpload.CURSOR.HAND";
break;
default:
throw new InvalidOperationException();
}
if (ButtonWindowMode != DefaultValues.ButtonWindowMode)
switch (ButtonWindowMode)
{
case WindowMode.Window:
options["button_window_mode"] = "SWFUpload.WINDOW_MODE.WINDOW";
break;
case WindowMode.Transparent:
options["button_window_mode"] = "SWFUpload.WINDOW_MODE.TRANSPARENT";
break;
case WindowMode.Opaque:
options["button_window_mode"] = "SWFUpload.WINDOW_MODE.OPAQUE";
break;
default:
throw new InvalidOperationException();
}
// EVENT HANDLERS
if (SwfUploadLoadedHandler != DefaultValues.SwfUploadLoadedHandler)
options["swfupload_loaded_handler"] = ClientScript.EncodeExpression(SwfUploadLoadedHandler);
if (FileDialogStartHandler != DefaultValues.FileDialogStartHandler)
options["file_dialog_start_handler"] = ClientScript.EncodeExpression(FileDialogStartHandler);
if (FileQueuedHandler != DefaultValues.FileQueuedHandler)
options["file_queued_handler"] = ClientScript.EncodeExpression(FileQueuedHandler);
if (FileQueueErrorHandler != DefaultValues.FileQueueErrorHandler)
options["file_queue_error_handler"] = ClientScript.EncodeExpression(FileQueueErrorHandler);
if (FileDialogCompleteHandler != DefaultValues.FileDialogCompleteHandler)
options["file_dialog_complete_handler"] = ClientScript.EncodeExpression(FileDialogCompleteHandler);
if (UploadStartHandler != DefaultValues.UploadStartHandler)
options["upload_start_handler"] = ClientScript.EncodeExpression(UploadStartHandler);
if (UploadProgressHandler != DefaultValues.UploadProgressHandler)
options["upload_progress_handler"] = ClientScript.EncodeExpression(UploadProgressHandler);
if (UploadErrorHandler != DefaultValues.UploadErrorHandler)
options["upload_error_handler"] = ClientScript.EncodeExpression(UploadErrorHandler);
if (UploadSuccessHandler != DefaultValues.UploadSuccessHandler)
options["upload_success_handler"] = ClientScript.EncodeExpression(UploadSuccessHandler);
if (UploadCompleteHandler != DefaultValues.UploadCompleteHandler)
options["upload_complete_handler"] = ClientScript.EncodeExpression(UploadCompleteHandler);
if (DebugHandler != DefaultValues.DebugHandler)
options["debug_handler"] = ClientScript.EncodeExpression(DebugHandler);
// CUSTOM SETTINGS
if (CustomSettings != DefaultValues.CustomSettings)
options["custom_settings"] = ClientScript.EncodeDictionary(Nparams.Parse(CustomSettings));
return options;
}
/// <summary>
/// Gets or sets the upload URL.
/// </summary>
/// <value>
/// The upload URL.
/// </value>
/// <remarks>
/// The upload_url setting accepts a full, absolute, or relative target URL for the uploaded file. Relative URLs should be relative to document. The upload_url should be in the same domain as the Flash Control for best compatibility.
/// If the preserve_relative_urls setting is false SWFUpload will convert the relative URL to an absolute URL to avoid the URL being interpreted differently by the Flash Player on different platforms. If you disable SWFUploads conversion of the URL relative URLs should be relative to the swfupload.swf file.
/// </remarks>
public string UploadUrl { get; set; }
/// <summary>
/// Gets or sets the name of the file post.
/// </summary>
/// <value>
/// The name of the file post.
/// </value>
/// <remarks>
/// The file_post_name allows you to set the value name used to post the file. This is not related to the file name. The default value is 'Filedata'. For maximum compatibility it is recommended that the default value is used.
/// </remarks>
public string FilePostName { get; set; }
/// <summary>
/// Gets or sets the post params.
/// </summary>
/// <value>
/// The post params.
/// </value>
/// <remarks>
/// The post_params setting defines the name/value pairs that will be posted with each uploaded file. This setting accepts a simple JavaScript object. Multiple post name/value pairs should be defined as demonstrated in the sample settings object. Values must be either strings or numbers (as interpreted by the JavaScript typeof function).
/// Note: Flash Player 8 does not support sending additional post parameters. SWFUpload will automatically send the post_params as part of the query string.
/// </remarks>
public object PostParams { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [use query string].
/// </summary>
/// <value>
/// <c>true</c> if [use query string]; otherwise, <c>false</c>.
/// </value>
/// <remarks>
/// The use_query_string setting may be true or false. This value indicates whether SWFUpload should send the post_params and file params on the query string or the post. This setting was introduced in SWFUpload v2.1.0.
/// </remarks>
public bool UseQueryString { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [preserve relative urls].
/// </summary>
/// <value>
/// <c>true</c> if [preserve relative urls]; otherwise, <c>false</c>.
/// </value>
/// <remarks>
/// A boolean value that indicates whether SWFUpload should attempt to convert relative URLs used by the Flash Player to absolute URLs. If set to true SWFUpload will not modify any URLs. The default value is false.
/// </remarks>
public bool PreserveRelativeUrls { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [requeue on error].
/// </summary>
/// <value>
/// <c>true</c> if [requeue on error]; otherwise, <c>false</c>.
/// </value>
/// <remarks>
/// The requeue_on_error setting may be true or false. When this setting is true any files that has an uploadError (excluding fileQueue errors and the FILE_CANCELLED uploadError) is returned to the front of the queue rather than being discarded. The file can be uploaded again if needed. To remove the file from the queue the cancelUpload method must be called.
/// All the events associated with a failed upload are still called and so the requeuing the failed upload can conflict with the Queue Plugin (or custom code that uploads the entire queue). Code that automatically uploads the next file in the queue will upload the failed file over and over again if care is not taken to allow the failing upload to be cancelled.
/// This setting was introduced in SWFUpload v2.1.0.
/// </remarks>
public bool RequeueOnError { get; set; }
/// <summary>
/// Gets or sets the HTTP success.
/// </summary>
/// <value>
/// The HTTP success.
/// </value>
/// <remarks>
/// An array that defines the HTTP Status Codes that will trigger success. 200 is always a success. Also, only the 200 status code provides the serverData.
/// When returning and accepting an HTTP Status Code other than 200 it is not necessary for the server to return content.
/// </remarks>
public string[] HttpSuccess { get; set; }
/// <summary>
/// Gets or sets the assume success timeout.
/// </summary>
/// <value>
/// The assume success timeout.
/// </value>
/// <remarks>
/// The number of seconds SWFUpload should wait for Flash to detect the server's response after the file has finished uploading. This setting allows you to work around the Flash Player bugs where long running server side scripts causes Flash to ignore the server response or the Mac Flash Player bug that ignores server responses with no content.
/// Testing has shown that Flash will ignore server responses that take longer than 30 seconds after the last uploadProgress event.
/// A timeout of zero (0) seconds disables this feature and is the default value. SWFUpload will wait indefinitely for the Flash Player to trigger the uploadSuccess event.
/// </remarks>
public int AssumeSuccessTimeout { get; set; }
/// <summary>
/// Gets or sets the file types.
/// </summary>
/// <value>
/// The file types.
/// </value>
/// <remarks>
/// The file_types setting accepts a semi-colon separated list of file extensions that are allowed to be selected by the user. Use '*.*' to allow all file types.
/// </remarks>
public string FileTypes { get; set; }
/// <summary>
/// Gets or sets the file types description.
/// </summary>
/// <value>
/// The file types description.
/// </value>
/// <remarks>
/// A text description that is displayed to the user in the File Browser dialog.
/// </remarks>
public string FileTypesDescription { get; set; }
/// <summary>
/// Gets or sets the file size limit.
/// </summary>
/// <value>
/// The file size limit.
/// </value>
/// <remarks>
/// The file_size_limit setting defines the maximum allowed size of a file to be uploaded. This setting accepts a value and unit. Valid units are B, KB, MB and GB. If the unit is omitted default is KB. A value of 0 (zero) is interpreted as unlimited.
/// Note: This setting only applies to the user's browser. It does not affect any settings or limits on the web server.
/// </remarks>
public string FileSizeLimit { get; set; }
/// <summary>
/// Gets or sets the file upload limit.
/// </summary>
/// <value>
/// The file upload limit.
/// </value>
/// <remarks>
/// Defines the number of files allowed to be uploaded by SWFUpload. This setting also sets the upper bound of the file_queue_limit setting. Once the user has uploaded or queued the maximum number of files she will no longer be able to queue additional files. The value of 0 (zero) is interpreted as unlimited. Only successful uploads (uploads the trigger the uploadSuccess event) are counted toward the upload limit. The setStats function can be used to modify the number of successful uploads.
/// Note: This value is not tracked across pages and is reset when a page is refreshed. File quotas should be managed by the web server.
/// </remarks>
public int FileUploadLimit { get; set; }
/// <summary>
/// Gets or sets the file queue limit.
/// </summary>
/// <value>
/// The file queue limit.
/// </value>
/// <remarks>
/// Defines the number of unprocessed files allowed to be simultaneously queued. Once a file is uploaded, errored, or cancelled a new files can be queued in its place until the queue limit has been reached. If the upload limit (or remaining uploads allowed) is less than the queue limit then the lower number is used.
/// </remarks>
public int FileQueueLimit { get; set; }
/// <summary>
/// Gets or sets the flash URL.
/// </summary>
/// <value>
/// The flash URL.
/// </value>
/// <remarks>
/// The full, absolute, or relative URL to the Flash Control swf file. This setting cannot be changed once the SWFUpload has been instantiated. Relative URLs are relative to the page URL.
/// </remarks>
public string FlashUrl { get; set; }
/// <summary>
/// Gets or sets the width of the flash.
/// </summary>
/// <value>
/// The width of the flash.
/// </value>
/// <remarks>
/// (Removed in v2.1.0) Defines the width of the HTML element that contains the flash. Some browsers do not function correctly if this setting is less than 1 px. This setting is optional and has a default value of 1px.
/// </remarks>
public string FlashWidth { get; set; }
/// <summary>
/// Gets or sets the height of the flash.
/// </summary>
/// <value>
/// The height of the flash.
/// </value>
/// <remarks>
/// (Removed in v2.1.0) Defines the height of the HTML element that contains the flash. Some browsers do not function correctly if this setting is less than 1 px. This setting is optional and has a default value of 1px.
/// </remarks>
public string FlashHeight { get; set; }
/// <summary>
/// Gets or sets the color of the flash.
/// </summary>
/// <value>
/// The color of the flash.
/// </value>
/// <remarks>
/// Removed in v2.2.0 This setting sets the background color of the HTML element that contains the flash. The default value is '#FFFFFF'.
/// Note: This setting may not be effective in "skinning" 1px flash element in all browsers.
/// </remarks>
public string FlashColor { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [prevent SWF caching].
/// </summary>
/// <value>
/// <c>true</c> if [prevent SWF caching]; otherwise, <c>false</c>.
/// </value>
/// <remarks>
/// Added in v2.2.0 This boolean setting indicates whether a random value should be added to the Flash URL in an attempt to prevent the browser from caching the SWF movie. This works around a bug in some IE-engine based browsers.
/// Note: The algorithm for adding the random number to the URL is dumb and cannot handle URLs that already have some parameters.
/// </remarks>
public bool PreventSwfCaching { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="SwfUploadShape"/> is debug.
/// </summary>
/// <value>
/// <c>true</c> if debug; otherwise, <c>false</c>.
/// </value>
public bool Debug { get; set; }
/// <summary>
/// Gets or sets the button placeholder id.
/// </summary>
/// <value>
/// The button placeholder id.
/// </value>
/// <remarks>
/// (Added in v2.2.0) This required setting sets the ID of DOM element that will be replaced by the Flash Button. This setting overrides the button_placeholder setting. The Flash button can be styled using the CSS class 'swfupload'.
/// </remarks>
public string ButtonPlaceholderID { get; set; }
/// <summary>
/// Gets or sets the button placeholder.
/// </summary>
/// <value>
/// The button placeholder.
/// </value>
/// <remarks>
/// (Added in v2.2.0) This required setting sets the DOM element that will be replaced by the Flash Button. This setting is only applied if the button_placeholder_id is not set. The Flash button can be styled using the CSS class 'swfupload'.
/// </remarks>
public string ButtonPlaceholder { get; set; }
/// <summary>
/// Gets or sets the button image URL.
/// </summary>
/// <value>
/// The button image URL.
/// </value>
/// <remarks>
/// (Added in v2.2.0) Fully qualified, absolute or relative URL to the image file to be used as the Flash button. Any Flash supported image file format can be used (another SWF file or gif, jpg, or png).
/// This URL is affected by the preserve_relative_urls setting and should follow the same rules as the upload_url setting.
/// The button image is treated as a sprite. There are 4 button states that must be represented by the button image. Each button state image should be stacked above the other in this order: normal, hover, down/click, disabled.
/// </remarks>
public string ButtonImageUrl { get; set; }
/// <summary>
/// Gets or sets the width of the button.
/// </summary>
/// <value>
/// The width of the button.
/// </value>
/// <remarks>
/// (Added in v2.2.0) A number defining the width of the Flash button.
/// </remarks>
public int ButtonWidth { get; set; }
/// <summary>
/// Gets or sets the height of the button.
/// </summary>
/// <value>
/// The height of the button.
/// </value>
/// <remarks>
/// (Added in v2.2.0) A number defining the height of the Flash button. This value should be 1/4th of the height or the button image.
/// </remarks>
public int ButtonHeight { get; set; }
/// <summary>
/// Gets or sets the button text.
/// </summary>
/// <value>
/// The button text.
/// </value>
/// <remarks>
/// (Added in v2.2.0) Plain or HTML text that is displayed over the Flash button. HTML text can be further styled using CSS classes and the button_text_style setting. See Adobe's Flash documentation for details.
/// </remarks>
public string ButtonText { get; set; }
/// <summary>
/// Gets or sets the button text style.
/// </summary>
/// <value>
/// The button text style.
/// </value>
/// <remarks>
/// (Added in v2.2.0) CSS style string that defines how the button_text is displayed. See Adobe's Flash documentation for details.
/// </remarks>
public string ButtonTextStyle { get; set; }
/// <summary>
/// Gets or sets the button text top padding.
/// </summary>
/// <value>
/// The button text top padding.
/// </value>
/// <remarks>
/// (Added in v2.2.0) Used to vertically position the Flash button text. Negative values may be used.
/// </remarks>
public int ButtonTextTopPadding { get; set; }
/// <summary>
/// Gets or sets the button text left padding.
/// </summary>
/// <value>
/// The button text left padding.
/// </value>
/// <remarks>
/// (Added in v2.2.0) Used to horizontally position the Flash button text. Negative values may be used.
/// </remarks>
public int ButtonTextLeftPadding { get; set; }
/// <summary>
/// Gets or sets the button action.
/// </summary>
/// <value>
/// The button action.
/// </value>
/// <remarks>
/// (Added in v2.2.0) Defines the action taken when the Flash button is clicked. Valid action values can be found in the swfupload.js file under the BUTTON_ACTION object.
/// </remarks>
public Action ButtonAction { get; set; }
/// <summary>
/// Gets or sets the button disabled.
/// </summary>
/// <value>
/// The button disabled.
/// </value>
/// <remarks>
/// (Added in v2.2.0) A boolean value that sets whether the Flash button is in the disabled state. When in the disabled state the button will not execute any actions.
/// </remarks>
public bool ButtonDisabled { get; set; }
/// <summary>
/// Gets or sets the button cursor.
/// </summary>
/// <value>
/// The button cursor.
/// </value>
/// <remarks>
/// (Added in v2.2.0) Used to define what type of mouse cursor is displayed when hovering over the Flash button.
/// </remarks>
public Cursor ButtonCursor { get; set; }
/// <summary>
/// Gets or sets the button window mode.
/// </summary>
/// <value>
/// The button window mode.
/// </value>
/// <remarks>
/// (Added in v2.2.0) Sets the WMODE property of the Flash Movie. Valid values are available in the SWFUpload.WINDOW_MODE constants.
/// </remarks>
public WindowMode ButtonWindowMode { get; set; }
/// <summary>
/// Gets or sets the swfupload loaded handler.
/// </summary>
/// <value>
/// The swfupload loaded handler.
/// </value>
public string SwfUploadLoadedHandler { get; set; }
/// <summary>
/// Gets or sets the file dialog start handler.
/// </summary>
/// <value>
/// The file dialog start handler.
/// </value>
public string FileDialogStartHandler { get; set; }
/// <summary>
/// Gets or sets the file queued handler.
/// </summary>
/// <value>
/// The file queued handler.
/// </value>
public string FileQueuedHandler { get; set; }
/// <summary>
/// Gets or sets the file queue error handler.
/// </summary>
/// <value>
/// The file queue error handler.
/// </value>
public string FileQueueErrorHandler { get; set; }
/// <summary>
/// Gets or sets the file dialog complete handler.
/// </summary>
/// <value>
/// The file dialog complete handler.
/// </value>
public string FileDialogCompleteHandler { get; set; }
/// <summary>
/// Gets or sets the upload start handler.
/// </summary>
/// <value>
/// The upload start handler.
/// </value>
public string UploadStartHandler { get; set; }
/// <summary>
/// Gets or sets the upload progress handler.
/// </summary>
/// <value>
/// The upload progress handler.
/// </value>
public string UploadProgressHandler { get; set; }
/// <summary>
/// Gets or sets the upload error handler.
/// </summary>
/// <value>
/// The upload error handler.
/// </value>
public string UploadErrorHandler { get; set; }
/// <summary>
/// Gets or sets the upload success handler.
/// </summary>
/// <value>
/// The upload success handler.
/// </value>
public string UploadSuccessHandler { get; set; }
/// <summary>
/// Gets or sets the upload complete handler.
/// </summary>
/// <value>
/// The upload complete handler.
/// </value>
public string UploadCompleteHandler { get; set; }
/// <summary>
/// Gets or sets the debug handler.
/// </summary>
/// <value>
/// The debug handler.
/// </value>
public string DebugHandler { get; set; }
/// <summary>
/// Gets or sets the custom settings.
/// </summary>
/// <value>
/// The custom settings.
/// </value>
public object CustomSettings { get; set; }
#endregion
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// 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;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using Alachisoft.NCache.Config.Dom;
namespace Alachisoft.NCache.Config.Dom
{
public static class ConfigConverter
{
public static Hashtable ToHashtable(CacheServerConfig config)
{
return DomToHashtable.GetConfig(config);
}
public static Hashtable ToHashtable(CacheServerConfig[] configs)
{
return DomToHashtable.GetConfig(configs);
}
public static CacheServerConfig[] ToDom(Hashtable config)
{
return HashtableToDom.GetConfig(config);
}
static class HashtableToDom
{
public static CacheServerConfig[] GetConfig(Hashtable config)
{
CacheServerConfig[] caches = new CacheServerConfig[config.Count];
int i = 0;
foreach (Hashtable cache in config.Values)
caches[i++] = GetCacheConfiguration(CollectionsUtil.CreateCaseInsensitiveHashtable(cache));
return caches;
}
private static CacheServerConfig GetCacheConfiguration(Hashtable settings)
{
CacheServerConfig cache = new CacheServerConfig();
cache.Name = settings["id"].ToString();
if (settings.ContainsKey("web-cache"))
GetWebCache(cache, (Hashtable)settings["web-cache"]);
if (settings.ContainsKey("cache"))
GetCache(cache, (Hashtable)settings["cache"]);
return cache;
}
private static void GetCache(CacheServerConfig cache, Hashtable settings)
{
if (settings.ContainsKey("config-id"))
cache.ConfigID = Convert.ToDouble(settings["config-id"]);
if (settings.ContainsKey("last-modified"))
cache.LastModified = settings["last-modified"].ToString();
if (settings.ContainsKey("log"))
cache.Log = GetLog((Hashtable)settings["log"]);
if (settings.ContainsKey("cache-classes"))
GetCacheClasses(cache, (Hashtable)settings["cache-classes"]);
if (settings.ContainsKey("perf-counters"))
cache.PerfCounters = GetPerfCounters(settings);
}
private static PerfCounters GetPerfCounters(Hashtable settings)
{
PerfCounters perCounters = new PerfCounters();
perCounters.Enabled = Convert.ToBoolean(settings["perf-counters"]);
return perCounters;
}
private static ServerMapping GetServerMapping(Hashtable settings)
{
ServerMapping serverMapping = new ServerMapping();
if (settings.ContainsKey("server-end-point"))
serverMapping.MappingServers = GetMapping((Hashtable)settings["server-end-point"]);
return serverMapping;
}
private static Mapping[] GetMapping(Hashtable settings)
{
Mapping[] mapping = null;
if (settings.ContainsKey("end-point"))
mapping = settings["end-point"] as Mapping[];
return mapping;
}
private static void GetCacheClasses(CacheServerConfig cache, Hashtable settings)
{
if (settings.ContainsKey(cache.Name))
GetClassifiedCache(cache, (Hashtable)settings[cache.Name]);
}
private static void GetClassifiedCache(CacheServerConfig cache, Hashtable settings)
{
if (settings.ContainsKey("data-load-balancing"))
cache.AutoLoadBalancing = GetAutoLoadBalancing((Hashtable)settings["data-load-balancing"]);
if (settings.ContainsKey("cluster"))
cache.Cluster = GetCluster(settings);
if (settings.ContainsKey("internal-cache"))
GetInternalCache(cache, (Hashtable)settings["internal-cache"]);
else
GetInternalCache(cache, settings);
}
private static AutoLoadBalancing GetAutoLoadBalancing(Hashtable settings)
{
AutoLoadBalancing autoLoadBalancing = new AutoLoadBalancing();
if (settings.ContainsKey("enabled"))
autoLoadBalancing.Enabled = Convert.ToBoolean(settings["enabled"]);
if (settings.ContainsKey("auto-balancing-threshold"))
autoLoadBalancing.Threshold = Convert.ToInt32(settings["auto-balancing-threshold"]);
if (settings.ContainsKey("auto-balancing-interval"))
autoLoadBalancing.Interval = Convert.ToInt32(settings["auto-balancing-interval"]);
return autoLoadBalancing;
}
private static void GetInternalCache(CacheServerConfig cache, Hashtable settings)
{
if (settings.ContainsKey("indexes"))
cache.QueryIndices = GetIndexes((Hashtable)settings["indexes"]);
if (settings.ContainsKey("storage"))
cache.Storage = GetStorage((Hashtable)settings["storage"]);
if (settings.ContainsKey("scavenging-policy"))
cache.EvictionPolicy = GetEvictionPolicy((Hashtable)settings["scavenging-policy"]);
if (settings.ContainsKey("clean-interval"))
cache.Cleanup = GetCleanup(settings);
}
private static Cleanup GetCleanup(Hashtable settings)
{
Cleanup cleanup = new Cleanup();
cleanup.Interval = Convert.ToInt32(settings["clean-interval"]);
return cleanup;
}
private static EvictionPolicy GetEvictionPolicy(Hashtable settings)
{
EvictionPolicy evictionPolicy = new EvictionPolicy();
if (settings.ContainsKey("eviction-enabled"))
evictionPolicy.Enabled = Convert.ToBoolean(settings["eviction-enabled"]);
if (settings.ContainsKey("priority"))
evictionPolicy.DefaultPriority = ((Hashtable)settings["priority"])["default-value"].ToString();
if (settings.ContainsKey("class"))
evictionPolicy.Policy = settings["class"] as string;
if (settings.ContainsKey("evict-ratio"))
evictionPolicy.EvictionRatio = Convert.ToDecimal(settings["evict-ratio"]);
return evictionPolicy;
}
private static QueryIndex GetIndexes(Hashtable settings)
{
QueryIndex indexes = new QueryIndex();
if (settings.ContainsKey("index-classes"))
indexes.Classes = GetIndexClasses((Hashtable)settings["index-classes"]);
return indexes;
}
private static Class[] GetIndexClasses(Hashtable settings)
{
Class[] classes = new Class[settings.Count];
int i = 0;
foreach (Hashtable cls in settings.Values)
classes[i++] = GetIndexClass(cls);
return classes;
}
private static Class GetIndexClass(Hashtable settings)
{
Class cls = new Class();
if (settings.ContainsKey("id"))
cls.ID = settings["id"].ToString();
if (settings.ContainsKey("name"))
cls.Name = settings["name"].ToString();
if (settings.ContainsKey("attributes"))
cls.Attributes = GetIndexAttributes((Hashtable)settings["attributes"]);
return cls;
}
private static Attrib[] GetIndexAttributes(Hashtable settings)
{
Attrib[] attributes = new Attrib[settings.Count];
int i = 0;
foreach (Hashtable attrib in settings.Values)
attributes[i++] = GetIndexAttribute(attrib);
return attributes;
}
private static Attrib GetIndexAttribute(Hashtable settings)
{
Attrib attrib = new Attrib();
if (settings.ContainsKey("id"))
attrib.ID = settings["id"].ToString();
if (settings.ContainsKey("data-type"))
attrib.Type = settings["data-type"].ToString();
if (settings.ContainsKey("name"))
attrib.Name = settings["name"].ToString();
return attrib;
}
private static Storage GetStorage(Hashtable settings)
{
Storage storage = new Storage();
if (settings.ContainsKey("class"))
storage.Type = settings["class"].ToString();
if (settings.ContainsKey("heap"))
storage.Size = Convert.ToInt64(((Hashtable)settings["heap"])["max-size"]);
return storage;
}
private static Cluster GetCluster(Hashtable settings)
{
Cluster cluster = new Cluster();
if (settings.ContainsKey("type"))
{
cluster.Topology = settings["type"].ToString();
}
if (settings.ContainsKey("stats-repl-interval"))
cluster.StatsRepInterval = Convert.ToInt32(settings["stats-repl-interval"]);
if (settings.ContainsKey("op-timeout"))
cluster.OpTimeout = Convert.ToInt32(settings["op-timeout"]);
if (settings.ContainsKey("use-heart-beat"))
cluster.UseHeartbeat = Convert.ToBoolean(settings["use-heart-beat"]);
settings = (Hashtable)settings["cluster"];
if (settings.ContainsKey("channel"))
cluster.Channel = GetChannel((Hashtable)settings["channel"], 1);
return cluster;
}
private static Channel GetChannel(Hashtable settings, int defaultPortRange)
{
Channel channel = new Channel(defaultPortRange);
if (settings.ContainsKey("tcp"))
GetTcp(channel, (Hashtable)settings["tcp"]);
if (settings.ContainsKey("tcpping"))
GetTcpPing(channel, (Hashtable)settings["tcpping"]);
if (settings.ContainsKey("pbcast.gms"))
GetGMS(channel, (Hashtable)settings["pbcast.gms"]);
return channel;
}
private static void GetTcpPing(Channel channel, Hashtable settings)
{
if (settings.ContainsKey("initial_hosts"))
channel.InitialHosts = settings["initial_hosts"].ToString();
if (settings.ContainsKey("num_initial_members"))
channel.NumInitHosts = Convert.ToInt32(settings["num_initial_members"]);
if (settings.ContainsKey("port_range"))
channel.PortRange = Convert.ToInt32(settings["port_range"]);
}
private static void GetTcp(Channel channel, Hashtable settings)
{
if (settings.ContainsKey("start_port"))
channel.TcpPort = Convert.ToInt32(settings["start_port"]);
if (settings.ContainsKey("port_range"))
channel.PortRange = Convert.ToInt32(settings["port_range"]);
if (settings.ContainsKey("connection_retries"))
channel.ConnectionRetries = Convert.ToInt32(settings["connection_retries"]);
if (settings.ContainsKey("connection_retry_interval"))
channel.ConnectionRetryInterval = Convert.ToInt32(settings["connection_retry_interval"]);
}
private static void GetGMS(Channel channel, Hashtable settings)
{
if (settings.ContainsKey("join_retry_count"))
channel.JoinRetries = Convert.ToInt32(settings["join_retry_count"].ToString());
if (settings.ContainsKey("join_retry_timeout"))
channel.JoinRetryInterval = Convert.ToInt32(settings["join_retry_timeout"]);
}
private static Log GetLog(Hashtable settings)
{
Log log = new Log();
if (settings.ContainsKey("enabled"))
log.Enabled = Convert.ToBoolean(settings["enabled"]);
if (settings.ContainsKey("trace-errors"))
log.TraceErrors = Convert.ToBoolean(settings["trace-errors"]);
if (settings.ContainsKey("trace-notices"))
log.TraceNotices = Convert.ToBoolean(settings["trace-notices"]);
if (settings.ContainsKey("trace-debug"))
log.TraceDebug = Convert.ToBoolean(settings["trace-debug"]);
if (settings.ContainsKey("trace-warnings"))
log.TraceWarnings = Convert.ToBoolean(settings["trace-warnings"]);
if (settings.ContainsKey("log-path"))
log.LogPath = Convert.ToString(settings["log-path"]);
return log;
}
private static Parameter[] GetParameters(Hashtable settings)
{
if (settings == null) return null;
Parameter[] parameters = new Parameter[settings.Count];
int i = 0;
IDictionaryEnumerator ide = settings.GetEnumerator();
while (ide.MoveNext())
{
Parameter parameter = new Parameter();
parameter.Name = ide.Key as string;
parameter.ParamValue = ide.Value as string;
parameters[i] = parameter;
i++;
}
return parameters;
}
private static void GetWebCache(CacheServerConfig cache, Hashtable settings)
{
if (settings.ContainsKey("shared"))
cache.InProc = !Convert.ToBoolean(settings["shared"]);
}
}
static class DomToHashtable
{
public static Hashtable GetCacheConfiguration(CacheServerConfig cache)
{
Hashtable config = new Hashtable();
config.Add("type", "cache-configuration");
config.Add("id", cache.Name);
config.Add("cache", GetCache(cache));
config.Add("web-cache", GetWebCache(cache));
return config;
}
public static Hashtable GetWebCache(CacheServerConfig cache)
{
Hashtable settings = new Hashtable();
settings.Add("shared", (!cache.InProc).ToString().ToLower());
settings.Add("cache-id", cache.Name);
return settings;
}
public static Hashtable GetCache(CacheServerConfig cache)
{
Hashtable settings = new Hashtable();
settings.Add("name", cache.Name);
if (cache.Log != null)
settings.Add("log", GetLog(cache.Log));
settings.Add("config-id", cache.ConfigID);
if (cache.LastModified != null)
settings.Add("last-modified", cache.LastModified);
settings.Add("cache-classes", GetCacheClasses(cache));
settings.Add("class", cache.Name);
if (cache.PerfCounters != null)
settings.Add("perf-counters", cache.PerfCounters.Enabled);
return settings;
}
private static Hashtable GetParameters(Parameter[] parameters)
{
if (parameters == null)
return null;
Hashtable settings = new Hashtable();
for (int i = 0; i < parameters.Length; i++)
settings[parameters[i].Name] = parameters[i].ParamValue;
return settings;
}
private static Hashtable GetCacheClasses(CacheServerConfig cache)
{
Hashtable settings = new Hashtable();
settings.Add(cache.Name, GetClassifiedCache(cache));
return settings;
}
private static Hashtable GetClassifiedCache(CacheServerConfig cache)
{
Hashtable settings = new Hashtable();
settings.Add("id", cache.Name);
if (cache.AutoLoadBalancing != null)
{
settings.Add("data-load-balancing", GetAutoLoadBalancing(cache.AutoLoadBalancing));
}
if (cache.Cluster == null)
{
settings.Add("type", "local-cache");
GetInternalCache(settings, cache, true);
}
else
GetCluster(settings, cache);
return settings;
}
private static Hashtable GetAutoLoadBalancing(AutoLoadBalancing autoLoadBalancing)
{
Hashtable settings = new Hashtable();
settings.Add("enabled", autoLoadBalancing.Enabled);
settings.Add("auto-balancing-threshold", autoLoadBalancing.Threshold);
settings.Add("auto-balancing-interval", autoLoadBalancing.Interval);
return settings;
}
private static void GetInternalCache(Hashtable source, CacheServerConfig cache, bool localCache)
{
if (cache.QueryIndices != null)
source.Add("indexes", GetIndexes(cache.QueryIndices));
if (cache.Storage != null)
source.Add("storage", GetStorage(cache.Storage));
if (!localCache)
{
source.Add("type", "local-cache");
source.Add("id", "internal-cache");
}
if (cache.EvictionPolicy != null)
source.Add("scavenging-policy", GetEvictionPolicy(cache.EvictionPolicy));
if (cache.Cleanup != null)
source.Add("clean-interval", cache.Cleanup.Interval.ToString());
}
private static Hashtable GetEvictionPolicy(EvictionPolicy evictionPolicy)
{
Hashtable settings = new Hashtable();
settings.Add("class", evictionPolicy.Policy);
settings.Add("eviction-enabled", evictionPolicy.Enabled);
settings.Add("priority", GetEvictionPriority(evictionPolicy));
settings.Add("evict-ratio", evictionPolicy.EvictionRatio.ToString());
return settings;
}
private static Hashtable GetEvictionPriority(EvictionPolicy evictionPolicy)
{
Hashtable settings = new Hashtable();
settings.Add("default-value", evictionPolicy.DefaultPriority);
return settings;
}
private static Hashtable GetStorage(Storage storage)
{
Hashtable settings = new Hashtable();
settings.Add("class", storage.Type);
if (storage.Type == "heap")
settings.Add("heap", GetHeap(storage));
return settings;
}
private static Hashtable GetHeap(Storage storage)
{
Hashtable settings = new Hashtable();
settings.Add("max-size", storage.Size.ToString());
return settings;
}
private static Hashtable GetIndexes(QueryIndex indexes)
{
Hashtable settings = new Hashtable();
if (indexes.Classes != null)
settings.Add("index-classes", GetIndexClasses(indexes.Classes));
return settings;
}
private static Hashtable GetIndexClasses(Class[] classes)
{
Hashtable settings = new Hashtable();
foreach (Class cls in classes)
settings.Add(cls.ID, GetIndexClass(cls));
return settings;
}
private static Hashtable GetIndexClass(Class cls)
{
Hashtable settings = new Hashtable();
settings.Add("name", cls.Name);
settings.Add("type", "class");
settings.Add("id", cls.ID);
if (cls.Attributes != null)
settings.Add("attributes", GetIndexAttributes(cls.Attributes));
return settings;
}
private static Hashtable GetIndexAttributes(Attrib[] attributes)
{
Hashtable settings = new Hashtable();
foreach (Attrib attrib in attributes)
settings.Add(attrib.ID, GetIndexAttribute(attrib));
return settings;
}
private static Hashtable GetIndexAttribute(Attrib attrib)
{
Hashtable settings = new Hashtable();
settings.Add("name", attrib.Name);
settings.Add("data-type", attrib.Type);
settings.Add("type", "attrib");
settings.Add("id", attrib.ID);
return settings;
}
private static void GetCluster(Hashtable settings, CacheServerConfig cache)
{
settings.Add("type", cache.Cluster.Topology);
settings.Add("stats-repl-interval", cache.Cluster.StatsRepInterval.ToString());
settings.Add("op-timeout", cache.Cluster.OpTimeout.ToString());
settings.Add("use-heart-beat", cache.Cluster.UseHeartbeat.ToString().ToLower());
if (cache.Cleanup != null)
settings.Add("clean-interval", cache.Cleanup.Interval.ToString());
settings.Add("internal-cache", new Hashtable());
GetInternalCache((Hashtable)settings["internal-cache"], cache, false);
Hashtable cluster = new Hashtable();
cluster.Add("group-id", cache.Name);
cluster.Add("class", "tcp");
cluster.Add("channel", GetChannel(cache.Cluster.Channel, cache.Cluster.UseHeartbeat));
settings.Add("cluster", cluster);
}
private static Hashtable GetServerMapping(ServerMapping serverMapping)
{
Hashtable settings = new Hashtable();
if (serverMapping.MappingServers != null && serverMapping.MappingServers.Length > 0)
{
foreach (Mapping mapping in serverMapping.MappingServers)
settings.Add(mapping.PrivateIP, GetMapping(mapping));
}
return settings;
}
private static Hashtable GetMapping(Mapping mapping)
{
Hashtable settings = new Hashtable();
if (mapping != null)
{
settings.Add("private-ip", mapping.PrivateIP.ToString());
settings.Add("private-port", mapping.PrivatePort.ToString());
settings.Add("public-ip", mapping.PublicIP.ToString());
settings.Add("public-port", mapping.PublicPort.ToString());
}
return settings;
}
private static Hashtable GetMappings(Mapping[] mappings)
{
Hashtable settings = new Hashtable();
return settings;
}
private static Hashtable GetChannel(Channel channel, bool useHeartBeat)
{
Hashtable settings = new Hashtable();
settings.Add("tcp", GetTcp(channel, useHeartBeat));
settings.Add("tcpping", GetTcpPing(channel));
settings.Add("pbcast.gms", GetGMS(channel));
return settings;
}
private static Hashtable GetTcpPing(Channel channel)
{
Hashtable settings = new Hashtable();
settings.Add("initial_hosts", channel.InitialHosts.ToString());
settings.Add("num_initial_members", channel.NumInitHosts.ToString());
settings.Add("port_range", channel.PortRange.ToString());
return settings;
}
private static Hashtable GetTcp(Channel channel, bool useHeartBeat)
{
Hashtable settings = new Hashtable();
settings.Add("start_port", channel.TcpPort.ToString());
settings.Add("port_range", channel.PortRange.ToString());
settings.Add("connection_retries", channel.ConnectionRetries);
settings.Add("connection_retry_interval", channel.ConnectionRetryInterval);
settings.Add("use_heart_beat", useHeartBeat);
return settings;
}
private static Hashtable GetGMS(Channel channel)
{
Hashtable settings = new Hashtable();
settings.Add("join_retry_count", channel.JoinRetries.ToString());
settings.Add("join_retry_timeout", channel.JoinRetryInterval.ToString());
return settings;
}
private static Hashtable GetLog(Log log)
{
Hashtable settings = new Hashtable();
settings.Add("enabled", log.Enabled.ToString().ToLower());
settings.Add("trace-errors", log.TraceErrors.ToString().ToLower());
settings.Add("trace-notices", log.TraceNotices.ToString().ToLower());
settings.Add("trace-debug", log.TraceDebug.ToString().ToLower());
settings.Add("trace-warnings", log.TraceWarnings.ToString().ToLower());
settings.Add("log-path", log.LogPath.ToLower());
return settings;
}
public static Hashtable GetConfig(CacheServerConfig cache)
{
return GetCacheConfiguration(cache);
}
public static Hashtable GetConfig(CacheServerConfig[] caches)
{
Hashtable settings = new Hashtable();
foreach (CacheServerConfig cache in caches)
settings.Add(cache.Name, GetCacheConfiguration(cache));
return settings;
}
}
}
}
| |
/*
* 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 log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Connectors;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RemoteXInventoryServicesConnector")]
public class RemoteXInventoryServicesConnector : ISharedRegionModule, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled;
private XInventoryServicesConnector m_RemoteConnector;
private IUserManagement m_UserManager;
public RemoteXInventoryServicesConnector()
{
}
public RemoteXInventoryServicesConnector(string url)
{
m_RemoteConnector = new XInventoryServicesConnector(url);
}
public RemoteXInventoryServicesConnector(IConfigSource source)
{
Init(source);
}
public string Name
{
get { return "RemoteXInventoryServicesConnector"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
/// <summary>
/// Scene used by this module. This currently needs to be publicly settable for HGInventoryBroker.
/// </summary>
public Scene Scene { get; set; }
public IUserManagement UserManager
{
get
{
if (m_UserManager == null)
{
m_UserManager = Scene.RequestModuleInterface<IUserManagement>();
if (m_UserManager == null)
m_log.ErrorFormat(
"[XINVENTORY CONNECTOR]: Could not retrieve IUserManagement module from {0}",
Scene.RegionInfo.RegionName);
}
return m_UserManager;
}
}
protected void Init(IConfigSource source)
{
m_RemoteConnector = new XInventoryServicesConnector(source);
}
#region ISharedRegionModule
public void AddRegion(Scene scene)
{
// m_Scene = scene;
//m_log.Debug("[XXXX] Adding scene " + m_Scene.RegionInfo.RegionName);
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IInventoryService>(this);
if (Scene == null)
Scene = scene;
}
public void Close()
{
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryServices", "");
if (name == Name)
{
Init(source);
m_Enabled = true;
m_log.Info("[XINVENTORY CONNECTOR]: Remote XInventory enabled");
}
}
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
m_log.InfoFormat("[XINVENTORY CONNECTOR]: Enabled remote XInventory for region {0}", scene.RegionInfo.RegionName);
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
}
#endregion ISharedRegionModule
#region IInventoryService
public bool AddFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
return m_RemoteConnector.AddFolder(folder);
}
public bool AddItem(InventoryItemBase item)
{
if (item == null)
return false;
return m_RemoteConnector.AddItem(item);
}
public bool CreateUserInventory(UUID user)
{
return false;
}
public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
if (folderIDs == null)
return false;
if (folderIDs.Count == 0)
return false;
return m_RemoteConnector.DeleteFolders(ownerID, folderIDs);
}
public bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{
if (itemIDs == null)
return false;
if (itemIDs.Count == 0)
return true;
return m_RemoteConnector.DeleteItems(ownerID, itemIDs);
}
public List<InventoryItemBase> GetActiveGestures(UUID userId)
{
return new List<InventoryItemBase>();
}
public InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
//m_log.DebugFormat("[XINVENTORY CONNECTOR]: GetFolder {0}", folder.ID);
if (folder == null)
return null;
return m_RemoteConnector.GetFolder(folder);
}
public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
InventoryCollection invCol = m_RemoteConnector.GetFolderContent(userID, folderID);
// Commenting this for now, because it's causing more grief than good
//if (invCol != null && UserManager != null)
//{
// // Protect ourselves against the caller subsequently modifying the items list
// List<InventoryItemBase> items = new List<InventoryItemBase>(invCol.Items);
// if (items != null && items.Count > 0)
// //Util.FireAndForget(delegate
// //{
// foreach (InventoryItemBase item in items)
// if (!string.IsNullOrEmpty(item.CreatorData))
// UserManager.AddUser(item.CreatorIdAsUuid, item.CreatorData);
// //});
//}
return invCol;
}
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{
return m_RemoteConnector.GetFolderForType(userID, type);
}
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{
return m_RemoteConnector.GetFolderItems(userID, folderID);
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID userId)
{
return m_RemoteConnector.GetInventorySkeleton(userId);
}
public InventoryItemBase GetItem(InventoryItemBase item)
{
//m_log.DebugFormat("[XINVENTORY CONNECTOR]: GetItem {0}", item.ID);
if (item == null)
return null;
if (m_RemoteConnector == null)
m_log.DebugFormat("[XINVENTORY CONNECTOR]: connector stub is null!!!");
return m_RemoteConnector.GetItem(item);
}
public InventoryFolderBase GetRootFolder(UUID userID)
{
return m_RemoteConnector.GetRootFolder(userID);
}
public bool HasInventoryForUser(UUID userID)
{
return false;
}
public bool MoveFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
return m_RemoteConnector.MoveFolder(folder);
}
public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
if (items == null)
return false;
return m_RemoteConnector.MoveItems(ownerID, items);
}
public bool PurgeFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
return m_RemoteConnector.PurgeFolder(folder);
}
public bool UpdateFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
return m_RemoteConnector.UpdateFolder(folder);
}
public bool UpdateItem(InventoryItemBase item)
{
if (item == null)
return false;
return m_RemoteConnector.UpdateItem(item);
}
#endregion IInventoryService
}
}
| |
using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Diagnostics;
using System.Xml;
using SharpVectors.Dom.Svg;
using SharpVectors.Dom.Css;
using System.Runtime.InteropServices;
namespace SharpVectors.Renderer.Gdi
{
/// <summary>
/// Summary description for PaintServer.
/// </summary>
public class GradientPaintServer : PaintServer
{
public GradientPaintServer(SvgGradientElement gradientElement)
{
_gradientElement = gradientElement;
}
private SvgGradientElement _gradientElement;
#region Private methods
private ArrayList getColors(XmlNodeList stops)
{
ArrayList colors = new ArrayList(stops.Count);
for(int i = 0; i<stops.Count; i++)
{
SvgStopElement stop = (SvgStopElement) stops.Item(i);
string prop = stop.GetPropertyValue("stop-color");
GdiSvgColor svgColor = new GdiSvgColor(stop, "stop-color");
colors.Add(svgColor.Color);
}
return colors;
}
private ArrayList getPositions(XmlNodeList stops)
{
ArrayList positions = new ArrayList(stops.Count);
float lastPos = 0;
for(int i = 0; i<stops.Count; i++)
{
SvgStopElement stop = (SvgStopElement) stops.Item(i);
float pos = (float)stop.Offset.AnimVal;
pos /= 100;
pos = Math.Max(lastPos, pos);
positions.Add(pos);
lastPos = pos;
}
return positions;
}
private void correctPositions(ArrayList positions, ArrayList colors)
{
if(positions.Count > 0 )
{
float firstPos = (float)positions[0];
if(firstPos > 0F)
{
positions.Insert(0, 0F);
colors.Insert(0, colors[0]);
}
float lastPos = (float)positions[positions.Count - 1];
if(lastPos < 1F)
{
positions.Add(1F);
colors.Add(colors[colors.Count - 1]);
}
}
}
private void getColorsAndPositions(XmlNodeList stops, ref float[] positions, ref Color[] colors)
{
ArrayList alColors = getColors(stops);
ArrayList alPositions = getPositions(stops);
if(alPositions.Count > 0)
{
correctPositions(alPositions, alColors);
colors = (Color[])alColors.ToArray(typeof(Color));
positions = (float[])alPositions.ToArray(typeof(float));
}
else
{
colors = new Color[2];
colors[0] = Color.Black;
colors[1] = Color.Black;
positions = new float[2];
positions[0] = 0;
positions[1] = 1;
}
}
private LinearGradientBrush GetLinearGradientBrush(SvgLinearGradientElement res,RectangleF bounds)
{
float fLeft = (float)res.X1.AnimVal.Value;
float fRight = (float)res.X2.AnimVal.Value;
float fTop = (float)res.Y1.AnimVal.Value;
float fBottom = (float)res.Y2.AnimVal.Value;
bool bForceUserSpaceOnUse = (fLeft > 1 || fRight > 1 || fTop > 1 || fBottom > 1);
float fEffectiveLeft = fLeft;
float fEffectiveRight = fRight;
float fEffectiveTop = fTop;
float fEffectiveBottom = fBottom;
if(res.GradientUnits.AnimVal.Equals((ushort)SvgUnitType.ObjectBoundingBox) && !bForceUserSpaceOnUse)
{
if(res.SpreadMethod.AnimVal.Equals((ushort)SvgSpreadMethod.Pad))
{
fEffectiveRight = bounds.Right;
fEffectiveLeft = bounds.Left;
}
else
{
fEffectiveLeft = bounds.Left + fLeft * (bounds.Width);
fEffectiveRight = bounds.Left + fRight * (bounds.Width);
}
fEffectiveTop = bounds.Top + fTop * (bounds.Height);
fEffectiveBottom = bounds.Top + fBottom * (bounds.Height);
}
LinearGradientMode mode;
if(fTop == fBottom)
mode = LinearGradientMode.Horizontal;
else
{
if(fLeft == fRight)
mode = LinearGradientMode.Vertical;
else
{
if(fLeft < fRight)
mode = LinearGradientMode.ForwardDiagonal;
else
mode = LinearGradientMode.BackwardDiagonal;
}
}
float fEffectiveWidth = fEffectiveRight - fEffectiveLeft;
if(fEffectiveWidth <= 0)
fEffectiveWidth = bounds.Width;
float fEffectiveHeight = fEffectiveBottom - fEffectiveTop;
if(fEffectiveHeight <= 0)
fEffectiveHeight = bounds.Height;
LinearGradientBrush brush = new LinearGradientBrush(new RectangleF(fEffectiveLeft-1, fEffectiveTop-1, fEffectiveWidth+2, fEffectiveHeight+2), Color.White, Color.White, mode);
XmlNodeList stops = res.Stops;
ColorBlend cb = new ColorBlend();
Color[] adjcolors = null;
float[] adjpositions = null;
getColorsAndPositions(stops, ref adjpositions, ref adjcolors);
if(res.GradientUnits.AnimVal.Equals((ushort)SvgUnitType.ObjectBoundingBox) && !bForceUserSpaceOnUse)
{
if(res.SpreadMethod.AnimVal.Equals((ushort)SvgSpreadMethod.Pad))
{
for(int i=0;i<adjpositions.Length;i++)
{
if(fLeft == fRight)
adjpositions[i] = fTop + adjpositions[i] * (fBottom - fTop);
else
adjpositions[i] = fLeft + adjpositions[i] * (fRight - fLeft);
}
// this code corrects the values again... fix
int nSize = adjcolors.Length;
if(adjpositions[0] > 0.0)
++nSize;
if(adjpositions[adjcolors.Length-1] < 1)
++nSize;
Color [] readjcolors = new Color[nSize];
float [] readjpositions = new float[nSize];
if(adjpositions[0] > 0.0)
{
adjpositions.CopyTo(readjpositions,1);
adjcolors.CopyTo(readjcolors,1);
readjcolors[0] = readjcolors[1];
readjpositions[0] = 0;
}
else
{
adjpositions.CopyTo(readjpositions,0);
adjcolors.CopyTo(readjcolors,0);
}
if(adjpositions[adjcolors.Length-1] < 1)
{
readjcolors[nSize-1] = readjcolors[nSize-2];
readjpositions[nSize-1] = 1;
}
cb.Colors = readjcolors;
cb.Positions = readjpositions;
}
else
{
cb.Colors = adjcolors;
cb.Positions = adjpositions;
}
}
else
{
cb.Colors = adjcolors;
cb.Positions = adjpositions;
}
brush.InterpolationColors = cb;
if(res.SpreadMethod.AnimVal.Equals((ushort)SvgSpreadMethod.Reflect))
{
brush.WrapMode = WrapMode.TileFlipXY;
}
else if(res.SpreadMethod.AnimVal.Equals((ushort)SvgSpreadMethod.Repeat))
{
brush.WrapMode = WrapMode.Tile;
}
else if(res.SpreadMethod.AnimVal.Equals((ushort)SvgSpreadMethod.Pad))
{
brush.WrapMode = WrapMode.Tile;
}
brush.Transform = getTransformMatrix(res);
if(res.GetPropertyValue("color-interpolation")=="linearRGB")
{
brush.GammaCorrection = true;
}
else
{
brush.GammaCorrection = false;
}
return brush;
}
private Matrix getTransformMatrix(SvgGradientElement gradientElement)
{
SvgMatrix svgMatrix = ((SvgTransformList)gradientElement.GradientTransform.AnimVal).TotalMatrix;
Matrix transformMatrix = new Matrix(
(float) svgMatrix.A,
(float) svgMatrix.B,
(float) svgMatrix.C,
(float) svgMatrix.D,
(float) svgMatrix.E,
(float) svgMatrix.F);
return transformMatrix;
}
private PathGradientBrush GetRadialGradientBrush(SvgRadialGradientElement res,RectangleF bounds)
{
float fCenterX = (float)res.Cx.AnimVal.Value;
float fCenterY = (float)res.Cy.AnimVal.Value;
float fFocusX = (float)res.Fx.AnimVal.Value;
float fFocusY = (float)res.Fy.AnimVal.Value;
float fRadius = (float)res.R.AnimVal.Value;
float fEffectiveCX = fCenterX;
float fEffectiveCY = fCenterY;
float fEffectiveFX = fFocusX;
float fEffectiveFY = fFocusY;
float fEffectiveRadiusX = fRadius;
float fEffectiveRadiusY = fRadius;
if(res.GradientUnits.AnimVal.Equals(SvgUnitType.ObjectBoundingBox))
{
fEffectiveCX = bounds.Left + fCenterX * (bounds.Width);
fEffectiveCY = bounds.Top + fCenterY * (bounds.Height);
fEffectiveFX = bounds.Left + fFocusX * (bounds.Width);
fEffectiveFY = bounds.Top + fFocusY * (bounds.Height);
fEffectiveRadiusX = fRadius * bounds.Width;
fEffectiveRadiusY = fRadius * bounds.Height;
}
GraphicsPath gp = new GraphicsPath();
gp.AddEllipse(fEffectiveCX - fEffectiveRadiusX,fEffectiveCY - fEffectiveRadiusY,2 * fEffectiveRadiusX, 2 * fEffectiveRadiusY);
PathGradientBrush brush = new PathGradientBrush(gp);
brush.CenterPoint = new PointF(fEffectiveFX,fEffectiveFY);
XmlNodeList stops = res.Stops;
ColorBlend cb = new ColorBlend();
Color[] adjcolors = null;
float[] adjpositions = null;
getColorsAndPositions(stops, ref adjpositions, ref adjcolors);
// Need to invert the colors for some bizarre reason
Array.Reverse(adjcolors);
Array.Reverse(adjpositions);
for(int i = 0; i<adjpositions.Length; i++)
{
adjpositions[i] = 1 - adjpositions[i];
}
cb.Colors = adjcolors;
cb.Positions = adjpositions;
brush.InterpolationColors = cb;
// ISvgTransformable transElm = (ISvgTransformable)res;
// SvgTransformList svgTList = (SvgTransformList)transElm.transform.AnimVal;
// brush.Transform = svgTList.matrix.matrix;
if(res.GetPropertyValue("color-interpolation")=="linearRGB")
{
//GdipSetPathGradientGammaCorrection(brush, true);
}
else
{
//GdipSetPathGradientGammaCorrection(brush, false);
}
/*
* How to do brush.GammaCorrection = true on a PathGradientBrush? / nikgus
* */
return brush;
}
#endregion
#region Public methods
public Region GetRadialGradientRegion(RectangleF bounds)
{
SvgRadialGradientElement res = _gradientElement as SvgRadialGradientElement;
if(_gradientElement == null)
{
return null;
}
float fCenterX = (float)res.Cx.AnimVal.Value;
float fCenterY = (float)res.Cy.AnimVal.Value;
float fFocusX = (float)res.Fx.AnimVal.Value;
float fFocusY = (float)res.Fy.AnimVal.Value;
float fRadius = (float)res.R.AnimVal.Value;
float fEffectiveCX = fCenterX;
float fEffectiveCY = fCenterY;
float fEffectiveFX = fFocusX;
float fEffectiveFY = fFocusY;
float fEffectiveRadiusX = fRadius;
float fEffectiveRadiusY = fRadius;
if(res.GradientUnits.AnimVal.Equals(SvgUnitType.ObjectBoundingBox))
{
fEffectiveCX = bounds.Left + fCenterX * (bounds.Width);
fEffectiveCY = bounds.Top + fCenterY * (bounds.Height);
fEffectiveFX = bounds.Left + fFocusX * (bounds.Width);
fEffectiveFY = bounds.Top + fFocusY * (bounds.Height);
fEffectiveRadiusX = fRadius * bounds.Width;
fEffectiveRadiusY = fRadius * bounds.Height;
}
GraphicsPath gp2 = new GraphicsPath();
gp2.AddEllipse(fEffectiveCX - fEffectiveRadiusX,fEffectiveCY - fEffectiveRadiusY,2 * fEffectiveRadiusX, 2 * fEffectiveRadiusY);
return new Region(gp2);
}
public override Brush GetBrush(RectangleF bounds)
{
if(_gradientElement is SvgLinearGradientElement)
{
return GetLinearGradientBrush((SvgLinearGradientElement)_gradientElement,bounds);
}
else if(_gradientElement is SvgRadialGradientElement)
{
return GetRadialGradientBrush((SvgRadialGradientElement)_gradientElement,bounds);
}
else
{
return new SolidBrush(Color.Black);
}
}
[DllImport("gdiplus.dll")]
static internal extern int GdipSetPathGradientGammaCorrection (IntPtr brush, bool gamma);
#endregion
}
}
| |
using Terraria;
using Terraria.ModLoader;
namespace ExampleMod.NPCs
{
//imported from my tAPI mod because I'm lazy
public abstract class Fish : ModNPC
{
protected float speed = 7f;
protected float speedY = 4f;
protected float acceleration = 0.25f;
protected float accelerationY = 0.2f;
protected float correction = 0.95f;
protected bool targetDryPlayer = true;
protected float idleSpeed = 2f;
protected bool bounces = true;
public override void AI()
{
if (npc.direction == 0)
{
npc.TargetClosest(true);
}
if (npc.wet)
{
bool flag30 = false;
npc.TargetClosest(false);
if (Main.player[npc.target].wet && !Main.player[npc.target].dead)
{
flag30 = true;
}
if (!flag30)
{
if (npc.collideX)
{
npc.velocity.X *= -1f;
npc.direction *= -1;
npc.netUpdate = true;
}
if (npc.collideY)
{
npc.netUpdate = true;
if (npc.velocity.Y > 0f)
{
npc.velocity.Y = -npc.velocity.Y;
npc.directionY = -1;
npc.ai[0] = -1f;
}
else if (npc.velocity.Y < 0f)
{
npc.velocity.Y = -npc.velocity.Y;
npc.directionY = 1;
npc.ai[0] = 1f;
}
}
}
if (flag30)
{
npc.TargetClosest(true);
if (npc.velocity.X * npc.direction < 0f)
{
npc.velocity.X *= correction;
}
npc.velocity.X += npc.direction * acceleration;
npc.velocity.Y += npc.directionY * accelerationY;
if (npc.velocity.X > speed)
{
npc.velocity.X = speed;
}
if (npc.velocity.X < -speed)
{
npc.velocity.X = -speed;
}
if (npc.velocity.Y > speedY)
{
npc.velocity.Y = speedY;
}
if (npc.velocity.Y < -speedY)
{
npc.velocity.Y = -speedY;
}
}
else
{
if (targetDryPlayer)
{
if (Main.player[npc.target].position.Y > npc.position.Y)
{
npc.directionY = 1;
}
else
{
npc.directionY = -1;
}
npc.velocity.X += (float)npc.direction * 0.1f * idleSpeed;
if (npc.velocity.X < -idleSpeed || npc.velocity.X > idleSpeed)
{
npc.velocity.X *= 0.95f;
}
if (npc.ai[0] == -1f)
{
float num356 = -0.3f * idleSpeed;
if (npc.directionY < 0)
{
num356 = -0.5f * idleSpeed;
}
if (npc.directionY > 0)
{
num356 = -0.1f * idleSpeed;
}
npc.velocity.Y -= 0.01f * idleSpeed;
if (npc.velocity.Y < num356)
{
npc.ai[0] = 1f;
}
}
else
{
float num357 = 0.3f * idleSpeed;
if (npc.directionY < 0)
{
num357 = 0.1f * idleSpeed;
}
if (npc.directionY > 0)
{
num357 = 0.5f * idleSpeed;
}
npc.velocity.Y += 0.01f * idleSpeed;
if (npc.velocity.Y > num357)
{
npc.ai[0] = -1f;
}
}
}
else
{
npc.velocity.X += (float)npc.direction * 0.1f * idleSpeed;
if (npc.velocity.X < -idleSpeed || npc.velocity.X > idleSpeed)
{
npc.velocity.X *= 0.95f;
}
if (npc.ai[0] == -1f)
{
npc.velocity.Y -= 0.01f * idleSpeed;
if ((double)npc.velocity.Y < -0.3)
{
npc.ai[0] = 1f;
}
}
else
{
npc.velocity.Y += 0.01f * idleSpeed;
if ((double)npc.velocity.Y > 0.3)
{
npc.ai[0] = -1f;
}
}
}
int num358 = (int)(npc.position.X + (float)(npc.width / 2)) / 16;
int num359 = (int)(npc.position.Y + (float)(npc.height / 2)) / 16;
if (Main.tile[num358, num359 - 1] == null)
{
Main.tile[num358, num359 - 1] = new Tile();
}
if (Main.tile[num358, num359 + 1] == null)
{
Main.tile[num358, num359 + 1] = new Tile();
}
if (Main.tile[num358, num359 + 2] == null)
{
Main.tile[num358, num359 + 2] = new Tile();
}
if (Main.tile[num358, num359 - 1].liquid > 128)
{
if (Main.tile[num358, num359 + 1].active())
{
npc.ai[0] = -1f;
}
else if (Main.tile[num358, num359 + 2].active())
{
npc.ai[0] = -1f;
}
}
if (!targetDryPlayer && ((double)npc.velocity.Y > 0.4 || (double)npc.velocity.Y < -0.4))
{
npc.velocity.Y *= 0.95f;
}
}
}
else
{
if (npc.velocity.Y == 0f)
{
if (!bounces)
{
npc.velocity.X *= 0.94f;
if ((double)npc.velocity.X > -0.2 && (double)npc.velocity.X < 0.2)
{
npc.velocity.X = 0f;
}
}
else if (Main.netMode != 1)
{
npc.velocity.Y = (float)Main.rand.Next(-50, -20) * 0.1f;
npc.velocity.X = (float)Main.rand.Next(-20, 20) * 0.1f;
npc.netUpdate = true;
}
}
npc.velocity.Y += 0.3f;
if (npc.velocity.Y > 10f)
{
npc.velocity.Y = 10f;
}
npc.ai[0] = 1f;
}
npc.rotation = npc.velocity.Y * (float)npc.direction * 0.1f;
if ((double)npc.rotation < -0.2)
{
npc.rotation = -0.2f;
}
if ((double)npc.rotation > 0.2)
{
npc.rotation = 0.2f;
}
}
public override void FindFrame(int frameHeight)
{
npc.spriteDirection = npc.direction;
npc.frameCounter += 1.0;
if (npc.wet)
{
npc.frameCounter %= 24.0;
npc.frame.Y = frameHeight * (int)(npc.frameCounter / 6.0);
}
else
{
npc.frameCounter %= 12.0;
if (npc.frameCounter < 6.0)
{
npc.frame.Y = frameHeight * 4;
}
else
{
npc.frame.Y = frameHeight * 5;
}
}
}
}
}
| |
// 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.Globalization;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.IO;
using System.Xml.XmlDiff;
using Microsoft.Test.ModuleCore;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeBuilderTests : XLinqTestCase
{
//[TestCase(Name = "NewLineHandling", Param = "XNodeBuilder")]
public partial class TCEOFHandling : BridgeHelpers
{
private XmlDiff _diff = null;
public TCEOFHandling()
{
_diff = new XmlDiff();
}
private string ExpectedOutput(string input, NewLineHandling h, bool attr)
{
string output = new string(input.ToCharArray());
switch (h)
{
case NewLineHandling.Entitize:
output = output.Replace("\r", "
");
if (attr)
{
output = output.Replace("\n", "
");
output = output.Replace("\t", "	");
}
break;
case NewLineHandling.Replace:
if (!attr)
{
output = output.Replace("\r\n", "\n");
output = output.Replace("\r", "\n");
output = output.Replace("\n", "\r\n");
}
else
{
output = output.Replace("\r", "
");
output = output.Replace("\n", "
");
output = output.Replace("\t", "	");
}
break;
default:
break;
}
return output;
}
//[Variation(Desc = "NewLineHandling Default value - NewLineHandling.Replace", Id = 1, Priority = 0)]
public void EOF_Handling_01()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
TestLog.Compare(wSettings.NewLineHandling, NewLineHandling.Replace, "Incorrect default value for XmlWriterSettings.NewLineHandling");
XDocument d = new XDocument();
XmlWriter w = CreateWriter(d);
w.Dispose();
TestLog.Compare(w.Settings.NewLineHandling, NewLineHandling.Replace, "Incorrect default value for XmlWriter.Settings.NewLineHandling");
}
//[Variation(Desc = "XmlWriter creation with NewLineHandling.Entitize", Param = NewLineHandling.Entitize, Id = 2, Priority = 0)]
//[Variation(Desc = "XmlWriter creation with NewLineHandling.Replace", Param = NewLineHandling.Replace, Id = 3, Priority = 0)]
//[Variation(Desc = "XmlWriter creation with NewLineHandling.None", Param = NewLineHandling.None, Id = 4, Priority = 0)]
public void EOF_Handling_02()
{
XmlWriterSettings wSettings = new XmlWriterSettings();
XDocument d = new XDocument();
XmlWriter w = CreateWriter(d);
TestLog.Compare(w != null, "XmlWriter creation failed");
TestLog.Compare(w.Settings.NewLineHandling, NewLineHandling.Replace, "Invalid NewLineHandling assignment");
w.Dispose();
}
//[Variation(Desc = "Check for tab character in element with 'Entitize'", Param = NewLineHandling.Entitize, Id = 14, Priority = 0)]
//[Variation(Desc = "Check for tab character in element with 'Replace'", Param = NewLineHandling.Replace, Id = 15, Priority = 0)]
//[Variation(Desc = "Check for tab character in element with 'None'", Param = NewLineHandling.None, Id = 16, Priority = 0)]
public void EOF_Handling_06()
{
string Tabs = "foo\tbar	foo\n\tbar\t\n\t";
XDocument d = new XDocument();
XmlWriter w = CreateWriter(d);
w.WriteStartElement("root");
w.WriteString("foo\tbar");
w.WriteCharEntity('\t');
w.WriteString("foo\n\tbar\t\n\t");
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d, "<root>" + ExpectedOutput(Tabs, (NewLineHandling)Variation.Param, false) + "</root>"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Desc = "Check for combinations of NewLine characters in attribute with 'Entitize'", Param = NewLineHandling.Entitize, Id = 17, Priority = 0)]
//[Variation(Desc = "Check for combinations of NewLine characters in attribute with 'Replace'", Param = NewLineHandling.Replace, Id = 18, Priority = 0)]
//[Variation(Desc = "Check for combinations of NewLine characters in attribute with 'None'", Param = NewLineHandling.None, Id = 19, Priority = 0)]
public void EOF_Handling_07()
{
string NewLineCombinations = "\r \n \r\n \n\r \r\r \n\n \r\n\r \n\r\n";
XDocument d = new XDocument();
XmlWriter w = CreateWriter(d);
w.WriteStartElement("root");
w.WriteAttributeString("foo", NewLineCombinations);
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d, "<root foo=\"" + ExpectedOutput(NewLineCombinations, (NewLineHandling)Variation.Param, true) + "\" />"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Desc = "Check for combinations of entities in attribute with 'Entitize'", Param = NewLineHandling.Entitize, Id = 20, Priority = 0)]
//[Variation(Desc = "Check for combinations of entities in attribute with 'Replace'", Param = NewLineHandling.Replace, Id = 21, Priority = 0)]
//[Variation(Desc = "Check for combinations of entities in attribute with 'None'", Param = NewLineHandling.None, Id = 22, Priority = 0)]
public void EOF_Handling_08()
{
string NewLineCombinations = "\r \n \r\n \n\r \r\r \n\n \r\n\r \n\r\n";
string NewLineEntities = "
 
 
 

 

 

 

 

";
XDocument d = new XDocument();
XmlWriter w = CreateWriter(d);
w.WriteStartElement("root");
w.WriteStartAttribute("foo");
for (int i = 0; i < NewLineCombinations.Length; i++)
{
if (NewLineCombinations[i] == ' ') w.WriteString(" ");
else w.WriteCharEntity(NewLineCombinations[i]);
}
w.WriteEndAttribute();
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d, "<root foo=\"" + ExpectedOutput(NewLineEntities, (NewLineHandling)Variation.Param, true) + "\" />"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Desc = "Check for combinations of NewLine characters and entities in element with 'Entitize'", Param = NewLineHandling.Entitize, Id = 23, Priority = 0)]
//[Variation(Desc = "Check for combinations of NewLine characters and entities in element with 'Replace'", Param = NewLineHandling.Replace, Id = 24, Priority = 0)]
//[Variation(Desc = "Check for combinations of NewLine characters and entities in element with 'None'", Param = NewLineHandling.None, Id = 25, Priority = 0)]
public void EOF_Handling_09()
{
string NewLines = "\r
 
\n 
\r 
\n \n
 
\r";
XDocument d = new XDocument();
XmlWriter w = CreateWriter(d);
w.WriteStartElement("root");
w.WriteStartAttribute("foo");
// '\r
 '
w.WriteString("\r");
w.WriteCharEntity('\n');
w.WriteString(" ");
// '
\n '
w.WriteCharEntity('\r');
w.WriteString("\n ");
// '
\r '
w.WriteCharEntity('\r');
w.WriteString("\r ");
// '
\n '
w.WriteCharEntity('\n');
w.WriteString("\n ");
// '\n
 '
w.WriteString("\n");
w.WriteCharEntity('\r');
w.WriteString(" ");
// '
\r'
w.WriteCharEntity('\n');
w.WriteString("\r");
w.WriteEndAttribute();
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d, "<root foo=\"" + ExpectedOutput(NewLines, (NewLineHandling)Variation.Param, true) + "\" />"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Desc = "Check for tab character in attribute with 'Entitize'", Param = NewLineHandling.Entitize, Id = 26, Priority = 0)]
//[Variation(Desc = "Check for tab character in attribute with 'Replace'", Param = NewLineHandling.Replace, Id = 27, Priority = 0)]
//[Variation(Desc = "Check for tab character in attribute with 'None'", Param = NewLineHandling.None, Id = 28, Priority = 0)]
public void EOF_Handling_10()
{
string Tabs = "foo\tbar	foo\n\tbar\t\n\t";
XDocument d = new XDocument();
XmlWriter w = CreateWriter(d);
w.WriteStartElement("root");
w.WriteStartAttribute("foo");
w.WriteString("foo\tbar");
w.WriteCharEntity('\t');
w.WriteString("foo\n\tbar\t\n\t");
w.WriteEndAttribute();
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d, "<root foo=\"" + ExpectedOutput(Tabs, (NewLineHandling)Variation.Param, true) + "\" />"))
throw new TestException(TestResult.Failed, "");
}
/*================== NewLineChars, IndentChars ==================*/
//[Variation(Desc = "NewLineChars and IndentChars Default values and test for proper indentation, Entitize", Param = NewLineHandling.Entitize, Id = 29, Priority = 1)]
//[Variation(Desc = "NewLineChars and IndentChars Default values and test for proper indentation, Replace", Param = NewLineHandling.Replace, Id = 30, Priority = 1)]
//[Variation(Desc = "NewLineChars and IndentChars Default values and test for proper indentation, None", Param = NewLineHandling.None, Id = 31, Priority = 1)]
public void EOF_Handling_11()
{
XDocument d = new XDocument();
XmlWriter w = CreateWriter(d);
TestLog.Compare(w.Settings.NewLineChars, Environment.NewLine, "Incorrect default value for XmlWriter.Settings.NewLineChars");
TestLog.Compare(w.Settings.IndentChars, " ", "Incorrect default value for XmlWriter.Settings.IndentChars");
w.WriteStartElement("root");
w.WriteStartElement("foo");
w.WriteElementString("bar", "");
w.WriteEndElement();
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d, "<root>\r\n <foo>\r\n <bar />\r\n </foo>\r\n</root>"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Desc = "Test fo proper indentation and newline handling when Indent = true, with custom NewLineChars and IndentChars; Entitize, '\\r', ' '", Params = new object[] { NewLineHandling.Entitize, "\r", " " }, Id = 32, Priority = 2)]
//[Variation(Desc = "Test fo proper indentation and newline handling when Indent = true, with custom NewLineChars and IndentChars; Replace, '\\r', ' '", Params = new object[] { NewLineHandling.Replace, "\r", " " }, Id = 33, Priority = 2)]
//[Variation(Desc = "Test fo proper indentation and newline handling when Indent = true, with custom NewLineChars and IndentChars; None, '\\r', ' '", Params = new object[] { NewLineHandling.None, "\r", " " }, Id = 34, Priority = 2)]
//[Variation(Desc = "Test fo proper indentation and newline handling when Indent = true, with custom NewLineChars and IndentChars; Entitize, '
', ' '", Params = new object[] { NewLineHandling.Entitize, "
", " " }, Id = 35, Priority = 2)]
//[Variation(Desc = "Test fo proper indentation and newline handling when Indent = true, with custom NewLineChars and IndentChars; Replace, '
', ' '", Params = new object[] { NewLineHandling.Replace, "
", " " }, Id = 36, Priority = 2)]
//[Variation(Desc = "Test fo proper indentation and newline handling when Indent = true, with custom NewLineChars and IndentChars; None, '
', ' '", Params = new object[] { NewLineHandling.None, "
", " " }, Id = 37, Priority = 2)]
//[Variation(Desc = "Test fo proper indentation and newline handling when Indent = true, with custom NewLineChars and IndentChars; Entitize, '\\r', '\\n'", Params = new object[] { NewLineHandling.Entitize, "\r", "\n" }, Id = 38, Priority = 2)]
//[Variation(Desc = "Test fo proper indentation and newline handling when Indent = true, with custom NewLineChars and IndentChars; Replace, '\\r', '\\n'", Params = new object[] { NewLineHandling.Replace, "\r", "\n" }, Id = 39, Priority = 2)]
//[Variation(Desc = "Test fo proper indentation and newline handling when Indent = true, with custom NewLineChars and IndentChars; None, '\\r', '\\n'", Params = new object[] { NewLineHandling.None, "\r", "\n" }, Id = 40, Priority = 2)]
public void EOF_Handling_13()
{
string PrototypeOutput = "<root>&NewLine&Indent<foo>&NewLine&Indent&Indent<bar />&NewLine&Indent</foo>&NewLine</root>";
XDocument d = new XDocument();
XmlWriter w = CreateWriter(d);
w.WriteStartElement("root");
w.WriteStartElement("foo");
w.WriteElementString("bar", "");
w.WriteEndElement();
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d, PrototypeOutput.Replace("&NewLine", Variation.Params[1].ToString()).Replace("&Indent", Variation.Params[2].ToString())))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Desc = "NewLine handling in attribute when Indent=true; Entitize, '\\r\\n'", Params = new object[] { NewLineHandling.Entitize, "\r\n" }, Id = 50, Priority = 1)]
//[Variation(Desc = "NewLine handling in attribute when Indent=true; Replace, '\\r\\n'", Params = new object[] { NewLineHandling.Replace, "\r\n" }, Id = 51, Priority = 1)]
//[Variation(Desc = "NewLine handling in attribute when Indent=true; None, '\\r\\n'", Params = new object[] { NewLineHandling.None, "\r\n" }, Id = 52, Priority = 1)]
//[Variation(Desc = "NewLine handling in attribute when Indent=true; Entitize, '\\r'", Params = new object[] { NewLineHandling.Entitize, "\r" }, Id = 53, Priority = 2)]
//[Variation(Desc = "NewLine handling in attribute when Indent=true; Replace, '\\r'", Params = new object[] { NewLineHandling.Replace, "\r" }, Id = 54, Priority = 2)]
//[Variation(Desc = "NewLine handling in attribute when Indent=true; None, '\\r'", Params = new object[] { NewLineHandling.None, "\r" }, Id = 54, Priority = 2)]
//[Variation(Desc = "NewLine handling in attribute when Indent=true; Entitize, '---'", Params = new object[] { NewLineHandling.Entitize, "---" }, Id = 54, Priority = 2)]
//[Variation(Desc = "NewLine handling in attribute when Indent=true; Replace, '---'", Params = new object[] { NewLineHandling.Replace, "---" }, Id = 55, Priority = 2)]
//[Variation(Desc = "NewLine handling in attribute when Indent=true; None, '---'", Params = new object[] { NewLineHandling.None, "---" })]
public void EOF_Handling_15()
{
XDocument d = new XDocument();
XmlWriter w = CreateWriter(d);
w.WriteStartElement("root");
w.WriteAttributeString("foo", "foo\r\nfoo\nfoo\rfoo\tfoo");
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d, "<root foo=\"" + ExpectedOutput("foo\r\nfoo\nfoo\rfoo\tfoo", (NewLineHandling)Variation.Params[0], true) + "\" />"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Desc = "NewLine handling between attributes when NewLineOnAttributes=true; Entitize, '\\r\\n'", Params = new object[] { NewLineHandling.Entitize, "\r\n" }, Id = 56, Priority = 1)]
//[Variation(Desc = "NewLine handling between attributes when NewLineOnAttributes=true; Replace, '\\r\\n'", Params = new object[] { NewLineHandling.Replace, "\r\n" }, Id = 57, Priority = 1)]
//[Variation(Desc = "NewLine handling between attributes when NewLineOnAttributes=true; None, '\\r\\n'", Params = new object[] { NewLineHandling.None, "\r\n" }, Id = 58, Priority = 1)]
//[Variation(Desc = "NewLine handling between attributes when NewLineOnAttributes=true; Entitize, '\\r'", Params = new object[] { NewLineHandling.Entitize, "\r" }, Id = 59, Priority = 2)]
//[Variation(Desc = "NewLine handling between attributes when NewLineOnAttributes=true; Replace, '\\r'", Params = new object[] { NewLineHandling.Replace, "\r" }, Id = 60, Priority = 2)]
//[Variation(Desc = "NewLine handling between attributes when NewLineOnAttributes=true; None, '\\r'", Params = new object[] { NewLineHandling.None, "\r" }, Id = 61, Priority = 2)]
//[Variation(Desc = "NewLine handling between attributes when NewLineOnAttributes=true; Entitize, '---'", Params = new object[] { NewLineHandling.Entitize, "---" }, Id = 62, Priority = 2)]
//[Variation(Desc = "NewLine handling between attributes when NewLineOnAttributes=true; Replace, '---'", Params = new object[] { NewLineHandling.Replace, "---" }, Id = 63, Priority = 2)]
//[Variation(Desc = "NewLine handling between attributes when NewLineOnAttributes=true; None, '---'", Params = new object[] { NewLineHandling.None, "---" }, Id = 64, Priority = 2)]
public void EOF_Handling_16()
{
string PrototypeOutput = "<root&NewLine foo=\"fooval\"&NewLine bar=\"barval\" />";
XDocument d = new XDocument();
XmlWriter w = CreateWriter(d);
w.WriteStartElement("root");
w.WriteAttributeString("foo", "fooval");
w.WriteAttributeString("bar", "barval");
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d, PrototypeOutput.Replace("&NewLine", Variation.Params[1].ToString())))
throw new TestException(TestResult.Failed, "");
}
}
}
}
}
| |
using System.Drawing;
using System.Text;
using System.Runtime.InteropServices;
using System;
namespace Oranikle.Studio.Controls
{
internal class Win32
{
public struct NCCALCSIZE_PARAMS
{
public Oranikle.Studio.Controls.NWin32.RECT rgc;
public Oranikle.Studio.Controls.Win32.WINDOWPOS wndpos;
}
public struct RECT
{
public int Bottom;
public int Left;
public int Right;
public int Top;
}
public struct WINDOWPOS
{
public int cx;
public int cy;
public uint flags;
public System.IntPtr hwnd;
public System.IntPtr hwndAfter;
public int x;
public int y;
}
public const int GW_CHILD = 5;
public const int GW_HWNDFIRST = 0;
public const int GW_HWNDLAST = 1;
public const int GW_HWNDNEXT = 2;
public const int GW_HWNDPREV = 3;
public const int GW_OWNER = 4;
public const int GWL_WNDPROC = -4;
public const int HC_ACTION = 0;
public const int WH_CALLWNDPROC = 4;
public const int WM_CREATE = 1;
public const int WM_DESTROY = 2;
public const int WM_HSCROLL = 276;
public const int WM_NCCALCSIZE = 131;
public const int WM_NCCREATE = 129;
public const int WM_NCPAINT = 133;
public const int WM_PAINT = 15;
public const int WM_PARENTNOTIFY = 528;
public const int WM_PRINT = 791;
public const int WM_SHARED_MENU = 482;
public const int WM_SHOWWINDOW = 24;
public const int WM_WINDOWPOSCHANGING = 70;
public Win32()
{
}
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("Gdi32.dll", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern System.IntPtr CreateCompatibleDC(System.IntPtr hdc);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("User32.dll", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int GetClassName(System.IntPtr hwnd, char[] className, int maxCount);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("user32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int GetClientRect(System.IntPtr hwnd, out System.Drawing.Rectangle rect);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("user32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int GetClientRect(System.IntPtr hwnd, ref Oranikle.Studio.Controls.NWin32.RECT lpRect);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("User32.dll", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern System.IntPtr GetWindow(System.IntPtr hwnd, int uCmd);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("User32.dll", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern System.IntPtr GetWindowDC(System.IntPtr handle);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("user32.dll", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
internal static extern bool GetWindowRect(System.IntPtr hWnd, out System.Drawing.Rectangle rect);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("user32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern bool InvalidateRect(System.IntPtr hwnd, ref System.Drawing.Rectangle rect, bool bErase);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("User32.dll", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern bool IsWindowVisible(System.IntPtr hwnd);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("user32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern bool MoveWindow(System.IntPtr hwnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("User32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
internal static extern int RealGetWindowClass(System.IntPtr hwnd, System.Text.StringBuilder pszType, int cchType);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("User32.dll", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern System.IntPtr ReleaseDC(System.IntPtr handle, System.IntPtr hDC);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("user32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern bool UpdateWindow(System.IntPtr hwnd);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("user32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern bool ValidateRect(System.IntPtr hwnd, ref System.Drawing.Rectangle rect);
[Flags]
internal enum FlagsSetWindowPos : uint
{
SWP_NOSIZE = 0x0001,
SWP_NOMOVE = 0x0002,
SWP_NOZORDER = 0x0004,
SWP_NOREDRAW = 0x0008,
SWP_NOACTIVATE = 0x0010,
SWP_FRAMECHANGED = 0x0020,
SWP_SHOWWINDOW = 0x0040,
SWP_HIDEWINDOW = 0x0080,
SWP_NOCOPYBITS = 0x0100,
SWP_NOOWNERZORDER = 0x0200,
SWP_NOSENDCHANGING = 0x0400,
SWP_DRAWFRAME = 0x0020,
SWP_NOREPOSITION = 0x0200,
SWP_DEFERERASE = 0x2000,
SWP_ASYNCWINDOWPOS = 0x4000
}
internal enum ShowWindowStyles : short
{
SW_HIDE = 0,
SW_SHOWNORMAL = 1,
SW_NORMAL = 1,
SW_SHOWMINIMIZED = 2,
SW_SHOWMAXIMIZED = 3,
SW_MAXIMIZE = 3,
SW_SHOWNOACTIVATE = 4,
SW_SHOW = 5,
SW_MINIMIZE = 6,
SW_SHOWMINNOACTIVE = 7,
SW_SHOWNA = 8,
SW_RESTORE = 9,
SW_SHOWDEFAULT = 10,
SW_FORCEMINIMIZE = 11,
SW_MAX = 11
}
internal enum WindowStyles : uint
{
WS_OVERLAPPED = 0x00000000,
WS_POPUP = 0x80000000,
WS_CHILD = 0x40000000,
WS_MINIMIZE = 0x20000000,
WS_VISIBLE = 0x10000000,
WS_DISABLED = 0x08000000,
WS_CLIPSIBLINGS = 0x04000000,
WS_CLIPCHILDREN = 0x02000000,
WS_MAXIMIZE = 0x01000000,
WS_CAPTION = 0x00C00000,
WS_BORDER = 0x00800000,
WS_DLGFRAME = 0x00400000,
WS_VSCROLL = 0x00200000,
WS_HSCROLL = 0x00100000,
WS_SYSMENU = 0x00080000,
WS_THICKFRAME = 0x00040000,
WS_GROUP = 0x00020000,
WS_TABSTOP = 0x00010000,
WS_MINIMIZEBOX = 0x00020000,
WS_MAXIMIZEBOX = 0x00010000,
WS_TILED = 0x00000000,
WS_ICONIC = 0x20000000,
WS_SIZEBOX = 0x00040000,
WS_POPUPWINDOW = 0x80880000,
WS_OVERLAPPEDWINDOW = 0x00CF0000,
WS_TILEDWINDOW = 0x00CF0000,
WS_CHILDWINDOW = 0x40000000
}
internal enum WindowExStyles
{
WS_EX_DLGMODALFRAME = 0x00000001,
WS_EX_NOPARENTNOTIFY = 0x00000004,
WS_EX_TOPMOST = 0x00000008,
WS_EX_ACCEPTFILES = 0x00000010,
WS_EX_TRANSPARENT = 0x00000020,
WS_EX_MDICHILD = 0x00000040,
WS_EX_TOOLWINDOW = 0x00000080,
WS_EX_WINDOWEDGE = 0x00000100,
WS_EX_CLIENTEDGE = 0x00000200,
WS_EX_CONTEXTHELP = 0x00000400,
WS_EX_RIGHT = 0x00001000,
WS_EX_LEFT = 0x00000000,
WS_EX_RTLREADING = 0x00002000,
WS_EX_LTRREADING = 0x00000000,
WS_EX_LEFTSCROLLBAR = 0x00004000,
WS_EX_RIGHTSCROLLBAR = 0x00000000,
WS_EX_CONTROLPARENT = 0x00010000,
WS_EX_STATICEDGE = 0x00020000,
WS_EX_APPWINDOW = 0x00040000,
WS_EX_OVERLAPPEDWINDOW = 0x00000300,
WS_EX_PALETTEWINDOW = 0x00000188,
WS_EX_LAYERED = 0x00080000
}
internal enum Msgs
{
WM_NULL = 0x0000,
WM_CREATE = 0x0001,
WM_DESTROY = 0x0002,
WM_MOVE = 0x0003,
WM_SIZE = 0x0005,
WM_ACTIVATE = 0x0006,
WM_SETFOCUS = 0x0007,
WM_KILLFOCUS = 0x0008,
WM_ENABLE = 0x000A,
WM_SETREDRAW = 0x000B,
WM_SETTEXT = 0x000C,
WM_GETTEXT = 0x000D,
WM_GETTEXTLENGTH = 0x000E,
WM_PAINT = 0x000F,
WM_CLOSE = 0x0010,
WM_QUERYENDSESSION = 0x0011,
WM_QUIT = 0x0012,
WM_QUERYOPEN = 0x0013,
WM_ERASEBKGND = 0x0014,
WM_SYSCOLORCHANGE = 0x0015,
WM_ENDSESSION = 0x0016,
WM_SHOWWINDOW = 0x0018,
WM_WININICHANGE = 0x001A,
WM_SETTINGCHANGE = 0x001A,
WM_DEVMODECHANGE = 0x001B,
WM_ACTIVATEAPP = 0x001C,
WM_FONTCHANGE = 0x001D,
WM_TIMECHANGE = 0x001E,
WM_CANCELMODE = 0x001F,
WM_SETCURSOR = 0x0020,
WM_MOUSEACTIVATE = 0x0021,
WM_CHILDACTIVATE = 0x0022,
WM_QUEUESYNC = 0x0023,
WM_GETMINMAXINFO = 0x0024,
WM_PAINTICON = 0x0026,
WM_ICONERASEBKGND = 0x0027,
WM_NEXTDLGCTL = 0x0028,
WM_SPOOLERSTATUS = 0x002A,
WM_DRAWITEM = 0x002B,
WM_MEASUREITEM = 0x002C,
WM_DELETEITEM = 0x002D,
WM_VKEYTOITEM = 0x002E,
WM_CHARTOITEM = 0x002F,
WM_SETFONT = 0x0030,
WM_GETFONT = 0x0031,
WM_SETHOTKEY = 0x0032,
WM_GETHOTKEY = 0x0033,
WM_QUERYDRAGICON = 0x0037,
WM_COMPAREITEM = 0x0039,
WM_GETOBJECT = 0x003D,
WM_COMPACTING = 0x0041,
WM_COMMNOTIFY = 0x0044,
WM_WINDOWPOSCHANGING = 0x0046,
WM_WINDOWPOSCHANGED = 0x0047,
WM_POWER = 0x0048,
WM_COPYDATA = 0x004A,
WM_CANCELJOURNAL = 0x004B,
WM_NOTIFY = 0x004E,
WM_INPUTLANGCHANGEREQUEST = 0x0050,
WM_INPUTLANGCHANGE = 0x0051,
WM_TCARD = 0x0052,
WM_HELP = 0x0053,
WM_USERCHANGED = 0x0054,
WM_NOTIFYFORMAT = 0x0055,
WM_CONTEXTMENU = 0x007B,
WM_STYLECHANGING = 0x007C,
WM_STYLECHANGED = 0x007D,
WM_DISPLAYCHANGE = 0x007E,
WM_GETICON = 0x007F,
WM_SETICON = 0x0080,
WM_NCCREATE = 0x0081,
WM_NCDESTROY = 0x0082,
WM_NCCALCSIZE = 0x0083,
WM_NCHITTEST = 0x0084,
WM_NCPAINT = 0x0085,
WM_NCACTIVATE = 0x0086,
WM_GETDLGCODE = 0x0087,
WM_SYNCPAINT = 0x0088,
WM_NCMOUSEMOVE = 0x00A0,
WM_NCLBUTTONDOWN = 0x00A1,
WM_NCLBUTTONUP = 0x00A2,
WM_NCLBUTTONDBLCLK = 0x00A3,
WM_NCRBUTTONDOWN = 0x00A4,
WM_NCRBUTTONUP = 0x00A5,
WM_NCRBUTTONDBLCLK = 0x00A6,
WM_NCMBUTTONDOWN = 0x00A7,
WM_NCMBUTTONUP = 0x00A8,
WM_NCMBUTTONDBLCLK = 0x00A9,
WM_KEYDOWN = 0x0100,
WM_KEYUP = 0x0101,
WM_CHAR = 0x0102,
WM_DEADCHAR = 0x0103,
WM_SYSKEYDOWN = 0x0104,
WM_SYSKEYUP = 0x0105,
WM_SYSCHAR = 0x0106,
WM_SYSDEADCHAR = 0x0107,
WM_KEYLAST = 0x0108,
WM_IME_STARTCOMPOSITION = 0x010D,
WM_IME_ENDCOMPOSITION = 0x010E,
WM_IME_COMPOSITION = 0x010F,
WM_IME_KEYLAST = 0x010F,
WM_INITDIALOG = 0x0110,
WM_COMMAND = 0x0111,
WM_SYSCOMMAND = 0x0112,
WM_TIMER = 0x0113,
WM_HSCROLL = 0x0114,
WM_VSCROLL = 0x0115,
WM_INITMENU = 0x0116,
WM_INITMENUPOPUP = 0x0117,
WM_MENUSELECT = 0x011F,
WM_MENUCHAR = 0x0120,
WM_ENTERIDLE = 0x0121,
WM_MENURBUTTONUP = 0x0122,
WM_MENUDRAG = 0x0123,
WM_MENUGETOBJECT = 0x0124,
WM_UNINITMENUPOPUP = 0x0125,
WM_MENUCOMMAND = 0x0126,
WM_CTLCOLORMSGBOX = 0x0132,
WM_CTLCOLOREDIT = 0x0133,
WM_CTLCOLORLISTBOX = 0x0134,
WM_CTLCOLORBTN = 0x0135,
WM_CTLCOLORDLG = 0x0136,
WM_CTLCOLORSCROLLBAR = 0x0137,
WM_CTLCOLORSTATIC = 0x0138,
WM_MOUSEMOVE = 0x0200,
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_LBUTTONDBLCLK = 0x0203,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205,
WM_RBUTTONDBLCLK = 0x0206,
WM_MBUTTONDOWN = 0x0207,
WM_MBUTTONUP = 0x0208,
WM_MBUTTONDBLCLK = 0x0209,
WM_MOUSEWHEEL = 0x020A,
WM_PARENTNOTIFY = 0x0210,
WM_ENTERMENULOOP = 0x0211,
WM_EXITMENULOOP = 0x0212,
WM_NEXTMENU = 0x0213,
WM_SIZING = 0x0214,
WM_CAPTURECHANGED = 0x0215,
WM_MOVING = 0x0216,
WM_DEVICECHANGE = 0x0219,
WM_MDICREATE = 0x0220,
WM_MDIDESTROY = 0x0221,
WM_MDIACTIVATE = 0x0222,
WM_MDIRESTORE = 0x0223,
WM_MDINEXT = 0x0224,
WM_MDIMAXIMIZE = 0x0225,
WM_MDITILE = 0x0226,
WM_MDICASCADE = 0x0227,
WM_MDIICONARRANGE = 0x0228,
WM_MDIGETACTIVE = 0x0229,
WM_MDISETMENU = 0x0230,
WM_ENTERSIZEMOVE = 0x0231,
WM_EXITSIZEMOVE = 0x0232,
WM_DROPFILES = 0x0233,
WM_MDIREFRESHMENU = 0x0234,
WM_IME_SETCONTEXT = 0x0281,
WM_IME_NOTIFY = 0x0282,
WM_IME_CONTROL = 0x0283,
WM_IME_COMPOSITIONFULL = 0x0284,
WM_IME_SELECT = 0x0285,
WM_IME_CHAR = 0x0286,
WM_IME_REQUEST = 0x0288,
WM_IME_KEYDOWN = 0x0290,
WM_IME_KEYUP = 0x0291,
WM_MOUSEHOVER = 0x02A1,
WM_MOUSELEAVE = 0x02A3,
WM_CUT = 0x0300,
WM_COPY = 0x0301,
WM_PASTE = 0x0302,
WM_CLEAR = 0x0303,
WM_UNDO = 0x0304,
WM_RENDERFORMAT = 0x0305,
WM_RENDERALLFORMATS = 0x0306,
WM_DESTROYCLIPBOARD = 0x0307,
WM_DRAWCLIPBOARD = 0x0308,
WM_PAINTCLIPBOARD = 0x0309,
WM_VSCROLLCLIPBOARD = 0x030A,
WM_SIZECLIPBOARD = 0x030B,
WM_ASKCBFORMATNAME = 0x030C,
WM_CHANGECBCHAIN = 0x030D,
WM_HSCROLLCLIPBOARD = 0x030E,
WM_QUERYNEWPALETTE = 0x030F,
WM_PALETTEISCHANGING = 0x0310,
WM_PALETTECHANGED = 0x0311,
WM_HOTKEY = 0x0312,
WM_PRINT = 0x0317,
WM_PRINTCLIENT = 0x0318,
WM_HANDHELDFIRST = 0x0358,
WM_HANDHELDLAST = 0x035F,
WM_AFXFIRST = 0x0360,
WM_AFXLAST = 0x037F,
WM_PENWINFIRST = 0x0380,
WM_PENWINLAST = 0x038F,
WM_APP = 0x8000,
WM_USER = 0x0400
}
internal enum HitTest
{
HTERROR = -2,
HTTRANSPARENT = -1,
HTNOWHERE = 0,
HTCLIENT = 1,
HTCAPTION = 2,
HTSYSMENU = 3,
HTGROWBOX = 4,
HTSIZE = 4,
HTMENU = 5,
HTHSCROLL = 6,
HTVSCROLL = 7,
HTMINBUTTON = 8,
HTMAXBUTTON = 9,
HTLEFT = 10,
HTRIGHT = 11,
HTTOP = 12,
HTTOPLEFT = 13,
HTTOPRIGHT = 14,
HTBOTTOM = 15,
HTBOTTOMLEFT = 16,
HTBOTTOMRIGHT = 17,
HTBORDER = 18,
HTREDUCE = 8,
HTZOOM = 9,
HTSIZEFIRST = 10,
HTSIZELAST = 17,
HTOBJECT = 19,
HTCLOSE = 20,
HTHELP = 21
}
internal enum ScrollBars : uint
{
SB_HORZ = 0,
SB_VERT = 1,
SB_CTL = 2,
SB_BOTH = 3
}
internal enum GetWindowLongIndex : int
{
GWL_STYLE = -16,
GWL_EXSTYLE = -20
}
// Hook Types
internal enum HookType : int
{
WH_JOURNALRECORD = 0,
WH_JOURNALPLAYBACK = 1,
WH_KEYBOARD = 2,
WH_GETMESSAGE = 3,
WH_CALLWNDPROC = 4,
WH_CBT = 5,
WH_SYSMSGFILTER = 6,
WH_MOUSE = 7,
WH_HARDWARE = 8,
WH_DEBUG = 9,
WH_SHELL = 10,
WH_FOREGROUNDIDLE = 11,
WH_CALLWNDPROCRET = 12,
WH_KEYBOARD_LL = 13,
WH_MOUSE_LL = 14
}
}
}
| |
using System.Runtime.CompilerServices;
using GitVersion.Configuration;
using GitVersion.Core.Tests.Helpers;
using GitVersion.Extensions;
using GitVersion.Helpers;
using GitVersion.Logging;
using GitVersion.Model.Configuration;
using GitVersion.VersionCalculation;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NUnit.Framework;
using Shouldly;
using YamlDotNet.Serialization;
namespace GitVersion.Core.Tests;
[TestFixture]
public class ConfigProviderTests : TestBase
{
private const string DefaultRepoPath = @"c:\MyGitRepo";
private string repoPath;
private IConfigProvider configProvider;
private IFileSystem fileSystem;
[SetUp]
public void Setup()
{
this.repoPath = DefaultRepoPath;
var options = Options.Create(new GitVersionOptions { WorkingDirectory = repoPath });
var sp = ConfigureServices(services => services.AddSingleton(options));
this.configProvider = sp.GetRequiredService<IConfigProvider>();
this.fileSystem = sp.GetRequiredService<IFileSystem>();
ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute<TestAttribute>();
}
[Test]
public void OverwritesDefaultsWithProvidedConfig()
{
var defaultConfig = this.configProvider.Provide(this.repoPath);
const string text = @"
next-version: 2.0.0
branches:
develop:
mode: ContinuousDeployment
tag: dev";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.NextVersion.ShouldBe("2.0.0");
config.Branches.ShouldNotBeNull();
config.Branches["develop"].Increment.ShouldBe(defaultConfig.Branches["develop"].Increment);
config.Branches["develop"].VersioningMode.ShouldBe(defaultConfig.Branches["develop"].VersioningMode);
config.Branches["develop"].Tag.ShouldBe("dev");
}
[Test]
public void AllBranchesModeWhenUsingMainline()
{
const string text = "mode: Mainline";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
var branches = config.Branches.Select(x => x.Value);
branches.All(branch => branch.VersioningMode == VersioningMode.Mainline).ShouldBe(true);
}
[Test]
public void CanRemoveTag()
{
const string text = @"
next-version: 2.0.0
branches:
release:
tag: """"";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.NextVersion.ShouldBe("2.0.0");
config.Branches["release"].Tag.ShouldBe(string.Empty);
}
[Test]
public void RegexIsRequired()
{
const string text = @"
next-version: 2.0.0
branches:
bug:
tag: bugfix";
SetupConfigFileContent(text);
var ex = Should.Throw<ConfigurationException>(() => this.configProvider.Provide(this.repoPath));
ex.Message.ShouldBe($"Branch configuration 'bug' is missing required configuration 'regex'{System.Environment.NewLine}" +
"See https://gitversion.net/docs/reference/configuration for more info");
}
[Test]
public void SourceBranchIsRequired()
{
const string text = @"
next-version: 2.0.0
branches:
bug:
regex: 'bug[/-]'
tag: bugfix";
SetupConfigFileContent(text);
var ex = Should.Throw<ConfigurationException>(() => this.configProvider.Provide(this.repoPath));
ex.Message.ShouldBe($"Branch configuration 'bug' is missing required configuration 'source-branches'{System.Environment.NewLine}" +
"See https://gitversion.net/docs/reference/configuration for more info");
}
[Test(Description = "This test proves the configuration validation will fail early with a helpful message when a branch listed in source-branches has no configuration.")]
public void SourceBranchesValidationShouldFailWhenMatchingBranchConfigurationIsMissing()
{
const string text = @"
branches:
bug:
regex: 'bug[/-]'
tag: bugfix
source-branches: [notconfigured]";
SetupConfigFileContent(text);
var ex = Should.Throw<ConfigurationException>(() => this.configProvider.Provide(this.repoPath));
ex.Message.ShouldBe($"Branch configuration 'bug' defines these 'source-branches' that are not configured: '[notconfigured]'{System.Environment.NewLine}" +
"See https://gitversion.net/docs/reference/configuration for more info");
}
[Test(Description = "Well-known branches may not be present in the configuration file. This test confirms the validation check succeeds when the source-branches configuration contain these well-known branches.")]
[TestCase(Config.MainBranchKey)]
[TestCase(Config.DevelopBranchKey)]
public void SourceBranchesValidationShouldSucceedForWellKnownBranches(string wellKnownBranchKey)
{
var text = $@"
branches:
bug:
regex: 'bug[/-]'
tag: bugfix
source-branches: [{wellKnownBranchKey}]";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.Branches["bug"].SourceBranches.ShouldBe(new List<string> { wellKnownBranchKey });
}
[Test]
public void CanProvideConfigForNewBranch()
{
const string text = @"
next-version: 2.0.0
branches:
bug:
regex: 'bug[/-]'
tag: bugfix
source-branches: []";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.Branches["bug"].Regex.ShouldBe("bug[/-]");
config.Branches["bug"].Tag.ShouldBe("bugfix");
}
[Test]
public void MasterConfigReplacedWithMain()
{
const string text = @"
next-version: 2.0.0
branches:
master:
regex: '^master$|^main$'
tag: beta";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.Branches[MainBranch].Regex.ShouldBe("^master$|^main$");
config.Branches[MainBranch].Tag.ShouldBe("beta");
}
[Test]
public void MasterConfigReplacedWithMainInSourceBranches()
{
const string text = @"
next-version: 2.0.0
branches:
breaking:
regex: breaking[/]
mode: ContinuousDeployment
increment: Major
source-branches: ['master']
is-release-branch: false";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.Branches["breaking"].Regex.ShouldBe("breaking[/]");
config.Branches["breaking"].SourceBranches.ShouldHaveSingleItem();
config.Branches["breaking"].SourceBranches?.ShouldContain(MainBranch);
}
[Test]
public void NextVersionCanBeInteger()
{
const string text = "next-version: 2";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.NextVersion.ShouldBe("2.0");
}
[Test]
public void NextVersionCanHaveEnormousMinorVersion()
{
const string text = "next-version: 2.118998723";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.NextVersion.ShouldBe("2.118998723");
}
[Test]
public void NextVersionCanHavePatch()
{
const string text = "next-version: 2.12.654651698";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.NextVersion.ShouldBe("2.12.654651698");
}
[Test]
[MethodImpl(MethodImplOptions.NoInlining)]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void CanWriteOutEffectiveConfiguration()
{
var config = this.configProvider.Provide(this.repoPath);
config.ToString().ShouldMatchApproved();
}
[Test]
public void CanUpdateAssemblyInformationalVersioningScheme()
{
const string text = @"
assembly-versioning-scheme: MajorMinor
assembly-file-versioning-scheme: MajorMinorPatch
assembly-informational-format: '{NugetVersion}'";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor);
config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch);
config.AssemblyInformationalFormat.ShouldBe("{NugetVersion}");
}
[Test]
public void CanUpdateAssemblyInformationalVersioningSchemeWithMultipleVariables()
{
const string text = @"
assembly-versioning-scheme: MajorMinor
assembly-file-versioning-scheme: MajorMinorPatch
assembly-informational-format: '{Major}.{Minor}.{Patch}'";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor);
config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch);
config.AssemblyInformationalFormat.ShouldBe("{Major}.{Minor}.{Patch}");
}
[Test]
public void CanUpdateAssemblyInformationalVersioningSchemeWithFullSemVer()
{
const string text = @"assembly-versioning-scheme: MajorMinorPatch
assembly-file-versioning-scheme: MajorMinorPatch
assembly-informational-format: '{FullSemVer}'
mode: ContinuousDelivery
next-version: 5.3.0
branches: {}";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch);
config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch);
config.AssemblyInformationalFormat.ShouldBe("{FullSemVer}");
}
[Test]
public void CanReadDefaultDocument()
{
const string text = "";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch);
config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch);
config.AssemblyInformationalFormat.ShouldBe(null);
config.Branches["develop"].Tag.ShouldBe("alpha");
config.Branches["release"].Tag.ShouldBe("beta");
config.TagPrefix.ShouldBe(Config.DefaultTagPrefix);
config.NextVersion.ShouldBe(null);
}
[Test]
public void VerifyAliases()
{
var config = typeof(Config);
var propertiesMissingAlias = config.GetProperties()
.Where(p => p.GetCustomAttribute<ObsoleteAttribute>() == null)
.Where(p => p.GetCustomAttribute(typeof(YamlMemberAttribute)) == null)
.Select(p => p.Name);
propertiesMissingAlias.ShouldBeEmpty();
}
[Test]
public void NoWarnOnGitVersionYmlFile()
{
SetupConfigFileContent(string.Empty);
var stringLogger = string.Empty;
void Action(string info) => stringLogger = info;
var logAppender = new TestLogAppender(Action);
var log = new Log(logAppender);
var options = Options.Create(new GitVersionOptions { WorkingDirectory = repoPath });
var sp = ConfigureServices(services =>
{
services.AddSingleton(options);
services.AddSingleton<ILog>(log);
});
this.configProvider = sp.GetRequiredService<IConfigProvider>();
this.configProvider.Provide(this.repoPath);
stringLogger.Length.ShouldBe(0);
}
private void SetupConfigFileContent(string text, string fileName = ConfigFileLocator.DefaultFileName) => SetupConfigFileContent(text, fileName, this.repoPath);
private void SetupConfigFileContent(string text, string fileName, string path)
{
var fullPath = PathHelper.Combine(path, fileName);
this.fileSystem.WriteAllText(fullPath, text);
}
[Test]
public void ShouldUseSpecifiedSourceBranchesForDevelop()
{
const string text = @"
next-version: 2.0.0
branches:
develop:
mode: ContinuousDeployment
source-branches: ['develop']
tag: dev";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.Branches["develop"].SourceBranches.ShouldBe(new List<string> { "develop" });
}
[Test]
public void ShouldUseDefaultSourceBranchesWhenNotSpecifiedForDevelop()
{
const string text = @"
next-version: 2.0.0
branches:
develop:
mode: ContinuousDeployment
tag: dev";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.Branches["develop"].SourceBranches.ShouldBe(new List<string>());
}
[Test]
public void ShouldUseSpecifiedSourceBranchesForFeature()
{
const string text = @"
next-version: 2.0.0
branches:
feature:
mode: ContinuousDeployment
source-branches: ['develop', 'release']
tag: dev";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.Branches["feature"].SourceBranches.ShouldBe(new List<string> { "develop", "release" });
}
[Test]
public void ShouldUseDefaultSourceBranchesWhenNotSpecifiedForFeature()
{
const string text = @"
next-version: 2.0.0
branches:
feature:
mode: ContinuousDeployment
tag: dev";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.Branches["feature"].SourceBranches.ShouldBe(
new List<string> { "develop", MainBranch, "release", "feature", "support", "hotfix" });
}
[Test]
public void ShouldNotOverrideAnythingWhenOverrideConfigIsEmpty()
{
const string text = @"
next-version: 1.2.3
tag-prefix: custom-tag-prefix-from-yml";
SetupConfigFileContent(text);
var expectedConfig = this.configProvider.Provide(this.repoPath);
var overridenConfig = this.configProvider.Provide(this.repoPath, new Config());
overridenConfig.AssemblyVersioningScheme.ShouldBe(expectedConfig.AssemblyVersioningScheme);
overridenConfig.AssemblyFileVersioningScheme.ShouldBe(expectedConfig.AssemblyFileVersioningScheme);
overridenConfig.AssemblyInformationalFormat.ShouldBe(expectedConfig.AssemblyInformationalFormat);
overridenConfig.AssemblyVersioningFormat.ShouldBe(expectedConfig.AssemblyVersioningFormat);
overridenConfig.AssemblyFileVersioningFormat.ShouldBe(expectedConfig.AssemblyFileVersioningFormat);
overridenConfig.VersioningMode.ShouldBe(expectedConfig.VersioningMode);
overridenConfig.TagPrefix.ShouldBe(expectedConfig.TagPrefix);
overridenConfig.ContinuousDeploymentFallbackTag.ShouldBe(expectedConfig.ContinuousDeploymentFallbackTag);
overridenConfig.NextVersion.ShouldBe(expectedConfig.NextVersion);
overridenConfig.MajorVersionBumpMessage.ShouldBe(expectedConfig.MajorVersionBumpMessage);
overridenConfig.MinorVersionBumpMessage.ShouldBe(expectedConfig.MinorVersionBumpMessage);
overridenConfig.PatchVersionBumpMessage.ShouldBe(expectedConfig.PatchVersionBumpMessage);
overridenConfig.NoBumpMessage.ShouldBe(expectedConfig.NoBumpMessage);
overridenConfig.LegacySemVerPadding.ShouldBe(expectedConfig.LegacySemVerPadding);
overridenConfig.BuildMetaDataPadding.ShouldBe(expectedConfig.BuildMetaDataPadding);
overridenConfig.CommitsSinceVersionSourcePadding.ShouldBe(expectedConfig.CommitsSinceVersionSourcePadding);
overridenConfig.TagPreReleaseWeight.ShouldBe(expectedConfig.TagPreReleaseWeight);
overridenConfig.CommitMessageIncrementing.ShouldBe(expectedConfig.CommitMessageIncrementing);
overridenConfig.Increment.ShouldBe(expectedConfig.Increment);
overridenConfig.CommitDateFormat.ShouldBe(expectedConfig.CommitDateFormat);
overridenConfig.MergeMessageFormats.ShouldBe(expectedConfig.MergeMessageFormats);
overridenConfig.UpdateBuildNumber.ShouldBe(expectedConfig.UpdateBuildNumber);
overridenConfig.Ignore.ShouldBeEquivalentTo(expectedConfig.Ignore);
overridenConfig.Branches.Keys.ShouldBe(expectedConfig.Branches.Keys);
foreach (var branch in overridenConfig.Branches.Keys)
{
overridenConfig.Branches[branch].ShouldBeEquivalentTo(expectedConfig.Branches[branch]);
}
}
[Test]
public void ShouldUseDefaultTagPrefixWhenNotSetInConfigFile()
{
const string text = "";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.TagPrefix.ShouldBe("[vV]");
}
[Test]
public void ShouldUseTagPrefixFromConfigFileWhenProvided()
{
const string text = "tag-prefix: custom-tag-prefix-from-yml";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath);
config.TagPrefix.ShouldBe("custom-tag-prefix-from-yml");
}
[Test]
public void ShouldOverrideTagPrefixWithOverrideConfigValue([Values] bool tagPrefixSetAtYmlFile)
{
var text = tagPrefixSetAtYmlFile ? "tag-prefix: custom-tag-prefix-from-yml" : "";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath, new Config { TagPrefix = "tag-prefix-from-override-config" });
config.TagPrefix.ShouldBe("tag-prefix-from-override-config");
}
[Test]
public void ShouldNotOverrideDefaultTagPrefixWhenNotSetInOverrideConfig()
{
const string text = "";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath, new Config { TagPrefix = null });
config.TagPrefix.ShouldBe("[vV]");
}
[Test]
public void ShouldNotOverrideTagPrefixFromConfigFileWhenNotSetInOverrideConfig()
{
const string text = "tag-prefix: custom-tag-prefix-from-yml";
SetupConfigFileContent(text);
var config = this.configProvider.Provide(this.repoPath, new Config { TagPrefix = null });
config.TagPrefix.ShouldBe("custom-tag-prefix-from-yml");
}
}
| |
namespace Orleans.CodeGenerator
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Orleans.CodeGeneration;
using Orleans.CodeGenerator.Utilities;
using Orleans.Concurrency;
using Orleans.Runtime;
using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils;
using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
/// <summary>
/// Code generator which generates <see cref="GrainReference"/>s for grains.
/// </summary>
internal static class GrainReferenceGenerator
{
/// <summary>
/// The suffix appended to the name of generated classes.
/// </summary>
private const string ClassSuffix = "Reference";
/// <summary>
/// A reference to the CheckGrainObserverParamInternal method.
/// </summary>
private static readonly Expression<Action> CheckGrainObserverParamInternalExpression =
() => GrainFactoryBase.CheckGrainObserverParamInternal(null);
/// <summary>
/// Returns the name of the generated class for the provided type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The name of the generated class for the provided type.</returns>
internal static string GetGeneratedClassName(Type type) => CodeGeneratorCommon.ClassPrefix + TypeUtils.GetSuitableClassName(type) + ClassSuffix;
/// <summary>
/// Generates the class for the provided grain types.
/// </summary>
/// <param name="grainType">
/// The grain interface type.
/// </param>
/// <param name="generatedTypeName">Name of the generated type.</param>
/// <param name="onEncounteredType">The callback which is invoked when a type is encountered.</param>
/// <returns>
/// The generated class.
/// </returns>
internal static TypeDeclarationSyntax GenerateClass(Type grainType, string generatedTypeName, Action<Type> onEncounteredType)
{
var grainTypeInfo = grainType.GetTypeInfo();
var genericTypes = grainTypeInfo.IsGenericTypeDefinition
? grainTypeInfo.GetGenericArguments()
.Select(_ => SF.TypeParameter(_.ToString()))
.ToArray()
: new TypeParameterSyntax[0];
// Create the special marker attribute.
var markerAttribute =
SF.Attribute(typeof(GrainReferenceAttribute).GetNameSyntax())
.AddArgumentListArguments(
SF.AttributeArgument(
SF.TypeOfExpression(grainType.GetTypeSyntax(includeGenericParameters: false))));
var attributes = SF.AttributeList()
.AddAttributes(
CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(),
SF.Attribute(typeof(SerializableAttribute).GetNameSyntax()),
SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()),
markerAttribute);
var classDeclaration =
SF.ClassDeclaration(generatedTypeName)
.AddModifiers(SF.Token(SyntaxKind.InternalKeyword))
.AddBaseListTypes(
SF.SimpleBaseType(typeof(GrainReference).GetTypeSyntax()),
SF.SimpleBaseType(grainType.GetTypeSyntax()))
.AddConstraintClauses(grainType.GetTypeConstraintSyntax())
.AddMembers(GenerateConstructors(generatedTypeName))
.AddMembers(
GenerateInterfaceIdProperty(grainType),
GenerateInterfaceVersionProperty(grainType),
GenerateInterfaceNameProperty(grainType),
GenerateIsCompatibleMethod(grainType),
GenerateGetMethodNameMethod(grainType))
.AddMembers(GenerateInvokeMethods(grainType, onEncounteredType))
.AddAttributeLists(attributes);
if (genericTypes.Length > 0)
{
classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes);
}
return classDeclaration;
}
/// <summary>
/// Generates constructors.
/// </summary>
/// <param name="className">The class name.</param>
/// <returns>Constructor syntax for the provided class name.</returns>
private static MemberDeclarationSyntax[] GenerateConstructors(string className)
{
var baseConstructors =
typeof(GrainReference).GetTypeInfo().GetConstructors(
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).Where(_ => !_.IsPrivate);
var constructors = new List<MemberDeclarationSyntax>();
foreach (var baseConstructor in baseConstructors)
{
var args = baseConstructor.GetParameters()
.Select(arg => SF.Argument(arg.Name.ToIdentifierName()))
.ToArray();
var declaration =
baseConstructor.GetDeclarationSyntax(className)
.WithInitializer(
SF.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer)
.AddArgumentListArguments(args))
.AddBodyStatements();
constructors.Add(declaration);
}
return constructors.ToArray();
}
/// <summary>
/// Generates invoker methods.
/// </summary>
/// <param name="grainType">The grain type.</param>
/// <param name="onEncounteredType">
/// The callback which is invoked when a type is encountered.
/// </param>
/// <returns>Invoker methods for the provided grain type.</returns>
private static MemberDeclarationSyntax[] GenerateInvokeMethods(Type grainType, Action<Type> onEncounteredType)
{
var baseReference = SF.BaseExpression();
var methods = GrainInterfaceUtils.GetMethods(grainType);
var members = new List<MemberDeclarationSyntax>();
foreach (var method in methods)
{
onEncounteredType(method.ReturnType);
var methodId = GrainInterfaceUtils.ComputeMethodId(method);
var methodIdArgument =
SF.Argument(SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(methodId)));
// Construct a new object array from all method arguments.
var parameters = method.GetParameters();
var body = new List<StatementSyntax>();
foreach (var parameter in parameters)
{
onEncounteredType(parameter.ParameterType);
if (typeof(IGrainObserver).GetTypeInfo().IsAssignableFrom(parameter.ParameterType))
{
body.Add(
SF.ExpressionStatement(
CheckGrainObserverParamInternalExpression.Invoke()
.AddArgumentListArguments(SF.Argument(parameter.Name.ToIdentifierName()))));
}
}
// Get the parameters argument value.
ExpressionSyntax args;
if (method.IsGenericMethodDefinition)
{
// Create an arguments array which includes the method's type parameters followed by the method's parameter list.
var allParameters = new List<ExpressionSyntax>();
foreach (var typeParameter in method.GetGenericArguments())
{
allParameters.Add(SF.TypeOfExpression(typeParameter.GetTypeSyntax()));
}
allParameters.AddRange(parameters.Select(GetParameterForInvocation));
args =
SF.ArrayCreationExpression(typeof(object).GetArrayTypeSyntax())
.WithInitializer(
SF.InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(allParameters.ToArray()));
}
else if (parameters.Length == 0)
{
args = SF.LiteralExpression(SyntaxKind.NullLiteralExpression);
}
else
{
args =
SF.ArrayCreationExpression(typeof(object).GetArrayTypeSyntax())
.WithInitializer(
SF.InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(parameters.Select(GetParameterForInvocation).ToArray()));
}
var options = GetInvokeOptions(method);
// Construct the invocation call.
var isOneWayTask = method.GetCustomAttribute<OneWayAttribute>() != null;
if (method.ReturnType == typeof(void) || isOneWayTask)
{
var invocation = SF.InvocationExpression(baseReference.Member("InvokeOneWayMethod"))
.AddArgumentListArguments(methodIdArgument)
.AddArgumentListArguments(SF.Argument(args));
if (options != null)
{
invocation = invocation.AddArgumentListArguments(options);
}
body.Add(SF.ExpressionStatement(invocation));
if (isOneWayTask)
{
if (method.ReturnType != typeof(Task))
{
throw new CodeGenerationException(
$"Method {grainType.GetParseableName()}.{method.Name} is marked with [{nameof(OneWayAttribute)}], " +
$"but has a return type which is not assignable from {typeof(Task)}");
}
var done = typeof(Task).GetNameSyntax(true).Member((object _) => Task.CompletedTask);
body.Add(SF.ReturnStatement(done));
}
}
else
{
var returnType = method.ReturnType == typeof(Task)
? typeof(object)
: method.ReturnType.GenericTypeArguments[0];
var invocation =
SF.InvocationExpression(baseReference.Member("InvokeMethodAsync", returnType))
.AddArgumentListArguments(methodIdArgument)
.AddArgumentListArguments(SF.Argument(args));
if (options != null)
{
invocation = invocation.AddArgumentListArguments(options);
}
ExpressionSyntax returnContent = invocation;
if (method.ReturnType.IsGenericType
&& method.ReturnType.GetGenericTypeDefinition().FullName == "System.Threading.Tasks.ValueTask`1")
{
// Wrapping invocation expression with initialization of ValueTask (e.g. new ValueTask<int>(base.InvokeMethod()))
returnContent =
SF.ObjectCreationExpression(method.ReturnType.GetTypeSyntax())
.AddArgumentListArguments(SF.Argument(SF.ExpressionStatement(invocation).Expression));
}
body.Add(SF.ReturnStatement(returnContent));
}
members.Add(method.GetDeclarationSyntax().AddBodyStatements(body.ToArray()));
}
return members.ToArray();
}
/// <summary>
/// Returns syntax for the options argument to <see cref="GrainReference.InvokeMethodAsync{T}"/> and <see cref="GrainReference.InvokeOneWayMethod"/>.
/// </summary>
/// <param name="method">The method which an invoke call is being generated for.</param>
/// <returns>
/// Argument syntax for the options argument to <see cref="GrainReference.InvokeMethodAsync{T}"/> and
/// <see cref="GrainReference.InvokeOneWayMethod"/>, or <see langword="null"/> if no options are to be specified.
/// </returns>
private static ArgumentSyntax GetInvokeOptions(MethodInfo method)
{
var options = new List<ExpressionSyntax>();
if (GrainInterfaceUtils.IsReadOnly(method))
{
options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.ReadOnly.ToString()));
}
if (GrainInterfaceUtils.IsUnordered(method))
{
options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.Unordered.ToString()));
}
if (GrainInterfaceUtils.IsAlwaysInterleave(method))
{
options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.AlwaysInterleave.ToString()));
}
if (GrainInterfaceUtils.IsNewTransactionRequired(method))
{
options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.TransactionRequiresNew.ToString()));
}
if (GrainInterfaceUtils.IsTransactionRequired(method))
{
options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.TransactionRequired.ToString()));
}
ExpressionSyntax allOptions;
if (options.Count <= 1)
{
allOptions = options.FirstOrDefault();
}
else
{
allOptions =
options.Aggregate((a, b) => SF.BinaryExpression(SyntaxKind.BitwiseOrExpression, a, b));
}
if (allOptions == null)
{
return null;
}
return SF.Argument(SF.NameColon("options"), SF.Token(SyntaxKind.None), allOptions);
}
private static ExpressionSyntax GetParameterForInvocation(ParameterInfo arg, int argIndex)
{
var argIdentifier = arg.GetOrCreateName(argIndex).ToIdentifierName();
// Addressable arguments must be converted to references before passing.
if (typeof(IAddressable).GetTypeInfo().IsAssignableFrom(arg.ParameterType)
&& arg.ParameterType.GetTypeInfo().IsInterface)
{
return
SF.ConditionalExpression(
SF.BinaryExpression(SyntaxKind.IsExpression, argIdentifier, typeof(Grain).GetTypeSyntax()),
SF.InvocationExpression(argIdentifier.Member("AsReference", arg.ParameterType)),
argIdentifier);
}
return argIdentifier;
}
private static MemberDeclarationSyntax GenerateInterfaceIdProperty(Type grainType)
{
var property = TypeUtils.Member((GrainReference _) => _.InterfaceId);
var returnValue = SF.LiteralExpression(
SyntaxKind.NumericLiteralExpression,
SF.Literal(GrainInterfaceUtils.GetGrainInterfaceId(grainType)));
return
SF.PropertyDeclaration(typeof(int).GetTypeSyntax(), property.Name)
.AddAccessorListAccessors(
SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
.AddBodyStatements(SF.ReturnStatement(returnValue)))
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.OverrideKeyword));
}
private static MemberDeclarationSyntax GenerateInterfaceVersionProperty(Type grainType)
{
var property = TypeUtils.Member((GrainReference _) => _.InterfaceVersion);
var returnValue = SF.LiteralExpression(
SyntaxKind.NumericLiteralExpression,
SF.Literal(GrainInterfaceUtils.GetGrainInterfaceVersion(grainType)));
return
SF.PropertyDeclaration(typeof(ushort).GetTypeSyntax(), property.Name)
.AddAccessorListAccessors(
SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
.AddBodyStatements(SF.ReturnStatement(returnValue)))
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.OverrideKeyword));
}
private static MemberDeclarationSyntax GenerateIsCompatibleMethod(Type grainType)
{
var method = TypeUtils.Method((GrainReference _) => _.IsCompatible(default(int)));
var methodDeclaration = method.GetDeclarationSyntax();
var interfaceIdParameter = method.GetParameters()[0].Name.ToIdentifierName();
var interfaceIds =
new HashSet<int>(
new[] { GrainInterfaceUtils.GetGrainInterfaceId(grainType) }.Concat(
GrainInterfaceUtils.GetRemoteInterfaces(grainType).Keys));
var returnValue = default(BinaryExpressionSyntax);
foreach (var interfaceId in interfaceIds)
{
var check = SF.BinaryExpression(
SyntaxKind.EqualsExpression,
interfaceIdParameter,
SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId)));
// If this is the first check, assign it, otherwise OR this check with the previous checks.
returnValue = returnValue == null
? check
: SF.BinaryExpression(SyntaxKind.LogicalOrExpression, returnValue, check);
}
return
methodDeclaration.AddBodyStatements(SF.ReturnStatement(returnValue))
.AddModifiers(SF.Token(SyntaxKind.OverrideKeyword));
}
private static MemberDeclarationSyntax GenerateInterfaceNameProperty(Type grainType)
{
var propertyName = TypeUtils.Member((GrainReference _) => _.InterfaceName);
var returnValue = grainType.GetParseableName().GetLiteralExpression();
return
SF.PropertyDeclaration(typeof(string).GetTypeSyntax(), propertyName.Name)
.AddAccessorListAccessors(
SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
.AddBodyStatements(SF.ReturnStatement(returnValue)))
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.OverrideKeyword));
}
private static MethodDeclarationSyntax GenerateGetMethodNameMethod(Type grainType)
{
var method = TypeUtils.Method((GrainReference _) => _.GetMethodName(default(int), default(int)));
var methodDeclaration =
method.GetDeclarationSyntax()
.AddModifiers(SF.Token(SyntaxKind.OverrideKeyword));
var parameters = method.GetParameters();
var interfaceIdArgument = parameters[0].Name.ToIdentifierName();
var methodIdArgument = parameters[1].Name.ToIdentifierName();
var interfaceCases = CodeGeneratorCommon.GenerateGrainInterfaceAndMethodSwitch(
grainType,
methodIdArgument,
methodType => new StatementSyntax[] { SF.ReturnStatement(methodType.Name.GetLiteralExpression()) });
// Generate the default case, which will throw a NotImplementedException.
var errorMessage = SF.BinaryExpression(
SyntaxKind.AddExpression,
"interfaceId=".GetLiteralExpression(),
interfaceIdArgument);
var throwStatement =
SF.ThrowStatement(
SF.ObjectCreationExpression(typeof(NotImplementedException).GetTypeSyntax())
.AddArgumentListArguments(SF.Argument(errorMessage)));
var defaultCase = SF.SwitchSection().AddLabels(SF.DefaultSwitchLabel()).AddStatements(throwStatement);
var interfaceIdSwitch =
SF.SwitchStatement(interfaceIdArgument).AddSections(interfaceCases.ToArray()).AddSections(defaultCase);
return methodDeclaration.AddBodyStatements(interfaceIdSwitch);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="MruSessionSecurityTokenCache.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace System.IdentityModel.Tokens
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IdentityModel.Diagnostics;
using System.IdentityModel.Tokens;
/// <summary>
/// An MRU cache (Most Recently Used).
/// </summary>
/// <remarks>
/// Thread safe. Critsec around each method.
/// A LinkedList is used to track MRU for fast purge.
/// A Dictionary is used for fast keyed lookup.
/// Grows until it reaches this.maximumSize, then purges down to this.sizeAfterPurge.
/// </remarks>
internal class MruSessionSecurityTokenCache : SessionSecurityTokenCache
{
#pragma warning disable 1591
public const int DefaultTokenCacheSize = 20000;
public static readonly TimeSpan DefaultPurgeInterval = TimeSpan.FromMinutes(15);
#pragma warning restore 1591
private DateTime nextPurgeTime = DateTime.UtcNow + DefaultPurgeInterval;
private Dictionary<SessionSecurityTokenCacheKey, CacheEntry> items;
private int maximumSize;
private CacheEntry mruEntry;
private LinkedList<SessionSecurityTokenCacheKey> mruList;
private int sizeAfterPurge;
private object syncRoot = new object();
private object purgeLock = new object();
/// <summary>
/// Constructor to create an instance of this class.
/// </summary>
/// <remarks>
/// Uses the default maximum cache size.
/// </remarks>
public MruSessionSecurityTokenCache()
: this(DefaultTokenCacheSize)
{
}
/// <summary>
/// Constructor to create an instance of this class.
/// </summary>
/// <param name="maximumSize">Defines the maximum size of the cache.</param>
public MruSessionSecurityTokenCache(int maximumSize)
: this(maximumSize, null)
{
}
/// <summary>
/// Constructor to create an instance of this class.
/// </summary>
/// <param name="maximumSize">Defines the maximum size of the cache.</param>
/// <param name="comparer">The method used for comparing cache entries.</param>
public MruSessionSecurityTokenCache(int maximumSize, IEqualityComparer<SessionSecurityTokenCacheKey> comparer)
: this((maximumSize / 5) * 4, maximumSize, comparer)
{
}
/// <summary>
/// Constructor to create an instance of this class.
/// </summary>
/// <param name="sizeAfterPurge">
/// If the cache size exceeds <paramref name="maximumSize"/>,
/// the cache will be resized to <paramref name="sizeAfterPurge"/> by removing least recently used items.
/// </param>
/// <param name="maximumSize">Defines the maximum size of the cache.</param>
public MruSessionSecurityTokenCache(int sizeAfterPurge, int maximumSize)
: this(sizeAfterPurge, maximumSize, null)
{
}
/// <summary>
/// Constructor to create an instance of this class.
/// </summary>
/// <param name="sizeAfterPurge">Specifies the size to which the cache is purged after it reaches <paramref name="maximumSize"/>.</param>
/// <param name="maximumSize">Specifies the maximum size of the cache.</param>
/// <param name="comparer">Specifies the method used for comparing cache entries.</param>
public MruSessionSecurityTokenCache(int sizeAfterPurge, int maximumSize, IEqualityComparer<SessionSecurityTokenCacheKey> comparer)
{
if (sizeAfterPurge < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ID0008), "sizeAfterPurge"));
}
if (sizeAfterPurge >= maximumSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ID0009), "sizeAfterPurge"));
}
// null comparer is ok
this.items = new Dictionary<SessionSecurityTokenCacheKey, CacheEntry>(maximumSize, comparer);
this.maximumSize = maximumSize;
this.mruList = new LinkedList<SessionSecurityTokenCacheKey>();
this.sizeAfterPurge = sizeAfterPurge;
this.mruEntry = new CacheEntry();
}
/// <summary>
/// Gets the maximum size of the cache
/// </summary>
public int MaximumSize
{
get { return this.maximumSize; }
}
/// <summary>
/// Deletes the specified cache entry from the MruCache.
/// </summary>
/// <param name="key">Specifies the key for the entry to be deleted.</param>
/// <exception cref="ArgumentNullException">The <paramref name="key"/> is null.</exception>
public override void Remove(SessionSecurityTokenCacheKey key)
{
if (key == null)
{
return;
}
lock (this.syncRoot)
{
CacheEntry entry;
if (this.items.TryGetValue(key, out entry))
{
this.items.Remove(key);
this.mruList.Remove(entry.Node);
if (object.ReferenceEquals(this.mruEntry.Node, entry.Node))
{
this.mruEntry.Value = null;
this.mruEntry.Node = null;
}
}
}
}
/// <summary>
/// Attempts to add an entry to the cache or update an existing one.
/// </summary>
/// <param name="key">The key for the entry to be added.</param>
/// <param name="value">The security token to be added to the cache.</param>
/// <param name="expirationTime">The expiration time for this entry.</param>
public override void AddOrUpdate(SessionSecurityTokenCacheKey key, SessionSecurityToken value, DateTime expirationTime)
{
if (key == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key");
}
lock (this.syncRoot)
{
this.Purge();
this.Remove(key);
// Add the new entry to the cache and make it the MRU element
CacheEntry entry = new CacheEntry();
entry.Node = this.mruList.AddFirst(key);
entry.Value = value;
this.items.Add(key, entry);
this.mruEntry = entry;
}
}
/// <summary>
/// Returns the Session Security Token corresponding to the specified key exists in the cache. Also if it exists, marks it as MRU.
/// </summary>
/// <param name="key">Specifies the key for the entry to be retrieved.</param>
/// <returns>Returns the Session Security Token from the cache if found, otherwise, null.</returns>
public override SessionSecurityToken Get(SessionSecurityTokenCacheKey key)
{
if (key == null)
{
return null;
}
// If found, make the entry most recently used
SessionSecurityToken sessionToken = null;
CacheEntry entry;
bool found;
lock (this.syncRoot)
{
// first check our MRU item
if (this.mruEntry.Node != null && key != null && key.Equals(this.mruEntry.Node.Value))
{
return this.mruEntry.Value;
}
found = this.items.TryGetValue(key, out entry);
if (found)
{
sessionToken = entry.Value;
// Move the node to the head of the MRU list if it's not already there
if (this.mruList.Count > 1 && !object.ReferenceEquals(this.mruList.First, entry.Node))
{
this.mruList.Remove(entry.Node);
this.mruList.AddFirst(entry.Node);
this.mruEntry = entry;
}
}
}
return sessionToken;
}
/// <summary>
/// Deletes matching cache entries from the MruCache.
/// </summary>
/// <param name="endpointId">Specifies the endpointId for the entries to be deleted.</param>
/// <param name="contextId">Specifies the contextId for the entries to be deleted.</param>
public override void RemoveAll(string endpointId, System.Xml.UniqueId contextId)
{
if (null == contextId || string.IsNullOrEmpty(endpointId))
{
return;
}
Dictionary<SessionSecurityTokenCacheKey, CacheEntry> entriesToDelete = new Dictionary<SessionSecurityTokenCacheKey, CacheEntry>();
SessionSecurityTokenCacheKey key = new SessionSecurityTokenCacheKey(endpointId, contextId, null);
key.IgnoreKeyGeneration = true;
lock (this.syncRoot)
{
foreach (SessionSecurityTokenCacheKey itemKey in this.items.Keys)
{
if (itemKey.Equals(key))
{
entriesToDelete.Add(itemKey, this.items[itemKey]);
}
}
foreach (SessionSecurityTokenCacheKey itemKey in entriesToDelete.Keys)
{
this.items.Remove(itemKey);
CacheEntry entry = entriesToDelete[itemKey];
this.mruList.Remove(entry.Node);
if (object.ReferenceEquals(this.mruEntry.Node, entry.Node))
{
this.mruEntry.Value = null;
this.mruEntry.Node = null;
}
}
}
}
/// <summary>
/// Attempts to remove all entries with a matching endpoint Id from the cache.
/// </summary>
/// <param name="endpointId">The endpoint id for the entry to be removed.</param>
public override void RemoveAll(string endpointId)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException(SR.GetString(SR.ID4294)));
}
/// <summary>
/// Returns all the entries that match the given key.
/// </summary>
/// <param name="endpointId">The endpoint id for the entries to be retrieved.</param>
/// <param name="contextId">The context id for the entries to be retrieved.</param>
/// <returns>A collection of all the matching entries, an empty collection of no match found.</returns>
public override IEnumerable<SessionSecurityToken> GetAll(string endpointId, System.Xml.UniqueId contextId)
{
Collection<SessionSecurityToken> tokens = new Collection<SessionSecurityToken>();
if (null == contextId || string.IsNullOrEmpty(endpointId))
{
return tokens;
}
CacheEntry entry;
SessionSecurityTokenCacheKey key = new SessionSecurityTokenCacheKey(endpointId, contextId, null);
key.IgnoreKeyGeneration = true;
lock (this.syncRoot)
{
foreach (SessionSecurityTokenCacheKey itemKey in this.items.Keys)
{
if (itemKey.Equals(key))
{
entry = this.items[itemKey];
// Move the node to the head of the MRU list if it's not already there
if (this.mruList.Count > 1 && !object.ReferenceEquals(this.mruList.First, entry.Node))
{
this.mruList.Remove(entry.Node);
this.mruList.AddFirst(entry.Node);
this.mruEntry = entry;
}
tokens.Add(entry.Value);
}
}
}
return tokens;
}
/// <summary>
/// This method must not be called from within a read or writer lock as a deadlock will occur.
/// Checks the time a decides if a cleanup needs to occur.
/// </summary>
private void Purge()
{
if (this.items.Count >= this.maximumSize)
{
// If the cache is full, purge enough LRU items to shrink the
// cache down to the low watermark
int countToPurge = this.maximumSize - this.sizeAfterPurge;
for (int i = 0; i < countToPurge; i++)
{
SessionSecurityTokenCacheKey keyRemove = this.mruList.Last.Value;
this.mruList.RemoveLast();
this.items.Remove(keyRemove);
}
if (DiagnosticUtility.ShouldTrace(TraceEventType.Information))
{
TraceUtility.TraceString(
TraceEventType.Information,
SR.GetString(
SR.ID8003,
this.maximumSize,
this.sizeAfterPurge));
}
}
}
public class CacheEntry
{
public SessionSecurityToken Value
{
get;
set;
}
public LinkedListNode<SessionSecurityTokenCacheKey> Node
{
get;
set;
}
}
}
}
| |
// Copyright 2021 Esri.
//
// 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 Android.App;
using Android.OS;
using Android.Widget;
using ArcGISRuntime.Samples.Managers;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks;
using Esri.ArcGISRuntime.Tasks.Offline;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArcGISRuntimeXamarin.Samples.OfflineBasemapByReference
{
[Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Generate offline map with local basemap",
category: "Map",
description: "Use the `OfflineMapTask` to take a web map offline, but instead of downloading an online basemap, use one which is already on the device.",
instructions: "1. Use the button to start taking the map offline.",
tags: new[] { "basemap", "download", "local", "offline", "save", "web map" })]
[ArcGISRuntime.Samples.Shared.Attributes.OfflineData("628e8e3521cf45e9a28a12fe10c02c4d")]
public class OfflineBasemapByReference : Activity
{
// Hold references to the UI controls.
private MapView _mapView;
private AlertDialog _alertDialog;
private ProgressBar _progressIndicator;
private Button _takeMapOfflineButton;
// The job to generate an offline map.
private GenerateOfflineMapJob _generateOfflineMapJob;
// The extent of the data to take offline.
private readonly Envelope _areaOfInterest = new Envelope(-88.1541, 41.7690, -88.1471, 41.7720, SpatialReferences.Wgs84);
// The ID for a web map item hosted on the server (water network map of Naperville IL).
private const string WebMapId = "acc027394bc84c2fb04d1ed317aac674";
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Generate offline map with local basemap";
CreateLayout();
Initialize();
}
private void ConfigureOfflineJobForBasemap(GenerateOfflineMapParameters parameters, Action completionHandler)
{
// Don't give the user a choice if there is no basemap specified.
if (string.IsNullOrWhiteSpace(parameters.ReferenceBasemapFilename))
{
return;
}
// Get the path to the basemap directory.
string basemapBasePath = DataManager.GetDataFolder("85282f2aaa2844d8935cdb8722e22a93");
// Get the full path to the basemap by combining the name specified in the web map (ReferenceBasemapFilename)
// with the offline basemap directory.
string basemapFullPath = Path.Combine(basemapBasePath, parameters.ReferenceBasemapFilename);
// If the offline basemap doesn't exist, proceed without it.
if (!File.Exists(basemapFullPath))
{
return;
}
// Create the dialog for getting the user's choice.
AlertDialog.Builder basemapAlert = new AlertDialog.Builder(this).SetMessage("Use the offline basemap?").SetTitle("Basemap choice");
// Add the 'yes' choice. When the user selects it, the basemap directory will be set and the job will continue.
basemapAlert = basemapAlert.SetPositiveButton("Yes", (o, e) =>
{
parameters.ReferenceBasemapDirectory = basemapBasePath;
completionHandler.Invoke();
});
// Add the 'no' choice. When the user selects it, the job will continue using the online map.
basemapAlert = basemapAlert.SetNegativeButton("No", (o, e) => completionHandler.Invoke());
// Show the dialog.
basemapAlert.Show();
}
// Note: all code below (except call to ConfigureOfflineJobForBasemap) is identical to code in the Generate offline map sample.
#region Generate offline map
private async void Initialize()
{
try
{
// Create the ArcGIS Online portal.
ArcGISPortal portal = await ArcGISPortal.CreateAsync();
// Get the Naperville water web map item using its ID.
PortalItem webmapItem = await PortalItem.CreateAsync(portal, WebMapId);
// Create a map from the web map item.
Map onlineMap = new Map(webmapItem);
// Display the map in the MapView.
_mapView.Map = onlineMap;
// Disable user interactions on the map (no panning or zooming from the initial extent).
_mapView.InteractionOptions = new MapViewInteractionOptions
{
IsEnabled = false
};
// Create a graphics overlay for the extent graphic and apply a renderer.
SimpleLineSymbol aoiOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Red, 3);
GraphicsOverlay extentOverlay = new GraphicsOverlay
{
Renderer = new SimpleRenderer(aoiOutlineSymbol)
};
_mapView.GraphicsOverlays.Add(extentOverlay);
// Add a graphic to show the area of interest (extent) that will be taken offline.
Graphic aoiGraphic = new Graphic(_areaOfInterest);
extentOverlay.Graphics.Add(aoiGraphic);
}
catch (Exception ex)
{
// Show the exception message to the user.
ShowStatusMessage(ex.Message);
}
}
private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
{
// Create a path for the output mobile map.
string tempPath = $"{Path.GetTempPath()}";
string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");
// Loop through the folder names and delete them.
foreach (string dir in outputFolders)
{
try
{
// Delete the folder.
Directory.Delete(dir, true);
}
catch (Exception)
{
// Ignore exceptions (files might be locked, for example).
}
}
// Create a new folder for the output mobile map.
string packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
int num = 1;
while (Directory.Exists(packagePath))
{
packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num.ToString());
num++;
}
// Create the output directory.
Directory.CreateDirectory(packagePath);
// Show the progress dialog while the job is running.
_alertDialog.Show();
// Create an offline map task with the current (online) map.
OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(_mapView.Map);
// Create the default parameters for the task, pass in the area of interest.
GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);
// Configure basemap settings for the job.
ConfigureOfflineJobForBasemap(parameters, async () =>
{
try
{
// Create the job with the parameters and output location.
_generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath);
// Handle the progress changed event for the job.
_generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;
// Await the job to generate geodatabases, export tile packages, and create the mobile map package.
GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();
// Check for job failure (writing the output was denied, e.g.).
if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
{
// Report failure to the user.
ShowStatusMessage("Failed to take the map offline.");
}
// Check for errors with individual layers.
if (results.LayerErrors.Any())
{
// Build a string to show all layer errors.
StringBuilder errorBuilder = new StringBuilder();
foreach (KeyValuePair<Layer, Exception> layerError in results.LayerErrors)
{
errorBuilder.AppendLine($"{layerError.Key.Id} : {layerError.Value.Message}");
}
// Show layer errors.
ShowStatusMessage(errorBuilder.ToString());
}
// Display the offline map.
_mapView.Map = results.OfflineMap;
// Apply the original viewpoint for the offline map.
_mapView.SetViewpoint(new Viewpoint(_areaOfInterest));
// Enable map interaction so the user can explore the offline data.
_mapView.InteractionOptions.IsEnabled = true;
// Change the title and disable the "Take map offline" button.
_takeMapOfflineButton.Text = "Map is offline";
_takeMapOfflineButton.Enabled = false;
}
catch (TaskCanceledException)
{
// Generate offline map task was canceled.
ShowStatusMessage("Taking map offline was canceled");
}
catch (Exception ex)
{
// Exception while taking the map offline.
ShowStatusMessage(ex.Message);
}
finally
{
// Hide the loading overlay when the job is done.
_alertDialog.Dismiss();
}
});
}
private void ShowStatusMessage(string message)
{
// Display the message to the user.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.SetMessage(message).SetTitle("Alert").Show();
}
// Show changes in job progress.
private void OfflineMapJob_ProgressChanged(object sender, EventArgs e)
{
// Get the job.
GenerateOfflineMapJob job = sender as GenerateOfflineMapJob;
// Dispatch to the UI thread.
RunOnUiThread(() =>
{
// Show the percent complete and update the progress bar.
string percentText = job.Progress > 0 ? job.Progress.ToString() + " %" : string.Empty;
_progressIndicator.Progress = job.Progress;
_alertDialog.SetMessage($"Taking map offline ({percentText}) ...");
});
}
private void CreateLayout()
{
// Create the layout.
LinearLayout layout = new LinearLayout(this)
{
Orientation = Orientation.Vertical
};
// Add the generate button.
_takeMapOfflineButton = new Button(this)
{
Text = "Take map offline"
};
_takeMapOfflineButton.Click += TakeMapOfflineButton_Click;
layout.AddView(_takeMapOfflineButton);
// Add the MapView.
_mapView = new MapView(this);
layout.AddView(_mapView);
// Add the layout to the view.
SetContentView(layout);
// Create the progress dialog display.
_progressIndicator = new ProgressBar(this);
_progressIndicator.SetProgress(40, true);
AlertDialog.Builder builder = new AlertDialog.Builder(this).SetView(_progressIndicator);
builder.SetCancelable(true);
builder.SetMessage("Generating offline map ...");
_alertDialog = builder.Create();
_alertDialog.SetButton("Cancel", (s, e) => { _generateOfflineMapJob?.Cancel(); });
}
#endregion Generate offline map
}
}
| |
// Author: http://lemming.life
// Language: C#
// Description: Collection of classes related to string operations.
using System;
using System.Text;
using System.Collections.Generic;
namespace Snippets {
class StringOperations {
public static void executeDriver() {
Console.WriteLine("\nTEST: String Operations");
Console.WriteLine("\nSubTest: Reverse");
Reverse.executeDriver();
Console.WriteLine("\nSubTest: Palindrome");
Palindrome.executeDriver();
Console.WriteLine("\nSubTest: UrlParser");
UrlParser.executeDriver();
Console.WriteLine("\nSubTest: IsWellFormed1");
IsWellFormed1.executeDriver();
Console.WriteLine("\nSubTest: IsWellFormed2");
IsWellFormed2.executeDriver();
}
public class Reverse {
// Purpose: Reverses strings and integers.
public static string reverseStr(string s) {
StringBuilder reversed = new StringBuilder();
for (int i = s.Length-1; i > -1; --i) {
reversed.Append(s[i]);
}
return reversed.ToString();
}
public static int reverseInt(int n) {
int reversed;
Int32.TryParse(reverseStr(n.ToString()), out reversed);
return reversed;
}
public static void executeDriver() {
string str = "Hello, World";
Console.WriteLine("The reverse of '{0}' is '{1}'", str, reverseStr(str));
int n = 12345;
Console.WriteLine("The reverse of {0} is {1}", n, reverseInt(n));
}
} // End class Reverse
public class Palindrome {
// Purpose: Given a string determine if it is a palindrome.
public static bool isPalindrome(string line) {
for (int i=0; i < line.Length/2; ++i) {
if (line[i] != line[line.Length - (i+1)]) {
return false;
}
}
return true;
}
public static void executeDriver() {
string line = "hello";
Console.WriteLine("Is {0} a palindrome? {1}", line, isPalindrome(line));
line = "101";
Console.WriteLine("Is {0} a palindrome? {1}", line, isPalindrome(line));
line = "aabbaa";
Console.WriteLine("Is {0} a palindrome? {1}", line, isPalindrome(line));
}
} // End class Palindrome
public class UrlParser {
// Description : Given a url extract the protocol, domain, and query string.
static string getProtocol(string url) {
string lookFor = "://";
int indexOf = url.IndexOf(lookFor);
return url.Substring(0, indexOf);
}
static string getDomain(string url) {
string lookFor1 = "://";
string lookFor2 = "/";
int indexOf1 = url.IndexOf(lookFor1) + lookFor1.Length;
url = url.Substring(indexOf1, url.Length - indexOf1);
int indexOf2 = url.IndexOf(lookFor2);
return url.Substring(0, indexOf2);
}
static string getQuery(string url, bool path = false) {
string lookFor = path ? getDomain(url) + "/" : "/";
int indexOf = lookFor.Length + (path ? url.IndexOf(lookFor) : url.LastIndexOf(lookFor));
return url.Substring(indexOf, url.Length - indexOf);
}
static string getQueryWithQuestionMark(string url) {
string lookFor = "?";
int indexOf = url.IndexOf(lookFor);
if (indexOf == -1) {return "";}
++indexOf;
return url.Substring(indexOf, url.Length - indexOf);
}
public static void executeDriver() {
string url = "http://google.com/theQuery123";
Console.WriteLine("Url is: " + url);
Console.WriteLine("Protocol: " + getProtocol(url));
Console.WriteLine("Domain: " + getDomain(url));
Console.WriteLine("Query no path: " + getQuery(url, false));
Console.WriteLine("Query with path: " + getQuery(url, true));
url = "http://google.com/some/stuff/in/between/theQuery123";
Console.WriteLine("\nUrl is: " + url);
Console.WriteLine("Protocol: " + getProtocol(url));
Console.WriteLine("Domain: " + getDomain(url));
Console.WriteLine("Query no path: " + getQuery(url, false));
Console.WriteLine("Query with path: " + getQuery(url, true));
url = "http://www.somewebsitewithnoqueryline.com/index.html";
Console.WriteLine("\nUrl is: " + url);
Console.WriteLine("Protocol: " + getProtocol(url));
Console.WriteLine("Domain: " + getDomain(url));
Console.WriteLine("Query?: " + getQueryWithQuestionMark(url));
url = "http://www.somewebsitewithquestionmarkquery.com/index.html?aquery=123";
Console.WriteLine("\nUrl is: " + url);
Console.WriteLine("Protocol: " + getProtocol(url));
Console.WriteLine("Domain: " + getDomain(url));
Console.WriteLine("Query?: " + getQueryWithQuestionMark(url));
}
} // End class UrlParser
public class IsWellFormed1 {
// Considers only strings that have characters: (,),{,},[,]
// Example1: () is well formed
// Example2: ([}) is not well formed.
public static void executeDriver() {
string line = "()";
Console.WriteLine("Is {0} well formed? {1}", line, isWellFormed(line));
line = "([)]";
Console.WriteLine("Is {0} well formed? {1}", line, isWellFormed(line));
}
public static bool isWellFormed(string line) {
if (line.Length % 2 != 0) { return false; }
for (int i=0; i<line.Length/2; ++i) {
if (line[i] != oppositeChar( line[line.Length - (1+i)]) ) {
return false;
}
}
return true;
}
private static char oppositeChar(char aChar) {
if (aChar == '(') return ')';
if (aChar == '{') return '}';
if (aChar == '[') return ']';
if (aChar == ')') return '(';
if (aChar == '}') return '{';
if (aChar == ']') return '[';
return ' ';
}
} // End class IsWellFormed1
public class IsWellFormed2 {
// Considers strings that have (,),{,},[,]
// but also characters in between those.
// Example1: (hello) is well formed.
// Example2: (he[llo]) is well formed.
// Example3: (he[llo) is not well formed.
// Example4: hell}o is not well formed.
public static void executeDriver() {
string line;
line = "hello";
Console.WriteLine("Is {0} well formed? {1}", line, isWellFormed(line)); // true
line = "(hello)";
Console.WriteLine("Is {0} well formed? {1}", line, isWellFormed(line)); // true
line = "(he[llo])";
Console.WriteLine("Is {0} well formed? {1}", line, isWellFormed(line)); // true
line = "hell{}";
Console.WriteLine("Is {0} well formed? {1}", line, isWellFormed(line)); // true
line = "(he[llo)";
Console.WriteLine("Is {0} well formed? {1}", line, isWellFormed(line)); // false
line = "hell}o";
Console.WriteLine("Is {0} well formed? {1}", line, isWellFormed(line)); // false
line = "]hello";
Console.WriteLine("Is {0} well formed? {1}", line, isWellFormed(line)); // false
line = "he(ll]o";
Console.WriteLine("Is {0} well formed? {1}", line, isWellFormed(line)); // false
}
public static bool isWellFormed(string line) {
Stack<char> charStack = new Stack<char>();
foreach (var c in line) {
if ( !isBracketType(c) ) { continue; }
if (isCharOpener(c)) {
charStack.Push(c);
} else {
if (charStack.Count == 0) return false;
if (c == oppositeChar(charStack.Peek())) {
charStack.Pop();
} else {
return false;
}
}
}
if (charStack.Count>0) { return false;}
return true;
}
private static bool isBracketType(char aChar) {
if (aChar == '(') return true;
if (aChar == '{') return true;
if (aChar == '[') return true;
if (aChar == ')') return true;
if (aChar == '}') return true;
if (aChar == ']') return true;
return false;
}
private static bool isCharOpener(char aChar) {
if (aChar == '(') return true;
if (aChar == '{') return true;
if (aChar == '[') return true;
return false;
}
private static char oppositeChar(char aChar) {
if (aChar == '(') return ')';
if (aChar == '{') return '}';
if (aChar == '[') return ']';
if (aChar == ')') return '(';
if (aChar == '}') return '{';
if (aChar == ']') return '[';
return ' ';
}
}
} // End class StringOperations
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SpatialAnalysis.Interoperability;
using System.Windows;
using SpatialAnalysis.Miscellaneous;
namespace SpatialAnalysis.Geometry
{
/// <summary>
/// Class PLine.
/// </summary>
public class PLine
{
private UVComparer _comparer { get; set; }
/// <summary>
/// Gets the point count.
/// </summary>
/// <value>The point count.</value>
public int PointCount { get { return this._pntList.Count; } }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="PLine"/> is closed.
/// </summary>
/// <value><c>true</c> if closed; otherwise, <c>false</c>.</value>
public bool Closed { get; set; }
private HashSet<UV> _pntSet { get; set; }
private List<UV> _pntList;
/// <summary>
/// Gets the points.
/// </summary>
/// <value>The points.</value>
public List<UV> Points
{
get { return this._pntList; }
}
private UV _start;
/// <summary>
/// Gets the start point of the polygon.
/// </summary>
/// <value>The start.</value>
public UV Start
{
get { return this._start; }
}
private UV _end;
/// <summary>
/// Gets the end point of the polygon.
/// </summary>
/// <value>The end.</value>
public UV End
{
get { return this._end; }
}
/// <summary>
/// Initializes a new instance of the <see cref="PLine"/> class.
/// </summary>
/// <param name="line">A line to start with.</param>
/// <param name="numberOfFractionalDigits">The number of fractional digits used as the tolerance of equality.</param>
/// <exception cref="ArgumentException">Line length is zero</exception>
public PLine(UVLine line, int numberOfFractionalDigits = 5, double tolerance = OSMDocument.AbsoluteTolerance)
{
if (line.End == line.Start)
{
throw new ArgumentException("Line length is zero");
}
this._end = line.End;
this._start = line.Start;
this._pntList = new List<UV>()
{
this._start,
this._end,
};
this._comparer = new UVComparer(numberOfFractionalDigits, tolerance);
this._pntSet = new HashSet<UV>(this._comparer)
{
this._end,
this._start
};
this.Closed = false;
}
/// <summary>
/// Initializes a new instance of the <see cref="PLine"/> class.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="closed">if set to <c>true</c> [closed].</param>
/// <param name="numberOfFractionalDigits">The number of fractional digits used as the tolerance of equality.</param>
/// <exception cref="ArgumentException">Points are duplicated</exception>
public PLine(List<UV> points, bool closed, int numberOfFractionalDigits = 5, double tolerance = OSMDocument.AbsoluteTolerance)
{
this._end = points[points.Count - 1];
this._start = points[0];
this._pntList = points;
this._comparer = new UVComparer(numberOfFractionalDigits, tolerance);
this._pntSet = new HashSet<UV>(this._comparer);
foreach (var item in this._pntList)
{
if (this._pntSet.Contains(item))
{
throw new ArgumentException("Points are duplicated");
}
else
{
this._pntSet.Add(item);
}
}
this.Closed = closed;
}
/// <summary>
/// Initializes a new instance of the <see cref="PLine"/> class. This method does not include any rounding to test equality!
/// </summary>
/// <param name="points">The points.</param>
/// <param name="closed">if set to <c>true</c> the polyline is closed.</param>
/// <exception cref="ArgumentException">Points are duplicated</exception>
//public PLine(List<UV> points, bool closed)
//{
// this._end = points[points.Count - 1];
// this._start = points[0];
// this._pntList = points;
// this._pntSet = new HashSet<UV>();//(new UVComparer(fractionalDigits));
// foreach (var item in this._pntList)
// {
// if (this._pntSet.Contains(item))
// {
// throw new ArgumentException("Points are duplicated");
// }
// else
// {
// this._pntSet.Add(item);
// }
// }
// this.Closed = closed;
//}
/// <summary>
/// Determines whether this instance is convex.
/// </summary>
/// <returns><c>true</c> if this instance is convex; otherwise, <c>false</c>.</returns>
public bool IsConvex()
{
return BarrierPolygon.IsConvex(this._pntList.ToArray());
}
/// <summary>
/// Splits the polygon to a list of points at given distances.
/// </summary>
/// <param name="length">The length.</param>
/// <returns>List<UV>.</returns>
public List<UV> SplitToPoints(double length)
{
List<UV> pnts = new List<UV>();
pnts.Add(this.Start);
double totalLength = 0;
double u = 0;
for (int i = 0; i < this.PointCount; i++)
{
int j = (i == this.PointCount - 1) ? 0 : i + 1;
if (!this.Closed && j == 0)
{
break;
}
UV vector = this.Points[j] - this.Points[i];
double dist = vector.GetLength();
vector /= dist;
while (u < totalLength + dist)
{
pnts.Add(this.Points[i] + (u - totalLength) * vector);
u += length;
}
totalLength += dist;
}
if (this.End != pnts[pnts.Count - 1] && !this.Closed)
{
pnts.Add(this.End);
}
UV current = pnts[0];
List<UV> pnts2 = new List<UV>() { current };
for (int i = 0; i < pnts.Count; i++)
{
if (pnts[i] != current)
{
current = pnts[i];
pnts2.Add(current);
}
}
pnts.Clear();
pnts = null;
return pnts2;
}
/// <summary>
/// Splits this polyline to a list of polylines with equal lengths
/// </summary>
/// <param name="length">The length.</param>
/// <param name="tolerance">The tolerance by default set to main documents absolute tolerance.</param>
/// <returns>List<PLine>.</returns>
public List<PLine> SplitToPLines(double length, double tolerance = OSMDocument.AbsoluteTolerance)
{
List<int> indexes = new List<int>() { 0 };
List<UV> pnts = new List<UV>();
double totalLength = 0;
double u = length;
for (int i = 0; i < this.PointCount; i++)
{
pnts.Add(this.Points[i]);
//indexes.Add(pnts.Count - 1);
int j = (i == this.PointCount - 1) ? 0 : i + 1;
if (!this.Closed && j == 0)
{
break;
}
UV vector = this.Points[j] - this.Points[i];
double dist = vector.GetLength();
vector /= dist;
while (u < totalLength + dist)
{
var p = this.Points[i] + (u - totalLength) * vector;
if (!this._pntSet.Contains(p))
{
pnts.Add(p);
}
indexes.Add(pnts.Count - 1);
u += length;
}
totalLength += dist;
}
if (this.Closed)
{
if (this.Start != pnts[pnts.Count - 1])
{
pnts.Add(this.Start);
}
indexes.Add(pnts.Count - 1);
}
else
{
if (this.End != pnts[pnts.Count - 1])
{
pnts.Add(this.End);
}
indexes.Add(pnts.Count - 1);
}
List<PLine> plines = new List<PLine>();
if (indexes.Count == 2)
{
plines.Add(this);
}
for (int i = 0; i < indexes.Count - 1; i++)
{
var points = pnts.GetRange(indexes[i], indexes[i + 1] - indexes[i] + 1);
if (points[0].DistanceTo(points[1]) < tolerance)
{
points.RemoveAt(1);
}
if (points.Count > 1)
{
if (points[points.Count - 1].DistanceTo(points[points.Count - 2]) < tolerance)
{
points.RemoveAt(points.Count - 2);
}
if (points.Count > 1)
{
PLine pline = new PLine(points, false);
plines.Add(pline);
}
}
}
return plines;
}
/// <summary>
/// Gets the length of this polygon.
/// </summary>
/// <returns>System.Double.</returns>
public double GetLength()
{
double length = 0;
for (int i = 0; i < this.Points.Count - 1; i++)
{
length += UV.GetDistanceBetween(this.Points[i], this.Points[i + 1]);
}
if (this.Closed)
{
length += UV.GetDistanceBetween(this.Start, this.End);
}
return length;
}
private void addStart(UV pnt)
{
this._start = pnt;
this._pntList.Insert(0, pnt);
this._pntSet.Add(pnt);
}
private void addEnd(UV pnt)
{
this._end = pnt;
this._pntList.Add(pnt);
this._pntSet.Add(pnt);
}
private bool addSegment(UVLine line)
{
try
{
if (this.Closed)
{
return false;
}
else
{
if (this._pntSet.Contains(line.Start) && this._pntSet.Contains(line.End))
{
if (this._comparer.Equals(this._start, line.Start) && this._comparer.Equals(this._end, line.End))
{
this.Closed = true;
return true;
}
else if (this._comparer.Equals(this._start, line.End) && this._comparer.Equals(this._end, line.Start))
{
this.Closed = true;
return true;
}
else
{
/*
StringBuilder sb = new StringBuilder();
sb.AppendLine("POINTS:");
foreach (var item in this._pntList)
{
sb.AppendLine(item.ToString());
}
sb.AppendLine("\nAdded Line:");
sb.AppendLine(line.Start.ToString());
sb.AppendLine(line.End.ToString());
MessageBox.Show(sb.ToString());
sb.Clear();
sb = null;
throw new ArgumentException("Self intersection");
*/
}
}
if (this._comparer.Equals(this._start, line.Start))
{
this.addStart(line.End);
return true;
}
if (this._comparer.Equals(this._start, line.End))
{
this.addStart(line.Start);
return true;
}
if (this._comparer.Equals(this._end, line.End))
{
this.addEnd(line.Start);
return true;
}
if (this._comparer.Equals(this._end, line.Start))
{
this.addEnd(line.End);
return true;
}
}
return false;
}
catch (Exception e)
{
MessageBox.Show(e.Report());
}
return false;
}
/// <summary>
/// Visualizes this polygon at the BIM environment
/// </summary>
/// <param name="visualizer">The visualizer.</param>
/// <param name="elevation">The elevation.</param>
public void Visualize(I_OSM_To_BIM visualizer, double elevation = 0)
{
List<UVLine> lines = new List<UVLine>();
for (int i = 0; i < this.PointCount - 1; i++)
{
lines.Add(new UVLine(this._pntList[i], this._pntList[i + 1]));
}
if (this.Closed)
{
lines.Add(new UVLine(this._end, this._start));
}
visualizer.VisualizeLines(lines, elevation);
}
/// <summary>
/// Converts this polyline to a list of lines.
/// </summary>
/// <returns>List<UVLine>.</returns>
public List<UVLine> ToLines()
{
List<UVLine> lines = new List<UVLine>();
for (int i = 0; i < this.PointCount - 1; i++)
{
lines.Add(new UVLine(this._pntList[i], this._pntList[i + 1]));
}
if (this.Closed)
{
lines.Add(new UVLine(this._pntList[this.PointCount - 1], this._pntList[0]));
}
return lines;
}
/// <summary>
/// Copies this instance deeply.
/// </summary>
/// <returns>PLine.</returns>
public PLine Copy()
{
PLine pline = new PLine(new UVLine(this._pntList[0].Copy(), this._pntList[1].Copy()));
for (int i = 2; i < this.PointCount; i++)
{
pline.addEnd(this._pntList[i].Copy());
}
pline.Closed = this.Closed;
return pline;
}
/// <summary>
/// Simplifies this polygon.
/// </summary>
/// <param name="distance">The distance tolerance.</param>
/// <param name="angle">The angle tolerance.</param>
/// <returns>List<UV>.</returns>
/// <exception cref="ArgumentException">Heap cannot remove the found end point</exception>
public List<UV> Simplify(double distance, double angle = .0001)
{
double distanceTolerance = distance * distance;
double sine = Math.Sin(angle * Math.PI / 180);
double angleTolerance = sine * sine;
SortedSet<PLNode> heap = new SortedSet<PLNode>(new PLNodeComparer(distanceTolerance));
PLNode[] allNodes = new PLNode[this.PointCount];
for (int i = 0; i < allNodes.Length; i++)
{
allNodes[i] = new PLNode(this._pntList[i]);
}
if (this.Closed)
{
for (int i = 0; i < allNodes.Length; i++)
{
int i0 = (i == 0) ? allNodes.Length - 1 : i - 1;
int i1 = (i == allNodes.Length - 1) ? 0 : i + 1;
allNodes[i].AddConnection(allNodes[i0]);
allNodes[i].AddConnection(allNodes[i1]);
allNodes[i].LoadFactors();
if (heap.Contains(allNodes[i]))
{
allNodes[i].Remained = false;
// this sucks. Although the polyline does not have equal points, there are
// points that are so close that their distance squared is zero! Damn it.
// this meains the heap should be reconstructed because removing one node
// breaks the connection! I have to make sure that each node is connected
// to the neighbors that exist in the heap
}
else
{
heap.Add(allNodes[i]);
}
}
if (heap.Count < this.PointCount) // reconstructing the heap
{
PLNode[] newNodes = new PLNode[heap.Count];
int k = 0;
for (int i = 0; i < this.PointCount; i++)
{
if (allNodes[i].Remained)
{
newNodes[k] = new PLNode(allNodes[i].Point);
k++;
}
}
heap.Clear();
allNodes = newNodes;
for (int i = 0; i < allNodes.Length; i++)
{
int i0 = (i == 0) ? allNodes.Length - 1 : i - 1;
int i1 = (i == allNodes.Length - 1) ? 0 : i + 1;
allNodes[i].AddConnection(allNodes[i0]);
allNodes[i].AddConnection(allNodes[i1]);
allNodes[i].LoadFactors();
heap.Add(allNodes[i]);
}
}
}
else
{
for (int i = 0; i < allNodes.Length; i++)
{
if (i > 0)
{
allNodes[i].AddConnection(allNodes[i - 1]);
}
if (i < allNodes.Length - 1)
{
allNodes[i].AddConnection(allNodes[i + 1]);
}
allNodes[i].LoadFactors();
if (heap.Contains(allNodes[i]))
{
allNodes[i].Remained = false;
// this sucks. Although the polyline does not have equal points, there are
// points that are so close that their distance squared is zero! Damn it.
// this meains the heap should be reconstructed because removing one node
// breaks the connection! I have to make sure that each node is connected
// to the neighbors that exist in the heap
}
else
{
heap.Add(allNodes[i]);
}
}
if (heap.Count < this.PointCount) // reconstructing the heap
{
PLNode[] newNodes = new PLNode[heap.Count];
int k = 0;
for (int i = 0; i < this.PointCount; i++)
{
if (allNodes[i].Remained)
{
newNodes[k] = new PLNode(allNodes[i].Point);
k++;
}
}
heap.Clear();
allNodes = newNodes;
for (int i = 0; i < allNodes.Length; i++)
{
if (i > 0)
{
allNodes[i].AddConnection(allNodes[i - 1]);
}
if (i < allNodes.Length - 1)
{
allNodes[i].AddConnection(allNodes[i + 1]);
}
allNodes[i].LoadFactors();
if (heap.Contains(allNodes[i]))
{
allNodes[i].Remained = false;
}
else
{
heap.Add(allNodes[i]);
}
}
}
}
// purging
var min = heap.Min;
while (!min.IsSignificant(angleTolerance, distanceTolerance))
{
heap.Remove(min);
if (min.Connections.Count == 1)
{
throw new ArgumentException("Heap cannot remove the found end point");
}
PLNode node1 = min.Connections.First();
min.Connections.Remove(node1);
PLNode node2 = min.Connections.First();
min.Connections.Remove(node2);
heap.Remove(node1);
heap.Remove(node2);
node1.Connections.Remove(min);
node2.Connections.Remove(min);
node1.AddConnection(node2);
node2.AddConnection(node1);
node1.LoadFactors();
heap.Add(node1);
node2.LoadFactors();
heap.Add(node2);
min.Remained = false;
min = heap.Min;
}
List<UV> purged = new List<UV>();
for (int i = 0; i < allNodes.Length; i++)
{
if (allNodes[i].Remained)
{
purged.Add(allNodes[i].Point);
}
}
return purged;
}
/// <summary>
/// Extracts a list of polylines from an arbitrary collection of lines. NOTE: There might be different possibilities for this operation.
/// </summary>
/// <param name="lines">The lines.</param>
/// <param name="fractionalDigits">The fractional digits used for hashing.</param>
/// <param name="tolerance">The tolerance of point equality.</param>
/// <returns>List<PLine>.</returns>
public static List<PLine> ExtractPLines(ICollection<UVLine> lines, int fractionalDigits = 5, double tolerance = OSMDocument.AbsoluteTolerance)
{
Dictionary<UV, HashSet<UVLine>> pntToLine = new Dictionary<UV, HashSet<UVLine>>(new UVComparer(fractionalDigits, tolerance));
foreach (var item in lines)
{
if (item.GetLengthSquared() > 0)
{
if (pntToLine.ContainsKey(item.Start))
{
pntToLine[item.Start].Add(item);
}
else
{
var set = new HashSet<UVLine>() { item };
pntToLine.Add(item.Start, set);
}
if (pntToLine.ContainsKey(item.End))
{
pntToLine[item.End].Add(item);
}
else
{
var list = new HashSet<UVLine>() { item };
pntToLine.Add(item.End, list);
}
}
else
{
MessageBox.Show("Line with zero length cannot be added to a polyLine!");
}
}
List<PLine> pLines = new List<PLine>();
while (pntToLine.Count != 0)
{
UVLine line = null;
try
{
line = pntToLine.First().Value.First();
}
catch (Exception e)
{
MessageBox.Show("Failed at 3\n" + e.Report());
}
PLine pLine = new PLine(line, fractionalDigits);
//lines.Remove(line);
pntToLine[line.Start].Remove(line);
if (pntToLine[line.Start].Count == 0)
{
pntToLine.Remove(line.Start);
}
pntToLine[line.End].Remove(line);
if (pntToLine[line.End].Count == 0)
{
pntToLine.Remove(line.End);
}
bool iterate = true;
while (iterate)
{
iterate = false;
if (pntToLine.ContainsKey(pLine._start))
{
UVLine line_ = null;
try
{
line_ = pntToLine[pLine._start].First();
}
catch (Exception e)
{
MessageBox.Show("Failed at 1\n" + e.Report());
}
pLine.addSegment(line_);
pntToLine[line_.Start].Remove(line_);
if (pntToLine[line_.Start].Count == 0)
{
pntToLine.Remove(line_.Start);
}
pntToLine[line_.End].Remove(line_);
if (pntToLine[line_.End].Count == 0)
{
pntToLine.Remove(line_.End);
}
//lines.Remove(line);
if (pLine.Closed)
{
break;
}
iterate = true;
}
if (pntToLine.Count == 0) break;
if (pntToLine.ContainsKey(pLine._end))
{
UVLine line_ = null;
try
{
line_ = pntToLine[pLine._end].First();
}
catch (Exception e)
{
MessageBox.Show("Failed at 2\n" + e.Report());
try
{
line_ = pntToLine[pLine._end].First();
}
catch (Exception)
{
}
}
pLine.addSegment(line_);
pntToLine[line_.Start].Remove(line_);
if (pntToLine[line_.Start].Count == 0)
{
pntToLine.Remove(line_.Start);
}
pntToLine[line_.End].Remove(line_);
if (pntToLine[line_.End].Count == 0)
{
pntToLine.Remove(line_.End);
}
//lines.Remove(line);
if (pLine.Closed)
{
break;
}
iterate = true;
}
}
pLines.Add(pLine);
}
return pLines;
}
/// <summary>
/// Finds the closest point on the polygon from a given point
/// </summary>
/// <param name="points">The points that represent a polygon.</param>
/// <param name="p">The point from which the closest point should be found.</param>
/// <param name="closed">if set to <c>true</c> the polygon is closed.</param>
/// <returns>UV.</returns>
public static UV ClosestPoint(List<UV> points, UV p, bool closed)
{
UV[] vecs = new UV[points.Count];
double[] vecLengths = new double[points.Count];
for (int i = 0; i < points.Count; i++)
{
vecs[i] = points[i] - p;
vecLengths[i] = vecs[i].GetLengthSquared();
}
double minDistSquared = double.PositiveInfinity;
int index = 0;
for (int i = 0; i < points.Count - 1; i++)
{
double area = vecs[i].CrossProductValue(vecs[i + 1]);
area *= area;
double d1 = UV.GetLengthSquared(points[i], points[i + 1]);
double distSquared = area / d1;
if (distSquared < vecLengths[i] - d1 || distSquared < vecLengths[i + 1] - d1)
{
distSquared = Math.Min(vecLengths[i + 1], vecLengths[i]);
}
if (minDistSquared > distSquared)
{
minDistSquared = distSquared;
index = i;
}
}
if (closed)
{
double area = vecs[points.Count - 1].CrossProductValue(vecs[0]);
area *= area;
double d1 = UV.GetLengthSquared(points[points.Count - 1], points[0]);
double distSquared = area / d1;
if (distSquared < vecLengths[0] - d1 || distSquared < vecLengths[points.Count - 1] - d1)
{
distSquared = Math.Min(vecLengths[0], vecLengths[points.Count - 1]);
}
if (minDistSquared > distSquared)
{
minDistSquared = distSquared;
index = points.Count - 1;
}
}
int j = index + 1;
if (j == points.Count)
j = 0;
UVLine line = new UVLine(points[index], points[j]);
return p.GetClosestPoint(line);
}
/// <summary>
/// Finds the closest point on the polygon from a given point
/// </summary>
/// <param name="points">The points that represent a polygon.</param>
/// <param name="p">The point from which the closest point should be found.</param>
/// <param name="closed">if set to <c>true</c> the polygon is closed.</param>
/// <returns>UV.</returns>
public static UV ClosestPoint(UV[] points, UV p, bool closed)
{
UV[] vecs = new UV[points.Length];
double[] vecLengths = new double[points.Length];
for (int i = 0; i < points.Length; i++)
{
vecs[i] = points[i] - p;
vecLengths[i] = vecs[i].GetLengthSquared();
}
double minDistSquared = double.PositiveInfinity;
int index = 0;
for (int i = 0; i < points.Length - 1; i++)
{
double area = vecs[i].CrossProductValue(vecs[i + 1]);
area *= area;
double d1 = UV.GetLengthSquared(points[i], points[i + 1]);
double distSquared = area / d1;
if (distSquared < vecLengths[i] - d1 || distSquared < vecLengths[i + 1] - d1)
{
distSquared = Math.Min(vecLengths[i + 1], vecLengths[i]);
}
if (minDistSquared > distSquared)
{
minDistSquared = distSquared;
index = i;
}
}
if (closed)
{
double area = vecs[points.Length - 1].CrossProductValue(vecs[0]);
area *= area;
double d1 = UV.GetLengthSquared(points[points.Length - 1], points[0]);
double distSquared = area / d1;
if (distSquared < vecLengths[0] - d1 || distSquared < vecLengths[points.Length - 1] - d1)
{
distSquared = Math.Min(vecLengths[0], vecLengths[points.Length - 1]);
}
if (minDistSquared > distSquared)
{
minDistSquared = distSquared;
index = points.Length - 1;
}
}
int j = index + 1;
if (j == points.Length)
j = 0;
UVLine line = new UVLine(points[index], points[j]);
return p.GetClosestPoint(line);
}
/// <summary>
/// Returns the distance squared to a list of points that represent a polygon
/// </summary>
/// <param name="pLinePoints">A list of points that represent a polygon.</param>
/// <param name="p">The point to measure the distance squared from.</param>
/// <param name="closed">if set to <c>true</c> the polygon is closed.</param>
/// <returns>System.Double.</returns>
public static double DistanceSquaredTo(List<UV> pLinePoints, UV p, bool closed)
{
UV[] vecs = new UV[pLinePoints.Count];
double[] vecLengths = new double[pLinePoints.Count];
for (int i = 0; i < pLinePoints.Count; i++)
{
vecs[i] = pLinePoints[i] - p;
vecLengths[i] = vecs[i].GetLengthSquared();
}
double minDistSquared = double.PositiveInfinity;
int index = 0;
for (int i = 0; i < pLinePoints.Count - 1; i++)
{
double area = vecs[i].CrossProductValue(vecs[i + 1]);
area *= area;
double d1 = UV.GetLengthSquared(pLinePoints[i], pLinePoints[i + 1]);
double distSquared = area / d1;
if (distSquared < vecLengths[i] - d1 || distSquared < vecLengths[i + 1] - d1)
{
distSquared = Math.Min(vecLengths[i + 1], vecLengths[i]);
}
if (minDistSquared > distSquared)
{
minDistSquared = distSquared;
index = i;
}
}
if (closed)
{
double area = vecs[pLinePoints.Count - 1].CrossProductValue(vecs[0]);
area *= area;
double d1 = UV.GetLengthSquared(pLinePoints[pLinePoints.Count - 1], pLinePoints[0]);
double distSquared = area / d1;
if (distSquared < vecLengths[0] - d1 || distSquared < vecLengths[pLinePoints.Count - 1] - d1)
{
distSquared = Math.Min(vecLengths[0], vecLengths[pLinePoints.Count - 1]);
}
if (minDistSquared > distSquared)
{
minDistSquared = distSquared;
index = pLinePoints.Count - 1;
}
}
return minDistSquared;
}
/// <summary>
/// Returns the distance squared to a list of points that represent a polygon
/// </summary>
/// <param name="pLinePoints">A list of points that represent a polygon.</param>
/// <param name="p">The point to measure the distance squared from.</param>
/// <param name="closed">if set to <c>true</c> the polygon is closed.</param>
/// <returns>System.Double.</returns>
public static double DistanceSquaredTo(UV[] pLinePoints, UV p, bool closed)
{
UV[] vecs = new UV[pLinePoints.Length];
double[] vecLengths = new double[pLinePoints.Length];
for (int i = 0; i < pLinePoints.Length; i++)
{
vecs[i] = pLinePoints[i] - p;
vecLengths[i] = vecs[i].GetLengthSquared();
}
double minDistSquared = double.PositiveInfinity;
int index = 0;
for (int i = 0; i < pLinePoints.Length - 1; i++)
{
double area = vecs[i].CrossProductValue(vecs[i + 1]);
area *= area;
double d1 = UV.GetLengthSquared(pLinePoints[i], pLinePoints[i + 1]);
double distSquared = area / d1;
if (distSquared < vecLengths[i] - d1 || distSquared < vecLengths[i + 1] - d1)
{
distSquared = Math.Min(vecLengths[i + 1], vecLengths[i]);
}
if (minDistSquared > distSquared)
{
minDistSquared = distSquared;
index = i;
}
}
if (closed)
{
double area = vecs[pLinePoints.Length - 1].CrossProductValue(vecs[0]);
area *= area;
double d1 = UV.GetLengthSquared(pLinePoints[pLinePoints.Length - 1], pLinePoints[0]);
double distSquared = area / d1;
if (distSquared < vecLengths[0] - d1 || distSquared < vecLengths[pLinePoints.Length - 1] - d1)
{
distSquared = Math.Min(vecLengths[0], vecLengths[pLinePoints.Length - 1]);
}
if (minDistSquared > distSquared)
{
minDistSquared = distSquared;
index = pLinePoints.Length - 1;
}
}
return minDistSquared;
}
/// <summary>
/// Returns the distance squared to a this polygon
/// </summary>
/// <param name="p">The point to measure the distance squared from.</param>
/// <returns>System.Double.</returns>
public double DistanceSquaredTo(UV p)
{
return PLine.DistanceSquaredTo(this.Points, p, this.Closed);
}
/// <summary>
/// Finds the closest point on the polygon from a given point
/// </summary>
/// <param name="p">The point from which the closest point should be found.</param>
/// <returns>UV.</returns>
public UV ClosestPoint(UV p)
{
return PLine.ClosestPoint(this.Points, p, this.Closed);
}
}
/// <summary>
/// Compares UV values and tests their equality with adjustable level of precision.
/// </summary>
/// <seealso cref="System.Collections.Generic.IEqualityComparer{SpatialAnalysis.Geometry.UV}" />
internal class UVComparer : IEqualityComparer<UV>
{
private int _fractionalDigits;
/// <summary>
/// Gets the fractional digits used for hashing.
/// </summary>
/// <value>The fractional digits.</value>
public int FractionalDigits
{
get { return _fractionalDigits; }
}
private double _tolerance;
/// <summary>
/// Gets the tolerance used for testing equality.
/// </summary>
/// <value>The tolerance.</value>
public double Tolerance
{
get { return _tolerance; }
}
/// <summary>
/// Initializes a new instance of the <see cref="UVComparer"/> class.
/// </summary>
/// <param name="fractionalDigits">The fractional digits for hashing.</param>
/// <param name="tolerance">The tolerance to equality.</param>
public UVComparer(int fractionalDigits, double tolerance)
{
this._tolerance = tolerance;
this._fractionalDigits = fractionalDigits;
}
public bool Equals(UV x, UV y)
{
double deltaX = x.U-y.U;
double deltaY = x.V - y.V;
if (Math.Abs(deltaX)<this._tolerance && Math.Abs(deltaY)<this._tolerance)
{
return true;
}
return false;
}
public int GetHashCode(UV obj)
{
int hash = 7;
hash = 71 * hash + Math.Round(obj.U,this._fractionalDigits).GetHashCode();
hash = 71 * hash + Math.Round(obj.V, this._fractionalDigits).GetHashCode();
return hash;
}
}
internal class PLNode
{
/// <summary>
/// Gets or sets a value indicating whether this <see cref="PLNode"/> is remained.
/// </summary>
/// <value><c>true</c> if remained; otherwise, <c>false</c>.</value>
public bool Remained { get; set; }
/// <summary>
/// Gets or sets the connections.
/// </summary>
/// <value>The connections.</value>
public HashSet<PLNode> Connections { get; set; }
/// <summary>
/// Gets or sets the point.
/// </summary>
/// <value>The point.</value>
public UV Point { get; set; }
/// <summary>
/// Cosine squared of the angle between two edges
/// </summary>
public double AngleFacotr { get; set; }
/// <summary>
/// Minimum distance between the previous and next points
/// </summary>
public double DistanceFactor { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="PLNode"/> class.
/// </summary>
/// <param name="point">The point.</param>
public PLNode(UV point)
{
this.Point = point;
this.Connections = new HashSet<PLNode>();
this.Remained = true;
}
/// <summary>
/// Adds the connection.
/// </summary>
/// <param name="node">The node.</param>
/// <exception cref="ArgumentException">Each node cannot be connected to more than 2 points</exception>
public void AddConnection(PLNode node)
{
this.Connections.Add(node);
if (this.Connections.Count > 2)
{
throw new ArgumentException("Each node cannot be connected to more than 2 points");
}
}
/// <summary>
/// Loads the factors.
/// </summary>
public void LoadFactors()
{
UV v1 = new UV();
UV v2 = new UV();
int i = 0;
foreach (var item in this.Connections)
{
if (i == 2)
break;
else if (i == 0)
{
v1 = this.Point - item.Point;
}
if (i == 1)
{
v2 = this.Point - item.Point;
}
i++;
}
if (i < 2)
{
this.AngleFacotr = double.PositiveInfinity;
this.DistanceFactor = double.PositiveInfinity;
}
else
{
double d1 = v1.GetLengthSquared();
double d2 = v2.GetLengthSquared();
this.DistanceFactor = Math.Min(d1, d2);
double crossProductValue = v1.CrossProductValue(v2);
this.AngleFacotr = crossProductValue * crossProductValue / (d1 * d2);
}
}
public override bool Equals(object obj)
{
PLNode node = (PLNode)obj;
if (node == null)
{
return false;
}
return this.Point.Equals(node.Point);
}
public override int GetHashCode()
{
return this.Point.GetHashCode();
}
public override string ToString()
{
return this.Point.ToString();
}
/// <summary>
/// Determines whether the specified angle tolerance is significant.
/// </summary>
/// <param name="angleTolerance">Angle tolerance is cos(angle)^2 *sign(cos(angle)</param>
/// <param name="distanceTolerance">Distance tolerance is distance^2</param>
/// <returns><c>true</c> if the specified angle tolerance is significant; otherwise, <c>false</c>.</returns>
public bool IsSignificant(double angleTolerance, double distanceTolerance)
{
return this.DistanceFactor > distanceTolerance && this.AngleFacotr > angleTolerance;
}
}
internal class PLNodeComparer : IComparer<PLNode>
{
private double _epsilon { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="PLNodeComparer"/> class.
/// </summary>
/// <param name="distanceTolerance">The distance tolerance.</param>
public PLNodeComparer(double distanceTolerance)
{
this._epsilon = distanceTolerance;
}
/// <summary>
/// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
/// </summary>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <returns>A signed integer that indicates the relative values of <paramref name="x" /> and <paramref name="y" />, as shown in the following table.Value Meaning Less than zero<paramref name="x" /> is less than <paramref name="y" />.Zero<paramref name="x" /> equals <paramref name="y" />.Greater than zero<paramref name="x" /> is greater than <paramref name="y" />.</returns>
public int Compare(PLNode x, PLNode y)
{
//end points
int result = -1 * x.Connections.Count.CompareTo(y.Connections.Count);
if (result != 0)
{
return result;
}
//distance
if (x.DistanceFactor < this._epsilon || y.DistanceFactor < this._epsilon)
{
if (x.DistanceFactor < this._epsilon && y.DistanceFactor < this._epsilon)
{
result = x.DistanceFactor.CompareTo(y.DistanceFactor);
}
else if (x.DistanceFactor < this._epsilon && y.DistanceFactor >= this._epsilon)
{
result = 1;
}
else if (x.DistanceFactor >= this._epsilon && y.DistanceFactor < this._epsilon)
{
result = -1;
}
return result;
}
result = x.AngleFacotr.CompareTo(y.AngleFacotr);
if (result == 0)
{
result = x.Point.GetHashCode().CompareTo(y.GetHashCode());
}
return result;
}
}
}
| |
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 webapi_learning.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;
}
}
}
| |
/*
* Thread.cs - Implementation of the "System.Threading.Thread" class.
*
* Copyright (C) 2001, 2003 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
*/
namespace System.Threading
{
using System.Runtime.CompilerServices;
using System.Runtime.Remoting.Contexts;
using System.Security.Principal;
using System.Diagnostics;
using System.Globalization;
public sealed class Thread
{
// Note: the private fields must be in the order below,
// because the runtime engine assumes they are this way.
// Internal runtime handle for the thread.
private IntPtr privateData;
// Flagged true if the thread has been created from managed code.
private bool createdFromManagedCode;
// State information for abort exceptions.
private Object stateInfo;
// Entry point for the thread.
private ThreadStart start;
// Name of this thread.
private String name;
#if CONFIG_REMOTING
// The context for this thread.
private Context context;
#endif // CONFIG_REMOTING
#if CONFIG_POLICY_OBJECTS
// The security principal for this thread.
private IPrincipal principal;
#endif // CONFIG_POLICY_OBJECTS
#if !ECMA_COMPAT
// Flag that is set for threads in the thread pool.
internal bool inThreadPool;
#endif
// Private constructor only called by the engine
private Thread(IntPtr privateData)
{
InitializeManaged(null, privateData);
}
// Constructor.
public Thread(ThreadStart start)
{
if(start == null)
{
throw new ArgumentNullException("start");
}
this.createdFromManagedCode = true;
InitializeManaged(start, IntPtr.Zero);
InitializeThread();
}
// Destructor.
~Thread()
{
FinalizeThread();
}
private void InitializeManaged(ThreadStart start, IntPtr privateData)
{
this.start = start;
this.privateData = privateData;
#if CONFIG_POLICY_OBJECTS
principal = new GenericPrincipal(new GenericIdentity(""), null);
#endif
}
[MethodImpl(MethodImplOptions.InternalCall)]
extern private void InitializeThread();
// Internal finalization for threads.
[MethodImpl(MethodImplOptions.InternalCall)]
extern private void FinalizeThread();
// Abort this thread.
[MethodImpl(MethodImplOptions.InternalCall)]
extern public void Abort();
// Abort this thread with a particular state object.
public void Abort(Object stateInfo)
{
if(this.stateInfo == null)
{
this.stateInfo = stateInfo;
}
Abort();
}
#if CONFIG_RUNTIME_INFRA
// Get the application domain of the currently executing thread.
public static AppDomain GetDomain()
{
return AppDomain.CurrentDomain;
}
#endif
// Join with this thread.
public void Join()
{
InternalJoin(-1);
}
// Join with this thread, stopping after a specified timeout.
public bool Join(int millisecondsTimeout)
{
if(millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException
("millisecondsTimeout",
_("ArgRange_NonNegOrNegOne"));
}
return InternalJoin(millisecondsTimeout);
}
public bool Join(TimeSpan timeout)
{
return InternalJoin(Monitor.TimeSpanToMS(timeout));
}
// Internal version of "Join". A timeout of -1 indicates
// infinite, and zero indicates "test and return immediately".
[MethodImpl(MethodImplOptions.InternalCall)]
extern private bool InternalJoin(int timeout);
// Insert a memory barrier, which guarantees that all
// pending memory loads and stores will be flushed.
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static void MemoryBarrier();
// Reset the pending thread abort on the current thread.
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static void ResetAbort();
// Sleep for a specific period of time.
public static void Sleep(int millisecondsTimeout)
{
if(millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException
("millisecondsTimeout",
_("ArgRange_NonNegOrNegOne"));
}
InternalSleep(millisecondsTimeout);
}
public static void Sleep(TimeSpan timeout)
{
InternalSleep(Monitor.TimeSpanToMS(timeout));
}
// Internal version of "Sleep". A timeout of -1 indicates
// infinite, and zero indicates return immediately.
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static void InternalSleep(int timeout);
// Start the thread executing.
[MethodImpl(MethodImplOptions.InternalCall)]
extern public void Start();
// Perform volatile read operations.
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static byte VolatileRead(ref byte address);
[MethodImpl(MethodImplOptions.InternalCall)]
[CLSCompliant(false)]
extern public static sbyte VolatileRead(ref sbyte address);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static short VolatileRead(ref short address);
[MethodImpl(MethodImplOptions.InternalCall)]
[CLSCompliant(false)]
extern public static ushort VolatileRead(ref ushort address);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static int VolatileRead(ref int address);
[MethodImpl(MethodImplOptions.InternalCall)]
[CLSCompliant(false)]
extern public static uint VolatileRead(ref uint address);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static long VolatileRead(ref long address);
[MethodImpl(MethodImplOptions.InternalCall)]
[CLSCompliant(false)]
extern public static ulong VolatileRead(ref ulong address);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static IntPtr VolatileRead(ref IntPtr address);
[MethodImpl(MethodImplOptions.InternalCall)]
[CLSCompliant(false)]
extern public static UIntPtr VolatileRead(ref UIntPtr address);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static float VolatileRead(ref float address);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static double VolatileRead(ref double address);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static Object VolatileRead(ref Object address);
// Perform volatile write operations.
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static void VolatileWrite(ref byte address, byte value);
[MethodImpl(MethodImplOptions.InternalCall)]
[CLSCompliant(false)]
extern public static void VolatileWrite(ref sbyte address, sbyte value);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static void VolatileWrite(ref short address, short value);
[MethodImpl(MethodImplOptions.InternalCall)]
[CLSCompliant(false)]
extern public static void VolatileWrite(ref ushort address, ushort value);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static void VolatileWrite(ref int address, int value);
[MethodImpl(MethodImplOptions.InternalCall)]
[CLSCompliant(false)]
extern public static void VolatileWrite(ref uint address, uint value);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static void VolatileWrite(ref long address, long value);
[MethodImpl(MethodImplOptions.InternalCall)]
[CLSCompliant(false)]
extern public static void VolatileWrite(ref ulong address, ulong value);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static void VolatileWrite(ref IntPtr address, IntPtr value);
[MethodImpl(MethodImplOptions.InternalCall)]
[CLSCompliant(false)]
extern public static void VolatileWrite(ref UIntPtr address, UIntPtr value);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static void VolatileWrite(ref float address, float value);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static void VolatileWrite(ref double address, double value);
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static void VolatileWrite(ref Object address, Object value);
// Properties.
public static Thread CurrentThread
{
get
{
return InternalCurrentThread();
}
}
public bool IsAlive
{
get
{
return ((InternalGetState() &
(ThreadState.Unstarted |
ThreadState.Stopped)) == 0);
}
}
public bool IsBackground
{
get
{
return ((InternalGetState() & ThreadState.Background) != 0);
}
set
{
InternalSetBackground(value);
}
}
public String Name
{
get
{
return name;
}
set
{
lock(this)
{
if(name != null)
{
throw new InvalidOperationException
(_("Invalid_WriteOnce"));
}
name = value;
}
}
}
public ThreadPriority Priority
{
get
{
return InternalGetPriority();
}
set
{
InternalSetPriority(value);
}
}
public System.Threading.ThreadState ThreadState
{
get
{
return InternalGetState();
}
}
// Internal version of "CurrentThread".
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static Thread InternalCurrentThread();
// Internal version of "IsBackground".
[MethodImpl(MethodImplOptions.InternalCall)]
extern private void InternalSetBackground(bool value);
// Internal version of "Priority".
[MethodImpl(MethodImplOptions.InternalCall)]
extern private ThreadPriority InternalGetPriority();
[MethodImpl(MethodImplOptions.InternalCall)]
extern private void InternalSetPriority(ThreadPriority value);
// Internal version of "ThreadState".
[MethodImpl(MethodImplOptions.InternalCall)]
extern private System.Threading.ThreadState InternalGetState();
// Get the packed stack trace information for this thread.
internal PackedStackFrame[] GetPackedStackTrace()
{
// We don't currently support getting the stack trace
// for a foreign thread. It is too risky security-wise.
return null;
}
// Determine if the runtime engine can start threads.
// Returns false on a single-threaded system.
[MethodImpl(MethodImplOptions.InternalCall)]
extern internal static bool CanStartThreads();
// Get the identifier for the current thread.
[MethodImpl(MethodImplOptions.InternalCall)]
extern internal static int InternalGetThreadId();
#if !ECMA_COMPAT
// Allocate a local data store slot.
public static LocalDataStoreSlot AllocateDataSlot()
{
return new LocalDataStoreSlot(false, null);
}
// Allocate a named data store slot.
public static LocalDataStoreSlot AllocateNamedDataSlot(String name)
{
return LocalDataStoreSlot.GetNamed(name);
}
// Free a named data store slot.
public static void FreeNamedDataSlot(String name)
{
LocalDataStoreSlot.FreeNamed(name);
}
// Get the compressed stack for a thread.
public CompressedStack GetCompressedStack()
{
return CompressedStack.GetCompressedStack();
}
// Get the data in a particular data store slot.
public static Object GetData(LocalDataStoreSlot slot)
{
if(slot == null)
{
return null;
}
else
{
return slot.Data;
}
}
// Get the current domain identifier.
public static int GetDomainID()
{
return GetDomain().domainID;
}
// Get a previously allocated named data store slot.
public static LocalDataStoreSlot GetNamedDataSlot(String name)
{
return LocalDataStoreSlot.GetNamed(name);
}
// Interrupt this thread.
[MethodImpl(MethodImplOptions.InternalCall)]
extern public void Interrupt();
// Resume execution of this thread.
[MethodImpl(MethodImplOptions.InternalCall)]
extern public void Resume();
// Set the compressed stack for a thread.
public void SetCompressedStack(CompressedStack stack)
{
// Ignored - not used in this implementation.
}
// Set the data in a particular local data store slot.
public static void SetData(LocalDataStoreSlot slot, Object data)
{
if(slot != null)
{
slot.Data = data;
}
}
// Perform a spin wait for a given number of iterations.
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static void SpinWait(int iterations);
// Suspend execution of this thread.
[MethodImpl(MethodImplOptions.InternalCall)]
extern public void Suspend();
// Get or set this thread's apartment state.
public ApartmentState ApartmentState
{
get
{
return ApartmentState.Unknown;
}
set
{
// Ignored - we don't use apartment states.
}
}
#if CONFIG_REMOTING
// Get the remoting context for the current thread.
public static Context CurrentContext
{
get
{
Thread thread = CurrentThread;
if(thread.context == null)
{
thread.context = Context.DefaultContext;
}
return thread.context;
}
}
#endif // CONFIG_REMOTING
// Get or set the current culture for the thread.
public CultureInfo CurrentCulture
{
get
{
return CultureInfo.CurrentCulture;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
CultureInfo.SetCurrentCulture(value);
}
}
#if CONFIG_POLICY_OBJECTS
// Get or set the principal representing the thread's security context.
public static IPrincipal CurrentPrincipal
{
get
{
return CurrentThread.principal;
}
set
{
CurrentThread.principal = value;
}
}
#endif
// Get or set the current UI culture for the thread.
public CultureInfo CurrentUICulture
{
get
{
return CultureInfo.CurrentUICulture;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
CultureInfo.SetCurrentUICulture(value);
}
}
// Determine if this is a thread pool thread.
public bool IsThreadPoolThread
{
get
{
return inThreadPool;
}
}
#endif // !ECMA_COMPAT
}; // class Thread
}; // namespace System.Threading
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 the Outercurve Foundation 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using WebsitePanel.Providers;
using WebsitePanel.Providers.Web;
namespace WebsitePanel.Portal
{
public partial class WebSitesEditHeliconApeFolder : WebsitePanelModuleBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// bind folder
BindFolder();
}
}
private void BindFolder()
{
HtaccessFolder folder;
string name = Request.QueryString["Name"];
string spaceId = Request.QueryString["SpaceID"];
if ("httpd.conf" == name && !string.IsNullOrEmpty(spaceId))
{
// read httpd.conf
folder = ES.Services.WebServers.GetHeliconApeHttpdFolder(int.Parse(spaceId));
ButtonDebuggerStart.Visible = false;
ButtonDebuggerStop.Visible = false;
}
else
{
// read web site
WebSite site = GetWebSite();
if (site == null)
{
RedirectToBrowsePage();
return;
}
LabelWebSiteName.Text = site.Name;
folderPath.RootFolder = site.ContentPath;
folderPath.PackageId = site.PackageId;
htaccessContent.Text = "# Helicon Ape\n";
ButtonDebuggerStart.Visible = true;
ButtonDebuggerStop.Visible = false;
if (String.IsNullOrEmpty(PanelRequest.Name))
return;
// read folder
folder = ES.Services.WebServers.GetHeliconApeFolder(PanelRequest.ItemID, PanelRequest.Name);
}
if (folder == null)
{
ReturnBack();
}
folderPath.SelectedFile = folder.Path;
folderPath.Enabled = false;
contentPath.Value = folder.ContentPath;
htaccessContent.Text = folder.HtaccessContent;
if (string.IsNullOrEmpty( htaccessContent.Text ))
{
htaccessContent.Text = "# Helicon Ape\n";
}
/*
DebuggerUrlField.Value = "";
if ( RE_APE_DEBUGGER_ENABLED.IsMatch(htaccessContent.Text) )
{
btnApeDebug.Text = (string)GetLocalResourceObject("btnApeDebuggerStop.Text");
GetDebuggerUrl();
}
*/
}
private void SaveFolder()
{
HtaccessFolder folder = new HtaccessFolder();
folder.Path = folderPath.SelectedFile;
folder.ContentPath = contentPath.Value;
folder.HtaccessContent = htaccessContent.Text;
string spaceId = Request.QueryString["SpaceID"];
try
{
if (folder.Path == HtaccessFolder.HTTPD_CONF_FILE && !string.IsNullOrEmpty(spaceId))
{
int result = ES.Services.WebServers.UpdateHeliconApeHttpdFolder(int.Parse(spaceId), folder);
if (result < 0)
{
ShowResultMessage(result);
return;
}
}
else
{
int result = ES.Services.WebServers.UpdateHeliconApeFolder(PanelRequest.ItemID, folder);
if (result < 0)
{
ShowResultMessage(result);
return;
}
}
}
catch (Exception ex)
{
ShowErrorMessage("WEB_UPDATE_HELICON_APE_FOLDER", ex);
return;
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
SaveFolder();
ReturnBack();
}
protected void btnSave_Click(object sender, EventArgs e)
{
SaveFolder();
}
protected readonly Regex RE_APE_DEBUGGER_ENABLED = new Regex(@"^[ \t]*(SetEnv\s+mod_developer\s+secure-key-([\d]+))", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);
protected readonly Regex RE_APE_DEBUGGER_DISABLED = new Regex(@"^[ \t]*#[ \t]*(SetEnv\s+mod_developer\s+secure-key-([\d]+))", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);
protected string DebuggerSecureKey = "";
protected string DebuggerSessionId = "";
protected string DebuggerUrl = "";
protected string DebuggingPageUrl = "";
protected void DebugStartClick(object sender, EventArgs e)
{
var code = htaccessContent.Text;
bool needUpdate = false;
if ( RE_APE_DEBUGGER_DISABLED.IsMatch(code) )
{
// already disabled, enable it!
DebuggerSecureKey = RE_APE_DEBUGGER_DISABLED.Match(code).Groups[2].Value;
code = RE_APE_DEBUGGER_DISABLED.Replace(code, "$1");
needUpdate = true;
}
else if (RE_APE_DEBUGGER_ENABLED.IsMatch(code))
{
// already enabled
DebuggerSecureKey = RE_APE_DEBUGGER_ENABLED.Match(code).Groups[2].Value;
needUpdate = false;
}
else
{
DebuggerSecureKey = new Random().Next(100000000, 999999999).ToString(CultureInfo.InvariantCulture);
code = code + "\nSetEnv mod_developer secure-key-" + DebuggerSecureKey + "\n";
needUpdate = true;
}
if (needUpdate)
{
htaccessContent.Text = code;
SaveFolder();
}
StartDebugger();
}
protected void DebugStopClick(object sender, EventArgs e)
{
var code = htaccessContent.Text;
if (RE_APE_DEBUGGER_ENABLED.IsMatch(code))
{
// alerdy enable, disable it!
code = RE_APE_DEBUGGER_ENABLED.Replace(code, "# $1");
htaccessContent.Text = code;
SaveFolder();
}
StopDebugger();
}
private void GetDebuggerUrl()
{
// TODO: interactive binding selection
if ( !string.IsNullOrEmpty(DebuggerSecureKey) )
{
WebSite site = GetWebSite();
if ( null != site)
{
if (site.Bindings.Length > 0)
{
ServerBinding serverBinding = site.Bindings[0];
DebuggerUrl = string.Format(
"{0}://{1}:{2}{3}/_ape_start_developer_session?ape_debug=secure-key-{4}_{5}",
serverBinding.Protocol,
serverBinding.Host ?? serverBinding.IP,
serverBinding.Port,
folderPath.SelectedFile.Replace('\\', '/'),
DebuggerSecureKey,
DebuggerSessionId
);
DebuggerUrlField.Value = DebuggerUrl;
}
}
}
// TODO: throw error if debugger url is empty
}
private WebSite GetWebSite()
{
WebSite webSite = ViewState["HtaccessWebSite"] as WebSite;
if (null == webSite)
{
webSite = ES.Services.WebServers.GetWebSite(PanelRequest.ItemID);
// TODO: ViewState["HtaccessWebSite"] = webSite;
}
return webSite;
}
private void GetDebuggingPageUrl()
{
if (!string.IsNullOrEmpty(DebuggerSecureKey))
{
WebSite site = GetWebSite();
if (null != site)
{
if (site.Bindings.Length > 0)
{
ServerBinding serverBinding = site.Bindings[0];
DebuggingPageUrl = string.Format(
"{0}://{1}:{2}{3}/?ape_debug=secure-key-{4}_{5}",
serverBinding.Protocol,
serverBinding.Host ?? serverBinding.IP,
serverBinding.Port,
folderPath.SelectedFile.Replace('\\', '/'),
DebuggerSecureKey,
DebuggerSessionId
);
}
}
}
// TODO: throw error if url is empty
}
private void StartDebugger()
{
ButtonDebuggerStart.Visible = false;
ButtonDebuggerStop.Visible = true;
// session id
DebuggerSessionId = new Random().Next(100000000, 999999999).ToString(CultureInfo.InvariantCulture);
// debugger url
GetDebuggerUrl();
// debugging page url
GetDebuggingPageUrl();
// show debugger iframe
DebuggerFramePanel.Visible = true;
DebuggerFrame.Attributes["src"] = DebuggerUrl;
// debugging page link
LinkDebuggingPage.NavigateUrl = DebuggingPageUrl;
LinkDebuggingPage.Text = DebuggingPageUrl;
DebuggingPageLinkModal.Show();
}
private void StopDebugger()
{
ButtonDebuggerStart.Visible = true;
ButtonDebuggerStop.Visible = false;
DebuggerUrl = "";
DebuggingPageUrl = "";
DebuggerSessionId = "";
// hide debugger iframe
DebuggerFramePanel.Visible = false;
}
protected void BtnCancelClick(object sender, EventArgs e)
{
ReturnBack();
}
private void ReturnBack()
{
string returnUrlBase64 = Request.QueryString["ReturnUrlBase64"];
if (!string.IsNullOrEmpty(returnUrlBase64))
{
Response.Redirect(Server.UrlDecode(DecodeFrom64(returnUrlBase64)));
}
else
{
Response.Redirect(EditUrl("ItemID", PanelRequest.ItemID.ToString(), "edit_item",
"MenuID=htaccessfolders",
PortalUtils.SPACE_ID_PARAM + "=" + PanelSecurity.PackageId.ToString()));
}
}
static public string DecodeFrom64(string encodedData)
{
return System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(encodedData));
}
}
}
| |
/**
* 7/8/2013
*/
#define PRO
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
namespace ProGrids
{
[InitializeOnLoad]
public static class pg_Initializer
{
/**
* When opening Unity, remember whether or not ProGrids was open when Unity was shut down last.
* Only check within 10 seconds of opening Unity because otherwise Init will be called multiple
* times due to _instance not being set (OnAfterDeserialize is called after static constructors).
*/
static pg_Initializer()
{
if( EditorApplication.timeSinceStartup < 10f && EditorPrefs.GetBool(pg_Constant.ProGridsIsEnabled) )
pg_Editor.InitProGrids();
}
}
public class pg_Editor : ScriptableObject, ISerializationCallbackReceiver
{
#region MEMBERS
string ProGrids_Icons_Path = "Assets/ProCore/ProGrids/GUI/ProGridsToggles";
public static pg_Editor instance
{
get
{
if(_instance == null)
{
pg_Editor[] editor = Resources.FindObjectsOfTypeAll<pg_Editor>();
if(editor != null && editor.Length > 0)
{
_instance = editor[0];
for(int i = 1; i < editor.Length; i++)
{
GameObject.DestroyImmediate(editor[i]);
}
}
}
return _instance;
}
set
{
_instance = value;
}
}
private static pg_Editor _instance;
Color oldColor;
private bool useAxisConstraints = false;
private bool snapEnabled = true;
private SnapUnit snapUnit = SnapUnit.Meter;
#if PRO
private float snapValue = 1f; // the actual snap value, taking into account unit size
private float t_snapValue = 1f; // what the user sees
#else
private float snapValue = .25f;
private float t_snapValue = .25f;
#endif
private bool drawGrid = true;
private bool drawAngles = false;
public float angleValue = 45f;
private bool gridRepaint = true;
public bool predictiveGrid = true;
private bool _snapAsGroup = true;
public bool snapAsGroup
{
get
{
return EditorPrefs.HasKey(pg_Constant.SnapAsGroup) ? EditorPrefs.GetBool(pg_Constant.SnapAsGroup) : true;
}
set
{
_snapAsGroup = value;
EditorPrefs.SetBool(pg_Constant.SnapAsGroup, _snapAsGroup);
}
}
public bool fullGrid { get; private set; }
private bool _scaleSnapEnabled = false;
public bool ScaleSnapEnabled
{
get
{
return EditorPrefs.HasKey(pg_Constant.SnapScale) ? EditorPrefs.GetBool(pg_Constant.SnapScale) : false;
}
set
{
_scaleSnapEnabled = value;
EditorPrefs.SetBool(pg_Constant.SnapScale, _scaleSnapEnabled);
}
}
bool lockGrid = false;
private Axis renderPlane = Axis.Y;
#if PG_DEBUG
private GameObject _pivotGo;
public GameObject pivotGo
{
get
{
if(_pivotGo == null)
{
GameObject find = GameObject.Find("PG_PIVOT_CUBE");
if(find == null)
{
_pivotGo = GameObject.CreatePrimitive(PrimitiveType.Cube);
_pivotGo.name = "PG_PIVOT_CUBE";
}
else
_pivotGo = find;
}
return _pivotGo;
}
set
{
_pivotGo = value;
}
}
#endif
#endregion
#region CONSTANT
const int VERSION = 20;
const bool RESET_PREFS_REQ = true;
#if PRO
const int WINDOW_HEIGHT = 240;
#else
const int WINDOW_HEIGHT = 260;
#endif
const int MAX_LINES = 150; // the maximum amount of lines to display on screen in either direction
public static float alphaBump; // Every tenth line gets an alpha bump by this amount
const int BUTTON_SIZE = 46;
private Texture2D icon_extendoClose, icon_extendoOpen;
[SerializeField] private pg_ToggleContent gc_SnapToGrid = new pg_ToggleContent("Snap", "", "Snaps all selected objects to grid.");
[SerializeField] private pg_ToggleContent gc_GridEnabled = new pg_ToggleContent("Hide", "Show", "Toggles drawing of guide lines on or off. Note that object snapping is not affected by this setting.");
[SerializeField] private pg_ToggleContent gc_SnapEnabled = new pg_ToggleContent("On", "Off", "Toggles snapping on or off.");
[SerializeField] private pg_ToggleContent gc_LockGrid = new pg_ToggleContent("Lock", "Unlck", "Lock the perspective grid center in place.");
[SerializeField] private pg_ToggleContent gc_AngleEnabled = new pg_ToggleContent("> On", "> Off", "If on, ProGrids will draw angled line guides. Angle is settable in degrees.");
[SerializeField] private pg_ToggleContent gc_RenderPlaneX = new pg_ToggleContent("X", "X", "Renders a grid on the X plane.");
[SerializeField] private pg_ToggleContent gc_RenderPlaneY = new pg_ToggleContent("Y", "Y", "Renders a grid on the Y plane.");
[SerializeField] private pg_ToggleContent gc_RenderPlaneZ = new pg_ToggleContent("Z", "Z", "Renders a grid on the Z plane.");
[SerializeField] private pg_ToggleContent gc_RenderPerspectiveGrid = new pg_ToggleContent("Full", "Plane", "Renders a 3d grid in perspective mode.");
[SerializeField] private GUIContent gc_ExtendMenu = new GUIContent("", "Show or hide the scene view menu.");
[SerializeField] private GUIContent gc_SnapIncrement = new GUIContent("", "Set the snap increment.");
#endregion
#region PREFERENCES
/** Settings **/
public Color gridColorX, gridColorY, gridColorZ;
public Color gridColorX_primary, gridColorY_primary, gridColorZ_primary;
// private bool lockOrthographic;
public void LoadPreferences()
{
if( (EditorPrefs.HasKey(pg_Constant.PGVersion) ? EditorPrefs.GetInt(pg_Constant.PGVersion) : 0) < VERSION )
{
EditorPrefs.SetInt(pg_Constant.PGVersion, VERSION);
if(RESET_PREFS_REQ)
{
pg_Preferences.ResetPrefs();
// Debug.Log("Resetting Prefs");
}
}
if(EditorPrefs.HasKey(pg_Constant.SnapEnabled))
{
snapEnabled = EditorPrefs.GetBool(pg_Constant.SnapEnabled);
}
SetSnapValue(
EditorPrefs.HasKey(pg_Constant.GridUnit) ? (SnapUnit)EditorPrefs.GetInt(pg_Constant.GridUnit) : SnapUnit.Meter,
EditorPrefs.HasKey(pg_Constant.SnapValue) ? EditorPrefs.GetFloat(pg_Constant.SnapValue) : 1,
EditorPrefs.HasKey(pg_Constant.SnapMultiplier) ? EditorPrefs.GetInt(pg_Constant.SnapMultiplier) : 100
);
if(EditorPrefs.HasKey(pg_Constant.UseAxisConstraints))
useAxisConstraints = EditorPrefs.GetBool(pg_Constant.UseAxisConstraints);
lockGrid = EditorPrefs.GetBool(pg_Constant.LockGrid);
if(lockGrid)
{
if(EditorPrefs.HasKey(pg_Constant.LockedGridPivot))
{
string piv = EditorPrefs.GetString(pg_Constant.LockedGridPivot);
string[] pivsplit = piv.Replace("(", "").Replace(")", "").Split(',');
float x, y, z;
if( !float.TryParse(pivsplit[0], out x) ) goto NoParseForYou;
if( !float.TryParse(pivsplit[1], out y) ) goto NoParseForYou;
if( !float.TryParse(pivsplit[2], out z) ) goto NoParseForYou;
pivot.x = x;
pivot.y = y;
pivot.z = z;
NoParseForYou:
; // appease the compiler
}
}
fullGrid = EditorPrefs.GetBool(pg_Constant.PerspGrid);
renderPlane = EditorPrefs.HasKey(pg_Constant.GridAxis) ? (Axis)EditorPrefs.GetInt(pg_Constant.GridAxis) : Axis.Y;
alphaBump = (EditorPrefs.HasKey("pg_alphaBump")) ? EditorPrefs.GetFloat("pg_alphaBump") : pg_Preferences.ALPHA_BUMP;
gridColorX = (EditorPrefs.HasKey("gridColorX")) ? pg_Util.ColorWithString(EditorPrefs.GetString("gridColorX")) : pg_Preferences.GRID_COLOR_X;
gridColorX_primary = new Color(gridColorX.r, gridColorX.g, gridColorX.b, gridColorX.a + alphaBump);
gridColorY = (EditorPrefs.HasKey("gridColorY")) ? pg_Util.ColorWithString(EditorPrefs.GetString("gridColorY")) : pg_Preferences.GRID_COLOR_Y;
gridColorY_primary = new Color(gridColorY.r, gridColorY.g, gridColorY.b, gridColorY.a + alphaBump);
gridColorZ = (EditorPrefs.HasKey("gridColorZ")) ? pg_Util.ColorWithString(EditorPrefs.GetString("gridColorZ")) : pg_Preferences.GRID_COLOR_Z;
gridColorZ_primary = new Color(gridColorZ.r, gridColorZ.g, gridColorZ.b, gridColorZ.a + alphaBump);
drawGrid = (EditorPrefs.HasKey("showgrid")) ? EditorPrefs.GetBool("showgrid") : pg_Preferences.SHOW_GRID;
predictiveGrid = EditorPrefs.HasKey(pg_Constant.PredictiveGrid) ? EditorPrefs.GetBool(pg_Constant.PredictiveGrid) : true;
_snapAsGroup = snapAsGroup;
_scaleSnapEnabled = ScaleSnapEnabled;
}
private GUISkin sixBySevenSkin;
#endregion
#region MENU
[MenuItem("Tools/ProGrids/About", false, 0)]
public static void MenuAboutProGrids()
{
pg_AboutWindow.Init("Assets/ProCore/ProGrids/About/pc_AboutEntry_ProGrids.txt", true);
}
[MenuItem("Tools/ProGrids/ProGrids Window", false, 15)]
public static void InitProGrids()
{
if( instance == null )
{
EditorPrefs.SetBool(pg_Constant.ProGridsIsEnabled, true);
instance = ScriptableObject.CreateInstance<pg_Editor>();
instance.hideFlags = HideFlags.DontSave;
EditorApplication.delayCall += instance.Initialize;
}
else
{
CloseProGrids();
}
SceneView.RepaintAll();
}
[MenuItem("Tools/ProGrids/Close ProGrids", true, 200)]
public static bool VerifyCloseProGrids()
{
return instance != null || Resources.FindObjectsOfTypeAll<pg_Editor>().Length > 0;
}
[MenuItem("Tools/ProGrids/Close ProGrids")]
public static void CloseProGrids()
{
foreach(pg_Editor editor in Resources.FindObjectsOfTypeAll<pg_Editor>())
editor.Close();
}
[MenuItem("Tools/ProGrids/Cycle SceneView Projection", false, 101)]
public static void CyclePerspective()
{
if(instance == null) return;
SceneView scnvw = SceneView.lastActiveSceneView;
if(scnvw == null) return;
int nextOrtho = EditorPrefs.GetInt(pg_Constant.LastOrthoToggledRotation);
switch(nextOrtho)
{
case 0:
scnvw.orthographic = true;
scnvw.LookAt(scnvw.pivot, Quaternion.Euler(Vector3.zero));
nextOrtho++;
break;
case 1:
scnvw.orthographic = true;
scnvw.LookAt(scnvw.pivot, Quaternion.Euler(Vector3.up * -90f));
nextOrtho++;
break;
case 2:
scnvw.orthographic = true;
scnvw.LookAt(scnvw.pivot, Quaternion.Euler(Vector3.right * 90f));
nextOrtho++;
break;
case 3:
scnvw.orthographic = false;
scnvw.LookAt(scnvw.pivot, new Quaternion(-0.1f, 0.9f, -0.2f, -0.4f) );
nextOrtho = 0;
break;
}
EditorPrefs.SetInt(pg_Constant.LastOrthoToggledRotation, nextOrtho);
}
[MenuItem("Tools/ProGrids/Cycle SceneView Projection", true, 101)]
[MenuItem("Tools/ProGrids/Increase Grid Size", true, 203)]
[MenuItem("Tools/ProGrids/Decrease Grid Size", true, 202)]
public static bool VerifyGridSizeAdjustment()
{
return instance != null;
}
[MenuItem("Tools/ProGrids/Decrease Grid Size", false, 202)]
public static void DecreaseGridSize()
{
if(instance == null) return;
int multiplier = EditorPrefs.HasKey(pg_Constant.SnapMultiplier) ? EditorPrefs.GetInt(pg_Constant.SnapMultiplier) : 100;
float val = EditorPrefs.HasKey(pg_Constant.SnapValue) ? EditorPrefs.GetFloat(pg_Constant.SnapValue) : 1f;
multiplier /= 2;
instance.SetSnapValue(instance.snapUnit, val, multiplier);
SceneView.RepaintAll();
}
[MenuItem("Tools/ProGrids/Increase Grid Size", false, 203)]
public static void IncreaseGridSize()
{
if(instance == null) return;
int multiplier = EditorPrefs.HasKey(pg_Constant.SnapMultiplier) ? EditorPrefs.GetInt(pg_Constant.SnapMultiplier) : 100;
float val = EditorPrefs.HasKey(pg_Constant.SnapValue) ? EditorPrefs.GetFloat(pg_Constant.SnapValue) : 1f;
multiplier *= 2;
instance.SetSnapValue(instance.snapUnit, val, multiplier);
SceneView.RepaintAll();
}
[MenuItem("Tools/ProGrids/Nudge Perspective Backward", true, 304)]
[MenuItem("Tools/ProGrids/Nudge Perspective Forward", true, 305)]
[MenuItem("Tools/ProGrids/Reset Perspective Nudge", true, 306)]
public static bool VerifyMenuNudgePerspective()
{
return instance != null && !instance.fullGrid && !instance.ortho && instance.lockGrid;
}
[MenuItem("Tools/ProGrids/Nudge Perspective Backward", false, 304)]
public static void MenuNudgePerspectiveBackward()
{
if(!instance.lockGrid) return;
instance.offset -= instance.snapValue;
instance.gridRepaint = true;
SceneView.RepaintAll();
}
[MenuItem("Tools/ProGrids/Nudge Perspective Forward", false, 305)]
public static void MenuNudgePerspectiveForward()
{
if(!instance.lockGrid) return;
instance.offset += instance.snapValue;
instance.gridRepaint = true;
SceneView.RepaintAll();
}
[MenuItem("Tools/ProGrids/Reset Perspective Nudge", false, 306)]
public static void MenuNudgePerspectiveReset()
{
if(!instance.lockGrid) return;
instance.offset = 0;
instance.gridRepaint = true;
SceneView.RepaintAll();
}
#endregion
#region INITIALIZATION / SERIALIZATION
public void OnBeforeSerialize() {}
public void OnAfterDeserialize()
{
instance = this;
instance.LoadGUIResources();
SceneView.onSceneGUIDelegate += OnSceneGUI;
EditorApplication.update += Update;
EditorApplication.hierarchyWindowChanged += HierarchyWindowChanged;
LoadPreferences();
}
public void Initialize()
{
SceneView.onSceneGUIDelegate += OnSceneGUI;
EditorApplication.update += Update;
EditorApplication.hierarchyWindowChanged += HierarchyWindowChanged;
LoadGUIResources();
LoadPreferences();
instance = this;
pg_GridRenderer.Init();
SetMenuIsExtended(false);
lastTime = Time.realtimeSinceStartup;
ToggleMenuVisibility();
gridRepaint = true;
RepaintSceneView();
}
void OnDestroy()
{
this.Close(true);
}
public void Close()
{
EditorPrefs.SetBool(pg_Constant.ProGridsIsEnabled, false);
GameObject.DestroyImmediate(this);
}
public void Close(bool isBeingDestroyed)
{
pg_GridRenderer.Destroy();
SceneView.onSceneGUIDelegate -= OnSceneGUI;
EditorApplication.update -= Update;
EditorApplication.hierarchyWindowChanged -= HierarchyWindowChanged;
instance = null;
foreach(System.Action<bool> listener in toolbarEventSubscribers)
listener(false);
SceneView.RepaintAll();
}
private void LoadGUIResources()
{
if(gc_GridEnabled.image_on == null)
gc_GridEnabled.image_on = LoadIcon("ProGrids2_GUI_Vis_On.png");
if(gc_GridEnabled.image_off == null)
gc_GridEnabled.image_off = LoadIcon("ProGrids2_GUI_Vis_Off.png");
if(gc_SnapEnabled.image_on == null)
gc_SnapEnabled.image_on = LoadIcon("ProGrids2_GUI_Snap_On.png");
if(gc_SnapEnabled.image_off == null)
gc_SnapEnabled.image_off = LoadIcon("ProGrids2_GUI_Snap_Off.png");
if(gc_SnapToGrid.image_on == null)
gc_SnapToGrid.image_on = LoadIcon("ProGrids2_GUI_PushToGrid_Normal.png");
if(gc_LockGrid.image_on == null)
gc_LockGrid.image_on = LoadIcon("ProGrids2_GUI_PGrid_Lock_On.png");
if(gc_LockGrid.image_off == null)
gc_LockGrid.image_off = LoadIcon("ProGrids2_GUI_PGrid_Lock_Off.png");
if(gc_AngleEnabled.image_on == null)
gc_AngleEnabled.image_on = LoadIcon("ProGrids2_GUI_AngleVis_On.png");
if(gc_AngleEnabled.image_off == null)
gc_AngleEnabled.image_off = LoadIcon("ProGrids2_GUI_AngleVis_Off.png");
if(gc_RenderPlaneX.image_on == null)
gc_RenderPlaneX.image_on = LoadIcon("ProGrids2_GUI_PGrid_X_On.png");
if(gc_RenderPlaneX.image_off == null)
gc_RenderPlaneX.image_off = LoadIcon("ProGrids2_GUI_PGrid_X_Off.png");
if(gc_RenderPlaneY.image_on == null)
gc_RenderPlaneY.image_on = LoadIcon("ProGrids2_GUI_PGrid_Y_On.png");
if(gc_RenderPlaneY.image_off == null)
gc_RenderPlaneY.image_off = LoadIcon("ProGrids2_GUI_PGrid_Y_Off.png");
if(gc_RenderPlaneZ.image_on == null)
gc_RenderPlaneZ.image_on = LoadIcon("ProGrids2_GUI_PGrid_Z_On.png");
if(gc_RenderPlaneZ.image_off == null)
gc_RenderPlaneZ.image_off = LoadIcon("ProGrids2_GUI_PGrid_Z_Off.png");
if(gc_RenderPerspectiveGrid.image_on == null)
gc_RenderPerspectiveGrid.image_on = LoadIcon("ProGrids2_GUI_PGrid_3D_On.png");
if(gc_RenderPerspectiveGrid.image_off == null)
gc_RenderPerspectiveGrid.image_off = LoadIcon("ProGrids2_GUI_PGrid_3D_Off.png");
if(icon_extendoOpen == null)
icon_extendoOpen = LoadIcon("ProGrids2_MenuExtendo_Open.png");
if(icon_extendoClose == null)
icon_extendoClose = LoadIcon("ProGrids2_MenuExtendo_Close.png");
}
private Texture2D LoadIcon(string iconName)
{
string iconPath = ProGrids_Icons_Path + "/" + iconName;
if(!File.Exists(iconPath))
{
string[] path = Directory.GetFiles("Assets", iconName, SearchOption.AllDirectories);
if(path.Length > 0)
{
ProGrids_Icons_Path = Path.GetDirectoryName(path[0]);
iconPath = path[0];
}
else
{
Debug.LogError("ProGrids failed to locate menu image: " + iconName + ".\nThis can happen if the GUI folder is moved or deleted. Deleting and re-importing ProGrids will fix this error.");
return (Texture2D) null;
}
}
return LoadAssetAtPath<Texture2D>(iconPath);
}
T LoadAssetAtPath<T>(string path) where T : UnityEngine.Object
{
return (T) AssetDatabase.LoadAssetAtPath(path, typeof(T));
}
#endregion
#region INTERFACE
GUIStyle gridButtonStyle = new GUIStyle();
GUIStyle extendoStyle = new GUIStyle();
GUIStyle gridButtonStyleBlank = new GUIStyle();
GUIStyle backgroundStyle = new GUIStyle();
bool guiInitialized = false;
public float GetSnapIncrement()
{
return t_snapValue;
}
public void SetSnapIncrement(float inc)
{
SetSnapValue(snapUnit, Mathf.Max(inc, .001f), 100);
}
void RepaintSceneView()
{
SceneView.RepaintAll();
}
int MENU_HIDDEN { get { return menuIsOrtho ? -192 : -173; } }
const int MENU_EXTENDED = 8;
const int PAD = 3;
Rect r = new Rect(8, MENU_EXTENDED, 42, 16);
Rect backgroundRect = new Rect(00,0,0,0);
Rect extendoButtonRect = new Rect(0,0,0,0);
bool menuOpen = true;
float menuStart = MENU_EXTENDED;
const float MENU_SPEED = 500f;
float deltaTime = 0f;
float lastTime = 0f;
const float FADE_SPEED = 2.5f;
float backgroundFade = 1f;
bool mouseOverMenu = false;
Color menuBackgroundColor = new Color(0f, 0f, 0f, .5f);
Color extendoNormalColor = new Color(.9f, .9f, .9f, .7f);
Color extendoHoverColor = new Color(0f, 1f, .4f, 1f);
bool extendoButtonHovering = false;
bool menuIsOrtho = false;
void Update()
{
deltaTime = Time.realtimeSinceStartup - lastTime;
lastTime = Time.realtimeSinceStartup;
if( menuOpen && menuStart < MENU_EXTENDED || !menuOpen && menuStart > MENU_HIDDEN )
{
menuStart += deltaTime * MENU_SPEED * (menuOpen ? 1f : -1f);
menuStart = Mathf.Clamp(menuStart, MENU_HIDDEN, MENU_EXTENDED);
RepaintSceneView();
}
float a = menuBackgroundColor.a;
backgroundFade = (mouseOverMenu || !menuOpen) ? FADE_SPEED : -FADE_SPEED;
menuBackgroundColor.a = Mathf.Clamp(menuBackgroundColor.a + backgroundFade * deltaTime, 0f, .5f);
extendoNormalColor.a = menuBackgroundColor.a;
extendoHoverColor.a = (menuBackgroundColor.a / .5f);
if( !Mathf.Approximately(menuBackgroundColor.a,a) )
RepaintSceneView();
}
void DrawSceneGUI()
{
// GUILayout.BeginArea(new Rect(300, 200, 400, 600));
// off = EditorGUILayout.RectField("Rect", off);
// extendoHoverColor = EditorGUI.ColorField(new Rect(200, 40, 200, 18), "howver", extendoHoverColor);
// GUILayout.EndArea();
GUI.backgroundColor = menuBackgroundColor;
backgroundRect.x = r.x - 4;
backgroundRect.y = 0;
backgroundRect.width = r.width + 8;
backgroundRect.height = r.y + r.height + PAD;
GUI.Box(backgroundRect, "", backgroundStyle);
// when hit testing mouse for showing the background, add some leeway
backgroundRect.width += 32f;
backgroundRect.height += 32f;
GUI.backgroundColor = Color.white;
if( !guiInitialized )
{
extendoStyle.normal.background = menuOpen ? icon_extendoClose : icon_extendoOpen;
extendoStyle.hover.background = menuOpen ? icon_extendoClose : icon_extendoOpen;
guiInitialized = true;
backgroundStyle.normal.background = EditorGUIUtility.whiteTexture;
Texture2D icon_button_normal = LoadIcon("ProGrids2_Button_Normal.png");
Texture2D icon_button_hover = LoadIcon("ProGrids2_Button_Hover.png");
if(icon_button_normal == null)
{
gridButtonStyleBlank = new GUIStyle("button");
}
else
{
gridButtonStyleBlank.normal.background = icon_button_normal;
gridButtonStyleBlank.hover.background = icon_button_hover;
gridButtonStyleBlank.normal.textColor = icon_button_normal != null ? Color.white : Color.black;
gridButtonStyleBlank.hover.textColor = new Color(.7f, .7f, .7f, 1f);
}
gridButtonStyleBlank.padding = new RectOffset(1,2,1,2);
gridButtonStyleBlank.alignment = TextAnchor.MiddleCenter;
}
r.y = menuStart;
gc_SnapIncrement.text = t_snapValue.ToString();
if( GUI.Button(r, gc_SnapIncrement, gridButtonStyleBlank) )
{
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
// On Mac ShowAsDropdown and ShowAuxWindow both throw stack pop exceptions when initialized.
pg_ParameterWindow options = EditorWindow.GetWindow<pg_ParameterWindow>(true, "ProGrids Settings", true);
Rect screenRect = SceneView.lastActiveSceneView.position;
options.editor = this;
options.position = new Rect(screenRect.x + r.x + r.width + PAD,
screenRect.y + r.y + 24,
256,
162);
#else
pg_ParameterWindow options = ScriptableObject.CreateInstance<pg_ParameterWindow>();
Rect screenRect = SceneView.lastActiveSceneView.position;
options.editor = this;
options.ShowAsDropDown(new Rect(screenRect.x + r.x + r.width + PAD,
screenRect.y + r.y + 24,
0,
0),
new Vector2(256, 162));
#endif
}
r.y += r.height + PAD;
// Draw grid
if(pg_ToggleContent.ToggleButton(r, gc_GridEnabled, drawGrid, gridButtonStyle, EditorStyles.miniButton))
SetGridEnabled(!drawGrid);
r.y += r.height + PAD;
// Snap enabled
if(pg_ToggleContent.ToggleButton(r, gc_SnapEnabled, snapEnabled, gridButtonStyle, EditorStyles.miniButton))
SetSnapEnabled(!snapEnabled);
r.y += r.height + PAD;
// Push to grid
if(pg_ToggleContent.ToggleButton(r, gc_SnapToGrid, true, gridButtonStyle, EditorStyles.miniButton))
SnapToGrid(Selection.transforms);
r.y += r.height + PAD;
// Lock grid
if(pg_ToggleContent.ToggleButton(r, gc_LockGrid, lockGrid, gridButtonStyle, EditorStyles.miniButton))
{
lockGrid = !lockGrid;
EditorPrefs.SetBool(pg_Constant.LockGrid, lockGrid);
EditorPrefs.SetString(pg_Constant.LockedGridPivot, pivot.ToString());
// if we've modified the nudge value, reset the pivot here
if(!lockGrid)
offset = 0f;
gridRepaint = true;
RepaintSceneView();
}
if(menuIsOrtho)
{
r.y += r.height + PAD;
if(pg_ToggleContent.ToggleButton(r, gc_AngleEnabled, drawAngles, gridButtonStyle, EditorStyles.miniButton))
SetDrawAngles(!drawAngles);
}
/**
* Perspective Toggles
*/
r.y += r.height + PAD + 4;
if(pg_ToggleContent.ToggleButton(r, gc_RenderPlaneX, (renderPlane & Axis.X) == Axis.X && !fullGrid, gridButtonStyle, EditorStyles.miniButton))
SetRenderPlane(Axis.X);
r.y += r.height + PAD;
if(pg_ToggleContent.ToggleButton(r, gc_RenderPlaneY, (renderPlane & Axis.Y) == Axis.Y && !fullGrid, gridButtonStyle, EditorStyles.miniButton))
SetRenderPlane(Axis.Y);
r.y += r.height + PAD;
if(pg_ToggleContent.ToggleButton(r, gc_RenderPlaneZ, (renderPlane & Axis.Z) == Axis.Z && !fullGrid, gridButtonStyle, EditorStyles.miniButton))
SetRenderPlane(Axis.Z);
r.y += r.height + PAD;
if(pg_ToggleContent.ToggleButton(r, gc_RenderPerspectiveGrid, fullGrid, gridButtonStyle, EditorStyles.miniButton))
{
fullGrid = !fullGrid;
gridRepaint = true;
EditorPrefs.SetBool(pg_Constant.PerspGrid, fullGrid);
RepaintSceneView();
}
r.y += r.height + PAD;
extendoButtonRect.x = r.x;
extendoButtonRect.y = r.y;
extendoButtonRect.width = r.width;
extendoButtonRect.height = r.height;
GUI.backgroundColor = extendoButtonHovering ? extendoHoverColor : extendoNormalColor;
gc_ExtendMenu.text = icon_extendoOpen == null ? (menuOpen ? "Close" : "Open") : "";
if(GUI.Button(r, gc_ExtendMenu, icon_extendoOpen ? extendoStyle : gridButtonStyleBlank))
{
ToggleMenuVisibility();
extendoButtonHovering = false;
}
GUI.backgroundColor = Color.white;
}
void ToggleMenuVisibility()
{
menuOpen = !menuOpen;
extendoStyle.normal.background = menuOpen ? icon_extendoClose : icon_extendoOpen;
extendoStyle.hover.background = menuOpen ? icon_extendoClose : icon_extendoOpen;
foreach(System.Action<bool> listener in toolbarEventSubscribers)
listener(menuOpen);
RepaintSceneView();
}
// skip color fading and stuff
void SetMenuIsExtended(bool isExtended)
{
menuOpen = isExtended;
menuIsOrtho = ortho;
menuStart = menuOpen ? MENU_EXTENDED : MENU_HIDDEN;
menuBackgroundColor.a = 0f;
extendoNormalColor.a = menuBackgroundColor.a;
extendoHoverColor.a = (menuBackgroundColor.a / .5f);
extendoStyle.normal.background = menuOpen ? icon_extendoClose : icon_extendoOpen;
extendoStyle.hover.background = menuOpen ? icon_extendoClose : icon_extendoOpen;
foreach(System.Action<bool> listener in toolbarEventSubscribers)
listener(menuOpen);
}
private void OpenProGridsPopup()
{
if( EditorUtility.DisplayDialog(
"Upgrade to ProGrids", // Title
"Enables all kinds of super-cool features, like different snap values, more units of measurement, and angles.", // Message
"Upgrade", // Okay
"Cancel" // Cancel
))
// #if UNITY_4
// AssetStore.OpenURL(pg_Constant.ProGridsUpgradeURL);
// #else
Application.OpenURL(pg_Constant.ProGridsUpgradeURL);
// #endif
}
#endregion
#region ONSCENEGUI
private Transform lastTransform;
const string AXIS_CONSTRAINT_KEY = "s";
const string TEMP_DISABLE_KEY = "d";
private bool toggleAxisConstraint = false;
private bool toggleTempSnap = false;
private Vector3 lastPosition = Vector3.zero;
// private Vector3 lastRotation = Vector3.zero;
private Vector3 lastScale = Vector3.one;
private Vector3 pivot = Vector3.zero, lastPivot = Vector3.zero;
private Vector3 camDir = Vector3.zero, prevCamDir = Vector3.zero;
private float lastDistance = 0f; ///< Distance from camera to pivot at the last time the grid mesh was updated.
public float offset = 0f;
private bool firstMove = true;
#if PROFILE_TIMES
pb_Profiler profiler = new pb_Profiler();
#endif
public bool ortho { get; private set; }
private bool prevOrtho = false;
float planeGridDrawDistance = 0f;
public void OnSceneGUI(SceneView scnview)
{
bool isCurrentView = scnview == SceneView.lastActiveSceneView;
if( isCurrentView )
{
Handles.BeginGUI();
DrawSceneGUI();
Handles.EndGUI();
}
// don't snap stuff in play mode
if(EditorApplication.isPlayingOrWillChangePlaymode)
return;
Event e = Event.current;
// repaint scene gui if mouse is near controls
if( isCurrentView && e.type == EventType.MouseMove )
{
bool tmp = extendoButtonHovering;
extendoButtonHovering = extendoButtonRect.Contains(e.mousePosition);
if( extendoButtonHovering != tmp )
RepaintSceneView();
mouseOverMenu = backgroundRect.Contains(e.mousePosition);
}
if (e.Equals(Event.KeyboardEvent(AXIS_CONSTRAINT_KEY)))
{
toggleAxisConstraint = true;
}
if (e.Equals(Event.KeyboardEvent(TEMP_DISABLE_KEY)))
{
toggleTempSnap = true;
}
if(e.type == EventType.KeyUp)
{
toggleAxisConstraint = false;
toggleTempSnap = false;
bool used = true;
switch(e.keyCode)
{
case KeyCode.Equals:
IncreaseGridSize();
break;
case KeyCode.Minus:
DecreaseGridSize();
break;
case KeyCode.LeftBracket:
if(VerifyMenuNudgePerspective())
MenuNudgePerspectiveBackward();
break;
case KeyCode.RightBracket:
if(VerifyMenuNudgePerspective())
MenuNudgePerspectiveForward();
break;
case KeyCode.Alpha0:
if(VerifyMenuNudgePerspective())
MenuNudgePerspectiveReset();
break;
case KeyCode.Backslash:
CyclePerspective();
break;
default:
used = false;
break;
}
if(used)
e.Use();
}
Camera cam = Camera.current;
if(cam == null)
return;
ortho = cam.orthographic && IsRounded(scnview.rotation.eulerAngles.normalized);
camDir = pg_Util.CeilFloor( pivot - cam.transform.position );
if(ortho && !prevOrtho || ortho != menuIsOrtho)
OnSceneBecameOrtho(isCurrentView);
if(!ortho && prevOrtho)
OnSceneBecamePersp(isCurrentView);
prevOrtho = ortho;
float camDistance = Vector3.Distance(cam.transform.position, lastPivot); // distance from camera to pivot
if(fullGrid)
{
pivot = lockGrid || Selection.activeTransform == null ? pivot : Selection.activeTransform.position;
}
else
{
Vector3 sceneViewPlanePivot = pivot;
Ray ray = new Ray(cam.transform.position, cam.transform.forward);
Plane plane = new Plane(Vector3.up, pivot);
float dist;
// the only time a locked grid should ever move is if it's pivot is out
// of the camera's frustum.
if( (lockGrid && !cam.InFrustum(pivot)) || !lockGrid || scnview != SceneView.lastActiveSceneView)
{
if(plane.Raycast(ray, out dist))
sceneViewPlanePivot = ray.GetPoint( Mathf.Min(dist, planeGridDrawDistance/2f) );
else
sceneViewPlanePivot = ray.GetPoint( Mathf.Min(cam.farClipPlane/2f, planeGridDrawDistance/2f) );
}
if(lockGrid)
{
pivot = pg_Enum.InverseAxisMask(sceneViewPlanePivot, renderPlane) + pg_Enum.AxisMask(pivot, renderPlane);
}
else
{
pivot = Selection.activeTransform == null ? pivot : Selection.activeTransform.position;
if( Selection.activeTransform == null || !cam.InFrustum(pivot) )
{
pivot = pg_Enum.InverseAxisMask(sceneViewPlanePivot, renderPlane) + pg_Enum.AxisMask(Selection.activeTransform == null ? pivot : Selection.activeTransform.position, renderPlane);
}
}
}
#if PG_DEBUG
pivotGo.transform.position = pivot;
#endif
if(drawGrid)
{
if(ortho)
{
// ortho don't care about pivots
DrawGridOrthographic(cam);
}
else
{
#if PROFILE_TIMES
profiler.LogStart("DrawGridPerspective");
#endif
if( gridRepaint || pivot != lastPivot || Mathf.Abs(camDistance - lastDistance) > lastDistance/2 || camDir != prevCamDir)
{
prevCamDir = camDir;
gridRepaint = false;
lastPivot = pivot;
lastDistance = camDistance;
if(fullGrid)
{
// if perspective and 3d, use pivot like normal
pg_GridRenderer.DrawGridPerspective(cam, pivot, snapValue, new Color[3] { gridColorX, gridColorY, gridColorZ }, alphaBump );
}
else
{
if( (renderPlane & Axis.X) == Axis.X)
planeGridDrawDistance = pg_GridRenderer.DrawPlane(cam, pivot + Vector3.right * offset, Vector3.up, Vector3.forward, snapValue, gridColorX, alphaBump);
if( (renderPlane & Axis.Y) == Axis.Y)
planeGridDrawDistance = pg_GridRenderer.DrawPlane(cam, pivot + Vector3.up * offset, Vector3.right, Vector3.forward, snapValue, gridColorY, alphaBump);
if( (renderPlane & Axis.Z) == Axis.Z)
planeGridDrawDistance = pg_GridRenderer.DrawPlane(cam, pivot + Vector3.forward * offset, Vector3.up, Vector3.right, snapValue, gridColorZ, alphaBump);
}
}
#if PROFILE_TIMES
profiler.LogFinish("DrawGridPerspective");
#endif
}
}
// Always keep track of the selection
if(!Selection.transforms.Contains(lastTransform))
{
if(Selection.activeTransform)
{
lastTransform = Selection.activeTransform;
lastPosition = Selection.activeTransform.position;
lastScale = Selection.activeTransform.localScale;
}
}
if( e.type == EventType.MouseUp )
firstMove = true;
if(!snapEnabled || GUIUtility.hotControl < 1)
return;
// Bugger.SetKey("Toggle Snap Off", toggleTempSnap);
/**
* Snapping (for all the junk in PG, this method is literally the only code that actually affects anything).
*/
if(Selection.activeTransform)
{
if( !FuzzyEquals(lastTransform.position, lastPosition) )
{
Transform selected = lastTransform;
if( !toggleTempSnap )
{
Vector3 old = selected.position;
Vector3 mask = old - lastPosition;
bool constraintsOn = toggleAxisConstraint ? !useAxisConstraints : useAxisConstraints;
if(constraintsOn)
selected.position = pg_Util.SnapValue(old, mask, snapValue);
else
selected.position = pg_Util.SnapValue(old, snapValue);
Vector3 offset = selected.position - old;
if( predictiveGrid && firstMove && !fullGrid )
{
firstMove = false;
Axis dragAxis = pg_Util.CalcDragAxis(offset, scnview.camera);
if(dragAxis != Axis.None && dragAxis != renderPlane)
SetRenderPlane(dragAxis);
}
if(_snapAsGroup)
{
OffsetTransforms(Selection.transforms, selected, offset);
}
else
{
foreach(Transform t in Selection.transforms)
t.position = constraintsOn ? pg_Util.SnapValue(t.position, mask, snapValue) : pg_Util.SnapValue(t.position, snapValue);
}
}
lastPosition = selected.position;
}
if( !FuzzyEquals(lastTransform.localScale, lastScale) && _scaleSnapEnabled )
{
if( !toggleTempSnap )
{
Vector3 old = lastTransform.localScale;
Vector3 mask = old - lastScale;
if( predictiveGrid )
{
Axis dragAxis = pg_Util.CalcDragAxis( Selection.activeTransform.TransformDirection(mask), scnview.camera);
if(dragAxis != Axis.None && dragAxis != renderPlane)
SetRenderPlane(dragAxis);
}
foreach(Transform t in Selection.transforms)
t.localScale = pg_Util.SnapValue(t.localScale, mask, snapValue);
lastScale = lastTransform.localScale;
}
}
}
}
void OnSceneBecameOrtho(bool isCurrentView)
{
pg_GridRenderer.Destroy();
if(isCurrentView && ortho != menuIsOrtho)
SetMenuIsExtended(menuOpen);
}
void OnSceneBecamePersp(bool isCurrentView)
{
if(isCurrentView && ortho != menuIsOrtho)
SetMenuIsExtended(menuOpen);
}
#endregion
#region GRAPHICS
GameObject go;
private void DrawGridOrthographic(Camera cam)
{
Axis camAxis = AxisWithVector(Camera.current.transform.TransformDirection(Vector3.forward).normalized);
if(drawGrid) {
switch(camAxis)
{
case Axis.X:
case Axis.NegX:
DrawGridOrthographic(cam, camAxis, gridColorX_primary, gridColorX);
break;
case Axis.Y:
case Axis.NegY:
DrawGridOrthographic(cam, camAxis, gridColorY_primary, gridColorY);
break;
case Axis.Z:
case Axis.NegZ:
DrawGridOrthographic(cam, camAxis, gridColorZ_primary, gridColorZ);
break;
}
}
}
int PRIMARY_COLOR_INCREMENT = 10;
Color previousColor;
private void DrawGridOrthographic(Camera cam, Axis camAxis, Color primaryColor, Color secondaryColor)
{
previousColor = Handles.color;
Handles.color = primaryColor;
// !-- TODO: Update this stuff only when necessary. Currently it runs evvverrrryyy frame
Vector3 bottomLeft = pg_Util.SnapToFloor(cam.ScreenToWorldPoint(Vector2.zero), snapValue);
Vector3 bottomRight = pg_Util.SnapToFloor(cam.ScreenToWorldPoint(new Vector2(cam.pixelWidth, 0f)), snapValue);
Vector3 topLeft = pg_Util.SnapToFloor(cam.ScreenToWorldPoint(new Vector2(0f, cam.pixelHeight)), snapValue);
Vector3 topRight = pg_Util.SnapToFloor(cam.ScreenToWorldPoint(new Vector2(cam.pixelWidth, cam.pixelHeight)), snapValue);
Vector3 axis = VectorWithAxis(camAxis);
float width = Vector3.Distance(bottomLeft, bottomRight);
float height = Vector3.Distance(bottomRight, topRight);
// Shift lines to 10m forward of the camera
bottomLeft += axis*10f;
topRight += axis*10f;
bottomRight += axis*10f;
topLeft += axis*10f;
/**
* Draw Vertical Lines
*/
Vector3 cam_right = cam.transform.right;
Vector3 cam_up = cam.transform.up;
float _snapVal = snapValue;
int segs = (int)Mathf.Ceil(width / _snapVal) + 2;
float n = 2f;
while(segs > MAX_LINES) {
_snapVal = _snapVal*n;
segs = (int)Mathf.Ceil(width / _snapVal ) + 2;
n++;
}
/// Screen start and end
Vector3 bl = cam_right.Sum() > 0 ? pg_Util.SnapToFloor(bottomLeft, cam_right, _snapVal*PRIMARY_COLOR_INCREMENT) : pg_Util.SnapToCeil(bottomLeft, cam_right, _snapVal*PRIMARY_COLOR_INCREMENT);
Vector3 start = bl - cam_up * (height+_snapVal*2);
Vector3 end = bl + cam_up * (height+_snapVal*2);
segs += PRIMARY_COLOR_INCREMENT;
/// The current line start and end
Vector3 line_start = Vector3.zero;
Vector3 line_end = Vector3.zero;
for(int i = -1; i < segs; i++)
{
line_start = start + (i * (cam_right * _snapVal));
line_end = end + (i * (cam_right * _snapVal) );
Handles.color = i % PRIMARY_COLOR_INCREMENT == 0 ? primaryColor : secondaryColor;
Handles.DrawLine( line_start, line_end );
}
/**
* Draw Horizontal Lines
*/
segs = (int)Mathf.Ceil(height / _snapVal) + 2;
n = 2;
while(segs > MAX_LINES) {
_snapVal = _snapVal*n;
segs = (int)Mathf.Ceil(height / _snapVal ) + 2;
n++;
}
Vector3 tl = cam_up.Sum() > 0 ? pg_Util.SnapToCeil(topLeft, cam_up, _snapVal*PRIMARY_COLOR_INCREMENT) : pg_Util.SnapToFloor(topLeft, cam_up, _snapVal*PRIMARY_COLOR_INCREMENT);
start = tl - cam_right * (width+_snapVal*2);
end = tl + cam_right * (width+_snapVal*2);
segs += (int)PRIMARY_COLOR_INCREMENT;
for(int i = -1; i < segs; i++)
{
line_start = start + (i * (-cam_up * _snapVal));
line_end = end + (i * (-cam_up * _snapVal));
Handles.color = i % PRIMARY_COLOR_INCREMENT == 0 ? primaryColor : secondaryColor;
Handles.DrawLine(line_start, line_end);
}
#if PRO
if(drawAngles)
{
Vector3 cen = pg_Util.SnapValue(((topRight + bottomLeft) / 2f), snapValue);
float half = (width > height) ? width : height;
float opposite = Mathf.Tan( Mathf.Deg2Rad*angleValue ) * half;
Vector3 up = cam.transform.up * opposite;
Vector3 right = cam.transform.right * half;
Vector3 bottomLeftAngle = cen - (up+right);
Vector3 topRightAngle = cen + (up+right);
Vector3 bottomRightAngle = cen + (right-up);
Vector3 topLeftAngle = cen + (up-right);
Handles.color = primaryColor;
// y = 1x+1
Handles.DrawLine(bottomLeftAngle, topRightAngle);
// y = -1x-1
Handles.DrawLine(topLeftAngle, bottomRightAngle);
}
#endif
Handles.color = previousColor;
}
#endregion
#region ENUM UTILITY
public SnapUnit SnapUnitWithString(string str)
{
foreach(SnapUnit su in SnapUnit.GetValues(typeof(SnapUnit)))
{
if(su.ToString() == str)
return su;
}
return (SnapUnit)0;
}
public Axis AxisWithVector(Vector3 val)
{
Vector3 v = new Vector3(Mathf.Abs(val.x), Mathf.Abs(val.y), Mathf.Abs(val.z));
if(v.x > v.y && v.x > v.z) {
if(val.x > 0)
return Axis.X;
else
return Axis.NegX;
}
else
if(v.y > v.x && v.y > v.z) {
if(val.y > 0)
return Axis.Y;
else
return Axis.NegY;
}
else {
if(val.z > 0)
return Axis.Z;
else
return Axis.NegZ;
}
}
public Vector3 VectorWithAxis(Axis axis)
{
switch(axis)
{
case Axis.X:
return Vector3.right;
case Axis.Y:
return Vector3.up;
case Axis.Z:
return Vector3.forward;
case Axis.NegX:
return -Vector3.right;
case Axis.NegY:
return -Vector3.up;
case Axis.NegZ:
return -Vector3.forward;
default:
return Vector3.forward;
}
}
public bool IsRounded(Vector3 v)
{
return ( Mathf.Approximately(v.x, 1f) || Mathf.Approximately(v.y, 1f) || Mathf.Approximately(v.z, 1f) ) || v == Vector3.zero;
}
public Vector3 RoundAxis(Vector3 v)
{
return VectorWithAxis(AxisWithVector(v));
}
#endregion
#region MOVING TRANSFORMS
static bool FuzzyEquals(Vector3 lhs, Vector3 rhs)
{
return Mathf.Abs(lhs.x - rhs.x) < .001f && Mathf.Abs(lhs.y - rhs.y) < .001f && Mathf.Abs(lhs.z - rhs.z) < .001f;
}
public void OffsetTransforms(Transform[] trsfrms, Transform ignore, Vector3 offset)
{
foreach(Transform t in trsfrms)
{
if(t != ignore)
t.position += offset;
}
}
void HierarchyWindowChanged()
{
if( Selection.activeTransform != null)
lastPosition = Selection.activeTransform.position;
}
#endregion
#region SETTINGS
public void SetSnapEnabled(bool enable)
{
EditorPrefs.SetBool(pg_Constant.SnapEnabled, enable);
if(Selection.activeTransform)
{
lastTransform = Selection.activeTransform;
lastPosition = Selection.activeTransform.position;
}
snapEnabled = enable;
gridRepaint = true;
RepaintSceneView();
}
public void SetSnapValue(SnapUnit su, float val, int multiplier)
{
int clamp_multiplier = (int)(Mathf.Min(Mathf.Max(25, multiplier), 102400));
float value_multiplier = clamp_multiplier / 100f;
/**
* multiplier is a value modifies the snap val. 100 = no change,
* 50 is half val, 200 is double val, etc.
*/
#if PRO
snapValue = pg_Enum.SnapUnitValue(su) * val * value_multiplier;
RepaintSceneView();
EditorPrefs.SetInt(pg_Constant.GridUnit, (int)su);
EditorPrefs.SetFloat(pg_Constant.SnapValue, val);
EditorPrefs.SetInt(pg_Constant.SnapMultiplier, clamp_multiplier);
// update gui (only necessary when calling with editorpref values)
t_snapValue = val * value_multiplier;
snapUnit = su;
switch(su)
{
case SnapUnit.Inch:
PRIMARY_COLOR_INCREMENT = 12; // blasted imperial units
break;
case SnapUnit.Foot:
PRIMARY_COLOR_INCREMENT = 3;
break;
default:
PRIMARY_COLOR_INCREMENT = 10;
break;
}
gridRepaint = true;
#else
Debug.LogWarning("Ye ought not be seein' this ye scurvy pirate.");
#endif
}
public void SetRenderPlane(Axis axis)
{
offset = 0f;
fullGrid = false;
renderPlane = axis;
EditorPrefs.SetBool(pg_Constant.PerspGrid, fullGrid);
EditorPrefs.SetInt(pg_Constant.GridAxis, (int)renderPlane);
gridRepaint = true;
RepaintSceneView();
}
public void SetGridEnabled(bool enable)
{
drawGrid = enable;
if(!drawGrid)
pg_GridRenderer.Destroy();
EditorPrefs.SetBool("showgrid", enable);
gridRepaint = true;
RepaintSceneView();
}
public void SetDrawAngles(bool enable)
{
drawAngles = enable;
gridRepaint = true;
RepaintSceneView();
}
private void SnapToGrid(Transform[] transforms)
{
Undo.RecordObjects(transforms as Object[], "Snap to Grid");
foreach(Transform t in transforms)
t.position = pg_Util.SnapValue(t.position, snapValue);
gridRepaint = true;
PushToGrid(snapValue);
}
#endregion
#region GLOBAL SETTING
internal bool GetUseAxisConstraints() { return toggleAxisConstraint ? !useAxisConstraints : useAxisConstraints; }
internal float GetSnapValue() { return snapValue; }
internal bool GetSnapEnabled() { return (toggleTempSnap ? !snapEnabled : snapEnabled); }
/**
* Returns the value of useAxisConstraints, accounting for the shortcut key toggle.
*/
public static bool UseAxisConstraints()
{
return instance != null ? instance.GetUseAxisConstraints() : false;
}
/**
* Return the current snap value.
*/
public static float SnapValue()
{
return instance != null ? instance.GetSnapValue() : 0f;
}
/**
* Return true if snapping is enabled, false otherwise.
*/
public static bool SnapEnabled()
{
return instance == null ? false : instance.GetSnapEnabled();
}
public static void AddPushToGridListener(System.Action<float> listener)
{
pushToGridListeners.Add(listener);
}
public static void RemovePushToGridListener(System.Action<float> listener)
{
pushToGridListeners.Remove(listener);
}
public static void AddToolbarEventSubscriber(System.Action<bool> listener)
{
toolbarEventSubscribers.Add(listener);
}
public static void RemoveToolbarEventSubscriber(System.Action<bool> listener)
{
toolbarEventSubscribers.Remove(listener);
}
public static bool SceneToolbarActive()
{
return instance != null;
}
[SerializeField] static List<System.Action<float>> pushToGridListeners = new List<System.Action<float>>();
[SerializeField] static List<System.Action<bool>> toolbarEventSubscribers = new List<System.Action<bool>>();
private void PushToGrid(float snapValue)
{
foreach(System.Action<float> listener in pushToGridListeners)
listener(snapValue);
}
public static void OnHandleMove(Vector3 worldDirection)
{
if (instance != null)
instance.OnHandleMove_Internal(worldDirection);
}
private void OnHandleMove_Internal(Vector3 worldDirection)
{
if( predictiveGrid && firstMove && !fullGrid )
{
firstMove = false;
Axis dragAxis = pg_Util.CalcDragAxis(worldDirection, SceneView.lastActiveSceneView.camera);
if(dragAxis != Axis.None && dragAxis != renderPlane)
SetRenderPlane(dragAxis);
}
}
#endregion
}
}
| |
using System.Collections.Generic;
namespace UnityEngine.Rendering.PostProcessing
{
#if UNITY_2017_2_OR_NEWER
using XRSettings = UnityEngine.XR.XRSettings;
#elif UNITY_5_6_OR_NEWER
using XRSettings = UnityEngine.VR.VRSettings;
#endif
// Context object passed around all post-fx in a frame
public sealed class PostProcessRenderContext
{
// -----------------------------------------------------------------------------------------
// The following should be filled by the render pipeline
// Camera currently rendering
Camera m_Camera;
public Camera camera
{
get { return m_Camera; }
set
{
m_Camera = value;
if (m_Camera.stereoEnabled)
{
#if UNITY_2017_2_OR_NEWER
var xrDesc = XRSettings.eyeTextureDesc;
width = xrDesc.width;
height = xrDesc.height;
m_sourceDescriptor = xrDesc;
#else
// Single-pass is only supported with 2017.2+ because
// that is when XRSettings.eyeTextureDesc is available.
// Without it, we don't have a robust method of determining
// if we are in single-pass. Users can just double the width
// here if they KNOW they are using single-pass.
width = XRSettings.eyeTextureWidth;
height = XRSettings.eyeTextureHeight;
#endif
if (m_Camera.stereoActiveEye == Camera.MonoOrStereoscopicEye.Right)
xrActiveEye = (int)Camera.StereoscopicEye.Right;
screenWidth = XRSettings.eyeTextureWidth;
screenHeight = XRSettings.eyeTextureHeight;
stereoActive = true;
}
else
{
width = m_Camera.pixelWidth;
height = m_Camera.pixelHeight;
#if UNITY_2017_2_OR_NEWER
m_sourceDescriptor.width = width;
m_sourceDescriptor.height = height;
#endif
screenWidth = width;
screenHeight = height;
stereoActive = false;
}
}
}
// The command buffer to fill in
public CommandBuffer command { get; set; }
// Source target (can't be the same as destination)
public RenderTargetIdentifier source { get; set; }
// Destination target (can't be the same as source)
public RenderTargetIdentifier destination { get; set; }
// Texture format used for the source target
// We need this to be set explictely as we don't have any way of knowing if we're rendering
// using HDR or not as scriptable render pipelines may ignore the HDR toggle on camera
// completely
public RenderTextureFormat sourceFormat { get; set; }
// Should we flip the last pass?
public bool flip { get; set; }
// -----------------------------------------------------------------------------------------
// The following is auto-populated by the post-processing stack
// Contains references to external resources (shaders, builtin textures...)
public PostProcessResources resources { get; internal set; }
// Property sheet factory handled by the currently active PostProcessLayer
public PropertySheetFactory propertySheets { get; internal set; }
// Custom user data objects (unused by builtin effects, feel free to store whatever you want
// in this dictionary)
public Dictionary<string, object> userData { get; private set; }
// Reference to the internal debug layer
public PostProcessDebugLayer debugLayer { get; internal set; }
// Current camera width in pixels
public int width { get; private set; }
// Current camera height in pixels
public int height { get; private set; }
public bool stereoActive { get; private set; }
// Current active rendering eye (for XR)
public int xrActiveEye { get; private set; }
// Pixel dimensions of logical screen size
public int screenWidth { get; private set; }
public int screenHeight { get; private set; }
// Are we currently rendering in the scene view?
public bool isSceneView { get; internal set; }
// Current antialiasing method set
public PostProcessLayer.Antialiasing antialiasing { get; internal set; }
// Mostly used to grab the jitter vector and other TAA-related values when an effect needs
// to do temporal reprojection (see: Depth of Field)
public TemporalAntialiasing temporalAntialiasing { get; internal set; }
// Internal values used for builtin effects
// Beware, these may not have been set before a specific builtin effect has been executed
internal PropertySheet uberSheet;
internal Texture autoExposureTexture;
internal LogHistogram logHistogram;
internal Texture logLut;
internal AutoExposure autoExposure;
internal int bloomBufferNameID;
public void Reset()
{
m_Camera = null;
width = 0;
height = 0;
#if UNITY_2017_2_OR_NEWER
m_sourceDescriptor = new RenderTextureDescriptor(0, 0);
#endif
stereoActive = false;
xrActiveEye = (int)Camera.StereoscopicEye.Left;
screenWidth = 0;
screenHeight = 0;
command = null;
source = 0;
destination = 0;
sourceFormat = RenderTextureFormat.ARGB32;
flip = false;
resources = null;
propertySheets = null;
debugLayer = null;
isSceneView = false;
antialiasing = PostProcessLayer.Antialiasing.None;
temporalAntialiasing = null;
uberSheet = null;
autoExposureTexture = null;
logLut = null;
autoExposure = null;
bloomBufferNameID = -1;
if (userData == null)
userData = new Dictionary<string, object>();
userData.Clear();
}
// Checks if TAA is enabled & supported
public bool IsTemporalAntialiasingActive()
{
return antialiasing == PostProcessLayer.Antialiasing.TemporalAntialiasing
&& !isSceneView
&& temporalAntialiasing.IsSupported();
}
// Checks if a specific debug overlay is enabled
public bool IsDebugOverlayEnabled(DebugOverlay overlay)
{
return debugLayer.debugOverlay == overlay;
}
// Shortcut function
public void PushDebugOverlay(CommandBuffer cmd, RenderTargetIdentifier source, PropertySheet sheet, int pass)
{
debugLayer.PushDebugOverlay(cmd, source, sheet, pass);
}
// TODO: Change w/h name to texture w/h in order to make
// size usages explicit
#if UNITY_2017_2_OR_NEWER
RenderTextureDescriptor m_sourceDescriptor;
RenderTextureDescriptor GetDescriptor(int depthBufferBits = 0, RenderTextureFormat colorFormat = RenderTextureFormat.Default, RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default)
{
var modifiedDesc = new RenderTextureDescriptor(m_sourceDescriptor.width, m_sourceDescriptor.height,
m_sourceDescriptor.colorFormat, depthBufferBits);
modifiedDesc.dimension = m_sourceDescriptor.dimension;
modifiedDesc.volumeDepth = m_sourceDescriptor.volumeDepth;
modifiedDesc.vrUsage = m_sourceDescriptor.vrUsage;
modifiedDesc.msaaSamples = m_sourceDescriptor.msaaSamples;
modifiedDesc.memoryless = m_sourceDescriptor.memoryless;
modifiedDesc.useMipMap = m_sourceDescriptor.useMipMap;
modifiedDesc.autoGenerateMips = m_sourceDescriptor.autoGenerateMips;
modifiedDesc.enableRandomWrite = m_sourceDescriptor.enableRandomWrite;
modifiedDesc.shadowSamplingMode = m_sourceDescriptor.shadowSamplingMode;
if (colorFormat != RenderTextureFormat.Default)
modifiedDesc.colorFormat = colorFormat;
modifiedDesc.sRGB = readWrite != RenderTextureReadWrite.Linear;
return modifiedDesc;
}
#endif
public void GetScreenSpaceTemporaryRT(CommandBuffer cmd, int nameID,
int depthBufferBits = 0, RenderTextureFormat colorFormat = RenderTextureFormat.Default, RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default,
FilterMode filter = FilterMode.Bilinear, int widthOverride = 0, int heightOverride = 0)
{
#if UNITY_2017_2_OR_NEWER
var desc = GetDescriptor(depthBufferBits, colorFormat, readWrite);
if (widthOverride > 0)
desc.width = widthOverride;
if (heightOverride > 0)
desc.height = heightOverride;
cmd.GetTemporaryRT(nameID, desc, filter);
#else
int actualWidth = width;
int actualHeight = height;
if (widthOverride > 0)
actualWidth = widthOverride;
if (heightOverride > 0)
actualHeight = heightOverride;
cmd.GetTemporaryRT(nameID, actualWidth, actualHeight, depthBufferBits, filter, colorFormat, readWrite);
// TODO: How to handle MSAA for XR in older versions? Query cam?
// TODO: Pass in vrUsage into the args
#endif
}
public RenderTexture GetScreenSpaceTemporaryRT(int depthBufferBits = 0, RenderTextureFormat colorFormat = RenderTextureFormat.Default,
RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default, int widthOverride = 0, int heightOverride = 0)
{
#if UNITY_2017_2_OR_NEWER
var desc = GetDescriptor(depthBufferBits, colorFormat, readWrite);
if (widthOverride > 0)
desc.width = widthOverride;
if (heightOverride > 0)
desc.height = heightOverride;
return RenderTexture.GetTemporary(desc);
#else
int actualWidth = width;
int actualHeight = height;
if (widthOverride > 0)
actualWidth = widthOverride;
if (heightOverride > 0)
actualHeight = heightOverride;
return RenderTexture.GetTemporary(actualWidth, actualHeight, depthBufferBits, colorFormat, readWrite);
#endif
}
}
}
| |
// 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!
namespace Google.Cloud.AIPlatform.V1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.LongRunning;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedMigrationServiceClientSnippets
{
/// <summary>Snippet for SearchMigratableResources</summary>
public void SearchMigratableResourcesRequestObject()
{
// Snippet: SearchMigratableResources(SearchMigratableResourcesRequest, CallSettings)
// Create client
MigrationServiceClient migrationServiceClient = MigrationServiceClient.Create();
// Initialize request argument(s)
SearchMigratableResourcesRequest request = new SearchMigratableResourcesRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Filter = "",
};
// Make the request
PagedEnumerable<SearchMigratableResourcesResponse, MigratableResource> response = migrationServiceClient.SearchMigratableResources(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (MigratableResource item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SearchMigratableResourcesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MigratableResource item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MigratableResource> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MigratableResource item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchMigratableResourcesAsync</summary>
public async Task SearchMigratableResourcesRequestObjectAsync()
{
// Snippet: SearchMigratableResourcesAsync(SearchMigratableResourcesRequest, CallSettings)
// Create client
MigrationServiceClient migrationServiceClient = await MigrationServiceClient.CreateAsync();
// Initialize request argument(s)
SearchMigratableResourcesRequest request = new SearchMigratableResourcesRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Filter = "",
};
// Make the request
PagedAsyncEnumerable<SearchMigratableResourcesResponse, MigratableResource> response = migrationServiceClient.SearchMigratableResourcesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((MigratableResource item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SearchMigratableResourcesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MigratableResource item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MigratableResource> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MigratableResource item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchMigratableResources</summary>
public void SearchMigratableResources()
{
// Snippet: SearchMigratableResources(string, string, int?, CallSettings)
// Create client
MigrationServiceClient migrationServiceClient = MigrationServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedEnumerable<SearchMigratableResourcesResponse, MigratableResource> response = migrationServiceClient.SearchMigratableResources(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (MigratableResource item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SearchMigratableResourcesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MigratableResource item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MigratableResource> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MigratableResource item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchMigratableResourcesAsync</summary>
public async Task SearchMigratableResourcesAsync()
{
// Snippet: SearchMigratableResourcesAsync(string, string, int?, CallSettings)
// Create client
MigrationServiceClient migrationServiceClient = await MigrationServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedAsyncEnumerable<SearchMigratableResourcesResponse, MigratableResource> response = migrationServiceClient.SearchMigratableResourcesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((MigratableResource item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SearchMigratableResourcesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MigratableResource item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MigratableResource> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MigratableResource item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchMigratableResources</summary>
public void SearchMigratableResourcesResourceNames()
{
// Snippet: SearchMigratableResources(LocationName, string, int?, CallSettings)
// Create client
MigrationServiceClient migrationServiceClient = MigrationServiceClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedEnumerable<SearchMigratableResourcesResponse, MigratableResource> response = migrationServiceClient.SearchMigratableResources(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (MigratableResource item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SearchMigratableResourcesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MigratableResource item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MigratableResource> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MigratableResource item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchMigratableResourcesAsync</summary>
public async Task SearchMigratableResourcesResourceNamesAsync()
{
// Snippet: SearchMigratableResourcesAsync(LocationName, string, int?, CallSettings)
// Create client
MigrationServiceClient migrationServiceClient = await MigrationServiceClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedAsyncEnumerable<SearchMigratableResourcesResponse, MigratableResource> response = migrationServiceClient.SearchMigratableResourcesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((MigratableResource item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SearchMigratableResourcesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MigratableResource item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MigratableResource> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MigratableResource item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for BatchMigrateResources</summary>
public void BatchMigrateResourcesRequestObject()
{
// Snippet: BatchMigrateResources(BatchMigrateResourcesRequest, CallSettings)
// Create client
MigrationServiceClient migrationServiceClient = MigrationServiceClient.Create();
// Initialize request argument(s)
BatchMigrateResourcesRequest request = new BatchMigrateResourcesRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
MigrateResourceRequests =
{
new MigrateResourceRequest(),
},
};
// Make the request
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> response = migrationServiceClient.BatchMigrateResources(request);
// Poll until the returned long-running operation is complete
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
BatchMigrateResourcesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> retrievedResponse = migrationServiceClient.PollOnceBatchMigrateResources(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
BatchMigrateResourcesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for BatchMigrateResourcesAsync</summary>
public async Task BatchMigrateResourcesRequestObjectAsync()
{
// Snippet: BatchMigrateResourcesAsync(BatchMigrateResourcesRequest, CallSettings)
// Additional: BatchMigrateResourcesAsync(BatchMigrateResourcesRequest, CancellationToken)
// Create client
MigrationServiceClient migrationServiceClient = await MigrationServiceClient.CreateAsync();
// Initialize request argument(s)
BatchMigrateResourcesRequest request = new BatchMigrateResourcesRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
MigrateResourceRequests =
{
new MigrateResourceRequest(),
},
};
// Make the request
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> response = await migrationServiceClient.BatchMigrateResourcesAsync(request);
// Poll until the returned long-running operation is complete
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
BatchMigrateResourcesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> retrievedResponse = await migrationServiceClient.PollOnceBatchMigrateResourcesAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
BatchMigrateResourcesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for BatchMigrateResources</summary>
public void BatchMigrateResources()
{
// Snippet: BatchMigrateResources(string, IEnumerable<MigrateResourceRequest>, CallSettings)
// Create client
MigrationServiceClient migrationServiceClient = MigrationServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
IEnumerable<MigrateResourceRequest> migrateResourceRequests = new MigrateResourceRequest[]
{
new MigrateResourceRequest(),
};
// Make the request
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> response = migrationServiceClient.BatchMigrateResources(parent, migrateResourceRequests);
// Poll until the returned long-running operation is complete
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
BatchMigrateResourcesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> retrievedResponse = migrationServiceClient.PollOnceBatchMigrateResources(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
BatchMigrateResourcesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for BatchMigrateResourcesAsync</summary>
public async Task BatchMigrateResourcesAsync()
{
// Snippet: BatchMigrateResourcesAsync(string, IEnumerable<MigrateResourceRequest>, CallSettings)
// Additional: BatchMigrateResourcesAsync(string, IEnumerable<MigrateResourceRequest>, CancellationToken)
// Create client
MigrationServiceClient migrationServiceClient = await MigrationServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
IEnumerable<MigrateResourceRequest> migrateResourceRequests = new MigrateResourceRequest[]
{
new MigrateResourceRequest(),
};
// Make the request
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> response = await migrationServiceClient.BatchMigrateResourcesAsync(parent, migrateResourceRequests);
// Poll until the returned long-running operation is complete
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
BatchMigrateResourcesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> retrievedResponse = await migrationServiceClient.PollOnceBatchMigrateResourcesAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
BatchMigrateResourcesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for BatchMigrateResources</summary>
public void BatchMigrateResourcesResourceNames()
{
// Snippet: BatchMigrateResources(LocationName, IEnumerable<MigrateResourceRequest>, CallSettings)
// Create client
MigrationServiceClient migrationServiceClient = MigrationServiceClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
IEnumerable<MigrateResourceRequest> migrateResourceRequests = new MigrateResourceRequest[]
{
new MigrateResourceRequest(),
};
// Make the request
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> response = migrationServiceClient.BatchMigrateResources(parent, migrateResourceRequests);
// Poll until the returned long-running operation is complete
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
BatchMigrateResourcesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> retrievedResponse = migrationServiceClient.PollOnceBatchMigrateResources(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
BatchMigrateResourcesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for BatchMigrateResourcesAsync</summary>
public async Task BatchMigrateResourcesResourceNamesAsync()
{
// Snippet: BatchMigrateResourcesAsync(LocationName, IEnumerable<MigrateResourceRequest>, CallSettings)
// Additional: BatchMigrateResourcesAsync(LocationName, IEnumerable<MigrateResourceRequest>, CancellationToken)
// Create client
MigrationServiceClient migrationServiceClient = await MigrationServiceClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
IEnumerable<MigrateResourceRequest> migrateResourceRequests = new MigrateResourceRequest[]
{
new MigrateResourceRequest(),
};
// Make the request
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> response = await migrationServiceClient.BatchMigrateResourcesAsync(parent, migrateResourceRequests);
// Poll until the returned long-running operation is complete
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
BatchMigrateResourcesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<BatchMigrateResourcesResponse, BatchMigrateResourcesOperationMetadata> retrievedResponse = await migrationServiceClient.PollOnceBatchMigrateResourcesAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
BatchMigrateResourcesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Forms.Platform.Android.AppCompat;
using Xamarin.Forms;
using Android.Support.Design.Widget;
using Android.Views;
using Android.Widget;
using Xamarin.Forms.Platform.Android;
using eShopOnContainers.Droid.Extensions;
using eShopOnContainers.Core.Controls;
using eShopOnContainers.Droid.Renderers;
using Android.Support.V4.View;
using Android.Graphics;
[assembly: ExportRenderer(typeof(TabbedPage), typeof(CustomTabbedPageRenderer))]
namespace eShopOnContainers.Droid.Renderers
{
public class CustomTabbedPageRenderer : TabbedPageRenderer
{
private const int DeleayBeforeTabAdded = 10;
protected readonly Dictionary<Element, BadgeView> BadgeViews = new Dictionary<Element, BadgeView>();
private TabLayout _tabLayout;
private TabLayout.SlidingTabStrip _tabStrip;
private ViewPager _viewPager;
private TabbedPage _tabbedPage;
private bool _firstTime = true;
protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
{
base.OnElementChanged(e);
_tabLayout = ViewGroup.FindChildOfType<TabLayout>();
if (_tabLayout == null)
{
Console.WriteLine("No TabLayout found. Badge not added.");
return;
}
_tabbedPage = e.NewElement as TabbedPage;
_viewPager = (ViewPager)GetChildAt(0);
_tabLayout.TabSelected += (s, a) =>
{
var page = _tabbedPage.Children[a.Tab.Position];
if (page is TabbedPage)
{
var tabPage = (TabbedPage)page;
SetTab(a.Tab, tabPage.Icon.File);
}
_viewPager.SetCurrentItem(a.Tab.Position, false);
};
_tabLayout.TabUnselected += (s, a) =>
{
var page = _tabbedPage.Children[a.Tab.Position];
if (page is TabbedPage)
{
SetTab(a.Tab, page.Icon.File);
}
};
_tabStrip = _tabLayout.FindChildOfType<TabLayout.SlidingTabStrip>();
for (var i = 0; i < _tabLayout.TabCount; i++)
{
AddTabBadge(i);
}
Element.ChildAdded += OnTabAdded;
Element.ChildRemoved += OnTabRemoved;
}
private void SetTab(TabLayout.Tab tab, string name)
{
try
{
int id = Resources.GetIdentifier(name, "drawable", Context.PackageName);
tab.SetIcon(null);
LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
linearLayoutParams.SetMargins(0, -48, 0, 0);
ImageView img = new ImageView(Context);
img.LayoutParameters = linearLayoutParams;
img.SetPadding(0, 0, 0, 48);
img.SetImageResource(id);
tab.SetCustomView(img);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
}
protected override void DispatchDraw(Canvas canvas)
{
base.DispatchDraw(canvas);
if (!_firstTime)
{
return;
}
for (int i = 0; i < _tabLayout.TabCount; i++)
{
var tab = _tabLayout.GetTabAt(i);
var page = _tabbedPage.Children[tab.Position];
if (page is TabbedPage)
{
var tabbedPage = (TabbedPage)page;
SetTab(tab, tabbedPage.Icon.File);
}
else
{
SetTab(tab, page.Icon.File);
}
if (!string.IsNullOrEmpty(_tabbedPage.Title))
{
tab.SetText(string.Empty);
}
}
_firstTime = false;
}
private void AddTabBadge(int tabIndex)
{
var element = Element.Children[tabIndex];
var view = _tabLayout?.GetTabAt(tabIndex).CustomView ?? _tabStrip?.GetChildAt(tabIndex);
var badgeView = (view as ViewGroup)?.FindChildOfType<BadgeView>();
if (badgeView == null)
{
var imageView = (view as ViewGroup)?.FindChildOfType<ImageView>();
var badgeTarget = imageView?.Drawable != null
? (Android.Views.View)imageView
: (view as ViewGroup)?.FindChildOfType<TextView>();
// Create badge for tab
badgeView = new BadgeView(Context, badgeTarget);
}
BadgeViews[element] = badgeView;
// Get text
var badgeText = CustomTabbedPage.GetBadgeText(element);
badgeView.Text = badgeText;
// Set color if not default
var tabColor = CustomTabbedPage.GetBadgeColor(element);
if (tabColor != Xamarin.Forms.Color.Default)
{
badgeView.BadgeColor = tabColor.ToAndroid();
}
element.PropertyChanged += OnTabbedPagePropertyChanged;
}
protected virtual void OnTabbedPagePropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
var element = sender as Element;
if (element == null)
return;
BadgeView badgeView;
if (!BadgeViews.TryGetValue(element, out badgeView))
{
return;
}
if (e.PropertyName == CustomTabbedPage.BadgeTextProperty.PropertyName)
{
badgeView.Text = CustomTabbedPage.GetBadgeText(element);
return;
}
if (e.PropertyName == CustomTabbedPage.BadgeColorProperty.PropertyName)
{
badgeView.BadgeColor = CustomTabbedPage.GetBadgeColor(element).ToAndroid();
}
}
private void OnTabRemoved(object sender, ElementEventArgs e)
{
e.Element.PropertyChanged -= OnTabbedPagePropertyChanged;
BadgeViews.Remove(e.Element);
}
private async void OnTabAdded(object sender, ElementEventArgs e)
{
await Task.Delay(DeleayBeforeTabAdded);
var page = e.Element as Page;
if (page == null)
return;
var tabIndex = Element.Children.IndexOf(page);
AddTabBadge(tabIndex);
}
protected override void Dispose(bool disposing)
{
if (Element != null)
{
foreach (var tab in Element.Children)
{
tab.PropertyChanged -= OnTabbedPagePropertyChanged;
}
Element.ChildRemoved -= OnTabRemoved;
Element.ChildAdded -= OnTabAdded;
BadgeViews.Clear();
}
base.Dispose(disposing);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class InteropTests
{
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public static void TestHandle()
{
//
// Ensure that the Handle property returns a valid CER_CONTEXT pointer.
//
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
{
IntPtr h = c.Handle;
unsafe
{
CERT_CONTEXT* pCertContext = (CERT_CONTEXT*)h;
// Does the blob data match?
int cbCertEncoded = pCertContext->cbCertEncoded;
Assert.Equal(TestData.MsCertificate.Length, cbCertEncoded);
byte[] pCertEncoded = new byte[cbCertEncoded];
Marshal.Copy((IntPtr)(pCertContext->pbCertEncoded), pCertEncoded, 0, cbCertEncoded);
Assert.Equal(TestData.MsCertificate, pCertEncoded);
// Does the serial number match?
CERT_INFO* pCertInfo = pCertContext->pCertInfo;
byte[] serialNumber = pCertInfo->SerialNumber.ToByteArray();
byte[] expectedSerial = "b00000000100dd9f3bd08b0aaf11b000000033".HexToByteArray();
Assert.Equal(expectedSerial, serialNumber);
}
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public static void TestHandleCtor()
{
IntPtr pCertContext = IntPtr.Zero;
unsafe
{
byte[] rawData = TestData.MsCertificate;
fixed (byte* pRawData = rawData)
{
CRYPTOAPI_BLOB certBlob = new CRYPTOAPI_BLOB() { cbData = rawData.Length, pbData = pRawData };
bool success = CryptQueryObject(
CertQueryObjectType.CERT_QUERY_OBJECT_BLOB,
ref certBlob,
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_CERT,
ExpectedFormatTypeFlags.CERT_QUERY_FORMAT_FLAG_BINARY,
0,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
out pCertContext
);
if (!success)
{
int hr = Marshal.GetHRForLastWin32Error();
throw new CryptographicException(hr);
}
}
}
// Now, create an X509Certificate around our handle.
using (X509Certificate2 c = new X509Certificate2(pCertContext))
{
// And release our ref-count on the handle. X509Certificate better be maintaining its own.
CertFreeCertificateContext(pCertContext);
// Now, test various properties to make sure the X509Certificate actually wraps our CERT_CONTEXT.
IntPtr h = c.Handle;
Assert.Equal(pCertContext, h);
pCertContext = IntPtr.Zero;
string issuer = c.Issuer;
Assert.Equal(
"CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US",
issuer);
byte[] expectedPublicKey = (
"3082010a0282010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb" +
"407db38e33e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb" +
"137688b02cf0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bba" +
"b95c759316524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1" +
"109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd" +
"2f826a8103f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c425" +
"2e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b2801" +
"84b82a29cfbfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec643" +
"0b950005b14f6571c50203010001").HexToByteArray();
byte[] publicKey = c.GetPublicKey();
Assert.Equal(expectedPublicKey, publicKey);
byte[] expectedThumbPrint = "108e2ba23632620c427c570b6d9db51ac31387fe".HexToByteArray();
byte[] thumbPrint = c.GetCertHash();
Assert.Equal(expectedThumbPrint, thumbPrint);
}
}
[DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CryptQueryObject(
CertQueryObjectType dwObjectType,
[In] ref CRYPTOAPI_BLOB pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
IntPtr pdwMsgAndCertEncodingType,
IntPtr pdwContentType,
IntPtr pdwFormatType,
IntPtr phCertStore,
IntPtr phMsg,
out IntPtr ppvContext
);
[DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CertFreeCertificateContext(IntPtr pCertContext);
private enum CertQueryObjectType : int
{
CERT_QUERY_OBJECT_FILE = 0x00000001,
CERT_QUERY_OBJECT_BLOB = 0x00000002,
}
[Flags]
private enum ExpectedContentTypeFlags : int
{
//encoded single certificate
CERT_QUERY_CONTENT_FLAG_CERT = 1 << ContentType.CERT_QUERY_CONTENT_CERT,
//encoded single CTL
CERT_QUERY_CONTENT_FLAG_CTL = 1 << ContentType.CERT_QUERY_CONTENT_CTL,
//encoded single CRL
CERT_QUERY_CONTENT_FLAG_CRL = 1 << ContentType.CERT_QUERY_CONTENT_CRL,
//serialized store
CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_STORE,
//serialized single certificate
CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CERT,
//serialized single CTL
CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CTL,
//serialized single CRL
CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CRL,
//an encoded PKCS#7 signed message
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED,
//an encoded PKCS#7 message. But it is not a signed message
CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_UNSIGNED,
//the content includes an embedded PKCS7 signed message
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED,
//an encoded PKCS#10
CERT_QUERY_CONTENT_FLAG_PKCS10 = 1 << ContentType.CERT_QUERY_CONTENT_PKCS10,
//an encoded PFX BLOB
CERT_QUERY_CONTENT_FLAG_PFX = 1 << ContentType.CERT_QUERY_CONTENT_PFX,
//an encoded CertificatePair (contains forward and/or reverse cross certs)
CERT_QUERY_CONTENT_FLAG_CERT_PAIR = 1 << ContentType.CERT_QUERY_CONTENT_CERT_PAIR,
//an encoded PFX BLOB, and we do want to load it (not included in
//CERT_QUERY_CONTENT_FLAG_ALL)
CERT_QUERY_CONTENT_FLAG_PFX_AND_LOAD = 1 << ContentType.CERT_QUERY_CONTENT_PFX_AND_LOAD,
}
[Flags]
private enum ExpectedFormatTypeFlags : int
{
CERT_QUERY_FORMAT_FLAG_BINARY = 1 << FormatType.CERT_QUERY_FORMAT_BINARY,
CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED = 1 << FormatType.CERT_QUERY_FORMAT_BASE64_ENCODED,
CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED = 1 << FormatType.CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED,
CERT_QUERY_FORMAT_FLAG_ALL = CERT_QUERY_FORMAT_FLAG_BINARY | CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED | CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED,
}
private enum MsgAndCertEncodingType : int
{
PKCS_7_ASN_ENCODING = 0x10000,
X509_ASN_ENCODING = 0x1,
}
private enum ContentType : int
{
//encoded single certificate
CERT_QUERY_CONTENT_CERT = 1,
//encoded single CTL
CERT_QUERY_CONTENT_CTL = 2,
//encoded single CRL
CERT_QUERY_CONTENT_CRL = 3,
//serialized store
CERT_QUERY_CONTENT_SERIALIZED_STORE = 4,
//serialized single certificate
CERT_QUERY_CONTENT_SERIALIZED_CERT = 5,
//serialized single CTL
CERT_QUERY_CONTENT_SERIALIZED_CTL = 6,
//serialized single CRL
CERT_QUERY_CONTENT_SERIALIZED_CRL = 7,
//a PKCS#7 signed message
CERT_QUERY_CONTENT_PKCS7_SIGNED = 8,
//a PKCS#7 message, such as enveloped message. But it is not a signed message,
CERT_QUERY_CONTENT_PKCS7_UNSIGNED = 9,
//a PKCS7 signed message embedded in a file
CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED = 10,
//an encoded PKCS#10
CERT_QUERY_CONTENT_PKCS10 = 11,
//an encoded PFX BLOB
CERT_QUERY_CONTENT_PFX = 12,
//an encoded CertificatePair (contains forward and/or reverse cross certs)
CERT_QUERY_CONTENT_CERT_PAIR = 13,
//an encoded PFX BLOB, which was loaded to phCertStore
CERT_QUERY_CONTENT_PFX_AND_LOAD = 14,
}
private enum FormatType : int
{
CERT_QUERY_FORMAT_BINARY = 1,
CERT_QUERY_FORMAT_BASE64_ENCODED = 2,
CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED = 3,
}
// CRYPTOAPI_BLOB has many typedef aliases in the C++ world (CERT_BLOB, DATA_BLOB, etc.) We'll just stick to one name here.
[StructLayout(LayoutKind.Sequential)]
private unsafe struct CRYPTOAPI_BLOB
{
public int cbData;
public byte* pbData;
public byte[] ToByteArray()
{
byte[] array = new byte[cbData];
Marshal.Copy((IntPtr)pbData, array, 0, cbData);
return array;
}
}
[StructLayout(LayoutKind.Sequential)]
private unsafe struct CERT_CONTEXT
{
public readonly MsgAndCertEncodingType dwCertEncodingType;
public readonly byte* pbCertEncoded;
public readonly int cbCertEncoded;
public readonly CERT_INFO* pCertInfo;
public readonly IntPtr hCertStore;
}
[StructLayout(LayoutKind.Sequential)]
private unsafe struct CERT_INFO
{
public readonly int dwVersion;
public CRYPTOAPI_BLOB SerialNumber;
public readonly CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm;
public readonly CRYPTOAPI_BLOB Issuer;
public readonly FILETIME NotBefore;
public readonly FILETIME NotAfter;
public readonly CRYPTOAPI_BLOB Subject;
public readonly CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo;
public readonly CRYPT_BIT_BLOB IssuerUniqueId;
public readonly CRYPT_BIT_BLOB SubjectUniqueId;
public readonly int cExtension;
public readonly CERT_EXTENSION* rgExtension;
}
[StructLayout(LayoutKind.Sequential)]
private struct CRYPT_ALGORITHM_IDENTIFIER
{
public readonly IntPtr pszObjId;
public readonly CRYPTOAPI_BLOB Parameters;
}
[StructLayout(LayoutKind.Sequential)]
private struct CERT_PUBLIC_KEY_INFO
{
public readonly CRYPT_ALGORITHM_IDENTIFIER Algorithm;
public readonly CRYPT_BIT_BLOB PublicKey;
}
[StructLayout(LayoutKind.Sequential)]
private unsafe struct CRYPT_BIT_BLOB
{
public readonly int cbData;
public readonly byte* pbData;
public readonly int cUnusedBits;
public byte[] ToByteArray()
{
byte[] array = new byte[cbData];
Marshal.Copy((IntPtr)pbData, array, 0, cbData);
return array;
}
}
[StructLayout(LayoutKind.Sequential)]
private unsafe struct CERT_EXTENSION
{
public readonly IntPtr pszObjId;
public readonly int fCritical;
public readonly CRYPTOAPI_BLOB Value;
}
[StructLayout(LayoutKind.Sequential)]
private struct FILETIME
{
private readonly uint _ftTimeLow;
private readonly uint _ftTimeHigh;
public DateTime ToDateTime()
{
long fileTime = (((long)_ftTimeHigh) << 32) + _ftTimeLow;
return DateTime.FromFileTime(fileTime);
}
}
}
}
| |
/* This file is part of SevenZipSharp.
SevenZipSharp 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 3 of the License, or
(at your option) any later version.
SevenZipSharp 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 SevenZipSharp. If not, see <http://www.gnu.org/licenses/>.
*/
using BizHawk.Common;
using System;
using System.Collections.Generic;
#if !WINCE && !MONO
using System.Configuration;
using System.Diagnostics;
using System.Security.Permissions;
#endif
#if WINCE
using OpenNETCF.Diagnostics;
#endif
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
#if MONO
using SevenZip.Mono.COM;
#endif
namespace SevenZip
{
#if UNMANAGED
/// <summary>
/// 7-zip library low-level wrapper.
/// </summary>
internal static class SevenZipLibraryManager
{
/// <summary>
/// Synchronization root for all locking.
/// </summary>
private static readonly object _syncRoot = new object();
#if !WINCE && !MONO
//zero 07-jul-2014 - no sense for this industrial strength enterprise bullshit. lets just hack it to our needs.
//NOTE - I think we hacked this originally.. it was this way from the initial commit, perhaps it had already been modified for our use
/// <summary>
/// Path to the 7-zip dll.
/// </summary>
/// <remarks>7zxa.dll supports only decoding from .7z archives.
/// Features of 7za.dll:
/// - Supporting 7z format;
/// - Built encoders: LZMA, PPMD, BCJ, BCJ2, COPY, AES-256 Encryption.
/// - Built decoders: LZMA, PPMD, BCJ, BCJ2, COPY, AES-256 Encryption, BZip2, Deflate.
/// 7z.dll (from the 7-zip distribution) supports every InArchiveFormat for encoding and decoding.
/// </remarks>
//private static string _libraryFileName = ConfigurationManager.AppSettings["7zLocation"] ?? Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "7z.dll");
private static string _libraryFileName = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "dll\\7z.dll");
#endif
#if WINCE
private static string _libraryFileName =
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase), "7z.dll");
#endif
/// <summary>
/// 7-zip library handle.
/// </summary>
private static IntPtr _modulePtr;
/// <summary>
/// 7-zip library features.
/// </summary>
private static LibraryFeature? _features;
private static Dictionary<object, Dictionary<InArchiveFormat, IInArchive>> _inArchives;
#if COMPRESS
private static Dictionary<object, Dictionary<OutArchiveFormat, IOutArchive>> _outArchives;
#endif
private static int _totalUsers;
// private static string _LibraryVersion;
private static bool? _modifyCapabale;
private static readonly OSTailoredCode.ILinkedLibManager libLoader = OSTailoredCode.LinkedLibManager;
private static void InitUserInFormat(object user, InArchiveFormat format)
{
if (!_inArchives.ContainsKey(user))
{
_inArchives.Add(user, new Dictionary<InArchiveFormat, IInArchive>());
}
if (!_inArchives[user].ContainsKey(format))
{
_inArchives[user].Add(format, null);
_totalUsers++;
}
}
#if COMPRESS
private static void InitUserOutFormat(object user, OutArchiveFormat format)
{
if (!_outArchives.ContainsKey(user))
{
_outArchives.Add(user, new Dictionary<OutArchiveFormat, IOutArchive>());
}
if (!_outArchives[user].ContainsKey(format))
{
_outArchives[user].Add(format, null);
_totalUsers++;
}
}
#endif
private static void Init()
{
_inArchives = new Dictionary<object, Dictionary<InArchiveFormat, IInArchive>>();
#if COMPRESS
_outArchives = new Dictionary<object, Dictionary<OutArchiveFormat, IOutArchive>>();
#endif
}
/// <summary>
/// Loads the 7-zip library if necessary and adds user to the reference list
/// </summary>
/// <param name="user">Caller of the function</param>
/// <param name="format">Archive format</param>
public static void LoadLibrary(object user, Enum format)
{
lock (_syncRoot)
{
if (_inArchives == null
#if COMPRESS
|| _outArchives == null
#endif
)
{
Init();
}
#if !WINCE && !MONO
if (_modulePtr == IntPtr.Zero)
{
//zero 29-oct-2012 - this check isnt useful since LoadLibrary can pretty much check for the same thing. and it wrecks our dll relocation scheme
//if (!File.Exists(_libraryFileName))
//{
// throw new SevenZipLibraryException("DLL file does not exist.");
//}
if ((_modulePtr = libLoader.LoadPlatformSpecific(_libraryFileName)) == IntPtr.Zero)
{
//try a different directory
string alternateFilename = Path.Combine(Path.Combine(Path.GetDirectoryName(_libraryFileName),"dll"),"7z.dll");
if ((_modulePtr = libLoader.LoadPlatformSpecific(alternateFilename)) == IntPtr.Zero)
throw new SevenZipLibraryException("failed to load library.");
}
if (libLoader.GetProcAddr(_modulePtr, "GetHandlerProperty") == IntPtr.Zero)
{
libLoader.FreePlatformSpecific(_modulePtr);
throw new SevenZipLibraryException("library is invalid.");
}
}
#endif
if (format is InArchiveFormat)
{
InitUserInFormat(user, (InArchiveFormat) format);
return;
}
#if COMPRESS
if (format is OutArchiveFormat)
{
InitUserOutFormat(user, (OutArchiveFormat) format);
return;
}
#endif
throw new ArgumentException(
"Enum " + format + " is not a valid archive format attribute!");
}
}
/*/// <summary>
/// Gets the native 7zip library version string.
/// </summary>
public static string LibraryVersion
{
get
{
if (String.IsNullOrEmpty(_LibraryVersion))
{
FileVersionInfo dllVersionInfo = FileVersionInfo.GetVersionInfo(_libraryFileName);
_LibraryVersion = String.Format(
System.Globalization.CultureInfo.CurrentCulture,
"{0}.{1}",
dllVersionInfo.FileMajorPart, dllVersionInfo.FileMinorPart);
}
return _LibraryVersion;
}
}*/
/// <summary>
/// Gets the value indicating whether the library supports modifying archives.
/// </summary>
public static bool ModifyCapable
{
get
{
lock (_syncRoot)
{
if (!_modifyCapabale.HasValue)
{
#if !WINCE && !MONO
FileVersionInfo dllVersionInfo = FileVersionInfo.GetVersionInfo(_libraryFileName);
_modifyCapabale = dllVersionInfo.FileMajorPart >= 9;
#else
_modifyCapabale = true;
#endif
}
return _modifyCapabale.Value;
}
}
}
//static readonly string Namespace = Assembly.GetExecutingAssembly().GetManifestResourceNames()[0].Split('.')[0];
static readonly string Namespace = "BizHawk"; //Remove dirty hack above
private static string GetResourceString(string str)
{
return Namespace + ".arch." + str;
}
private static bool ExtractionBenchmark(string archiveFileName, Stream outStream,
ref LibraryFeature? features, LibraryFeature testedFeature)
{
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
GetResourceString(archiveFileName));
try
{
using (var extr = new SevenZipExtractor(stream))
{
extr.ExtractFile(0, outStream);
}
}
catch (Exception)
{
return false;
}
features |= testedFeature;
return true;
}
private static bool CompressionBenchmark(Stream inStream, Stream outStream,
OutArchiveFormat format, CompressionMethod method,
ref LibraryFeature? features, LibraryFeature testedFeature)
{
try
{
var compr = new SevenZipCompressor { ArchiveFormat = format, CompressionMethod = method };
compr.CompressStream(inStream, outStream);
}
catch (Exception)
{
return false;
}
features |= testedFeature;
return true;
}
public static LibraryFeature CurrentLibraryFeatures
{
get
{
lock (_syncRoot)
{
if (_features != null && _features.HasValue)
{
return _features.Value;
}
_features = LibraryFeature.None;
#region Benchmark
#region Extraction features
using (var outStream = new MemoryStream())
{
ExtractionBenchmark("Test.lzma.7z", outStream, ref _features, LibraryFeature.Extract7z);
ExtractionBenchmark("Test.lzma2.7z", outStream, ref _features, LibraryFeature.Extract7zLZMA2);
int i = 0;
if (ExtractionBenchmark("Test.bzip2.7z", outStream, ref _features, _features.Value))
{
i++;
}
if (ExtractionBenchmark("Test.ppmd.7z", outStream, ref _features, _features.Value))
{
i++;
if (i == 2 && (_features & LibraryFeature.Extract7z) != 0 &&
(_features & LibraryFeature.Extract7zLZMA2) != 0)
{
_features |= LibraryFeature.Extract7zAll;
}
}
ExtractionBenchmark("Test.rar", outStream, ref _features, LibraryFeature.ExtractRar);
ExtractionBenchmark("Test.tar", outStream, ref _features, LibraryFeature.ExtractTar);
ExtractionBenchmark("Test.txt.bz2", outStream, ref _features, LibraryFeature.ExtractBzip2);
ExtractionBenchmark("Test.txt.gz", outStream, ref _features, LibraryFeature.ExtractGzip);
ExtractionBenchmark("Test.txt.xz", outStream, ref _features, LibraryFeature.ExtractXz);
ExtractionBenchmark("Test.zip", outStream, ref _features, LibraryFeature.ExtractZip);
}
#endregion
#region Compression features
using (var inStream = new MemoryStream())
{
inStream.Write(Encoding.UTF8.GetBytes("Test"), 0, 4);
using (var outStream = new MemoryStream())
{
CompressionBenchmark(inStream, outStream,
OutArchiveFormat.SevenZip, CompressionMethod.Lzma,
ref _features, LibraryFeature.Compress7z);
CompressionBenchmark(inStream, outStream,
OutArchiveFormat.SevenZip, CompressionMethod.Lzma2,
ref _features, LibraryFeature.Compress7zLZMA2);
int i = 0;
if (CompressionBenchmark(inStream, outStream,
OutArchiveFormat.SevenZip, CompressionMethod.BZip2,
ref _features, _features.Value))
{
i++;
}
if (CompressionBenchmark(inStream, outStream,
OutArchiveFormat.SevenZip, CompressionMethod.Ppmd,
ref _features, _features.Value))
{
i++;
if (i == 2 && (_features & LibraryFeature.Compress7z) != 0 &&
(_features & LibraryFeature.Compress7zLZMA2) != 0)
{
_features |= LibraryFeature.Compress7zAll;
}
}
CompressionBenchmark(inStream, outStream,
OutArchiveFormat.Zip, CompressionMethod.Default,
ref _features, LibraryFeature.CompressZip);
CompressionBenchmark(inStream, outStream,
OutArchiveFormat.BZip2, CompressionMethod.Default,
ref _features, LibraryFeature.CompressBzip2);
CompressionBenchmark(inStream, outStream,
OutArchiveFormat.GZip, CompressionMethod.Default,
ref _features, LibraryFeature.CompressGzip);
CompressionBenchmark(inStream, outStream,
OutArchiveFormat.Tar, CompressionMethod.Default,
ref _features, LibraryFeature.CompressTar);
CompressionBenchmark(inStream, outStream,
OutArchiveFormat.XZ, CompressionMethod.Default,
ref _features, LibraryFeature.CompressXz);
}
}
#endregion
#endregion
if (ModifyCapable && (_features.Value & LibraryFeature.Compress7z) != 0)
{
_features |= LibraryFeature.Modify;
}
return _features.Value;
}
}
}
/// <summary>
/// Removes user from reference list and frees the 7-zip library if it becomes empty
/// </summary>
/// <param name="user">Caller of the function</param>
/// <param name="format">Archive format</param>
public static void FreeLibrary(object user, Enum format)
{
#if !WINCE && !MONO
var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
sp.Demand();
#endif
lock (_syncRoot)
{
if (_modulePtr != IntPtr.Zero)
{
if (format is InArchiveFormat)
{
if (_inArchives != null && _inArchives.ContainsKey(user) &&
_inArchives[user].ContainsKey((InArchiveFormat) format) &&
_inArchives[user][(InArchiveFormat) format] != null)
{
try
{
Marshal.ReleaseComObject(_inArchives[user][(InArchiveFormat) format]);
}
catch (InvalidComObjectException) {}
_inArchives[user].Remove((InArchiveFormat) format);
_totalUsers--;
if (_inArchives[user].Count == 0)
{
_inArchives.Remove(user);
}
}
}
#if COMPRESS
if (format is OutArchiveFormat)
{
if (_outArchives != null && _outArchives.ContainsKey(user) &&
_outArchives[user].ContainsKey((OutArchiveFormat) format) &&
_outArchives[user][(OutArchiveFormat) format] != null)
{
try
{
Marshal.ReleaseComObject(_outArchives[user][(OutArchiveFormat) format]);
}
catch (InvalidComObjectException) {}
_outArchives[user].Remove((OutArchiveFormat) format);
_totalUsers--;
if (_outArchives[user].Count == 0)
{
_outArchives.Remove(user);
}
}
}
#endif
if ((_inArchives == null || _inArchives.Count == 0)
#if COMPRESS
&& (_outArchives == null || _outArchives.Count == 0)
#endif
)
{
_inArchives = null;
#if COMPRESS
_outArchives = null;
#endif
if (_totalUsers == 0)
{
#if !WINCE && !MONO
libLoader.FreePlatformSpecific(_modulePtr);
#endif
_modulePtr = IntPtr.Zero;
}
}
}
}
}
/// <summary>
/// Gets IInArchive interface to extract 7-zip archives.
/// </summary>
/// <param name="format">Archive format.</param>
/// <param name="user">Archive format user.</param>
public static IInArchive InArchive(InArchiveFormat format, object user)
{
lock (_syncRoot)
{
if (_inArchives[user][format] == null)
{
#if !WINCE && !MONO
var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
sp.Demand();
if (_modulePtr == IntPtr.Zero)
{
LoadLibrary(user, format);
if (_modulePtr == IntPtr.Zero)
{
throw new SevenZipLibraryException();
}
}
var createObject = (NativeMethods.CreateObjectDelegate)
Marshal.GetDelegateForFunctionPointer(
libLoader.GetProcAddr(_modulePtr, "CreateObject"),
typeof(NativeMethods.CreateObjectDelegate));
if (createObject == null)
{
throw new SevenZipLibraryException();
}
#endif
object result;
Guid interfaceId =
#if !WINCE && !MONO
typeof(IInArchive).GUID;
#else
new Guid(((GuidAttribute)typeof(IInArchive).GetCustomAttributes(typeof(GuidAttribute), false)[0]).Value);
#endif
Guid classID = Formats.InFormatGuids[format];
try
{
#if !WINCE && !MONO
createObject(ref classID, ref interfaceId, out result);
#elif !MONO
NativeMethods.CreateCOMObject(ref classID, ref interfaceId, out result);
#else
result = SevenZip.Mono.Factory.CreateInterface<IInArchive>(user, classID, interfaceId);
#endif
}
catch (Exception)
{
throw new SevenZipLibraryException("Your 7-zip library does not support this archive type.");
}
InitUserInFormat(user, format);
_inArchives[user][format] = result as IInArchive;
}
return _inArchives[user][format];
#if !WINCE && !MONO
}
#endif
}
#if COMPRESS
/// <summary>
/// Gets IOutArchive interface to pack 7-zip archives.
/// </summary>
/// <param name="format">Archive format.</param>
/// <param name="user">Archive format user.</param>
public static IOutArchive OutArchive(OutArchiveFormat format, object user)
{
lock (_syncRoot)
{
if (_outArchives[user][format] == null)
{
#if !WINCE && !MONO
var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
sp.Demand();
if (_modulePtr == IntPtr.Zero)
{
throw new SevenZipLibraryException();
}
var createObject = (NativeMethods.CreateObjectDelegate)
Marshal.GetDelegateForFunctionPointer(
libLoader.GetProcAddr(_modulePtr, "CreateObject"),
typeof(NativeMethods.CreateObjectDelegate));
if (createObject == null)
{
throw new SevenZipLibraryException();
}
#endif
object result;
Guid interfaceId =
#if !WINCE && !MONO
typeof(IOutArchive).GUID;
#else
new Guid(((GuidAttribute)typeof(IOutArchive).GetCustomAttributes(typeof(GuidAttribute), false)[0]).Value);
#endif
Guid classID = Formats.OutFormatGuids[format];
try
{
#if !WINCE && !MONO
createObject(ref classID, ref interfaceId, out result);
#elif !MONO
NativeMethods.CreateCOMObject(ref classID, ref interfaceId, out result);
#else
result = SevenZip.Mono.Factory.CreateInterface<IOutArchive>(classID, interfaceId, user);
#endif
}
catch (Exception)
{
throw new SevenZipLibraryException("Your 7-zip library does not support this archive type.");
}
InitUserOutFormat(user, format);
_outArchives[user][format] = result as IOutArchive;
}
return _outArchives[user][format];
#if !WINCE && !MONO
}
#endif
}
#endif
#if !WINCE && !MONO
public static void SetLibraryPath(string libraryPath)
{
if (_modulePtr != IntPtr.Zero && !Path.GetFullPath(libraryPath).Equals(
Path.GetFullPath(_libraryFileName), StringComparison.OrdinalIgnoreCase))
{
throw new SevenZipLibraryException(
"can not change the library path while the library \"" + _libraryFileName + "\" is being used.");
}
if (!File.Exists(libraryPath))
{
throw new SevenZipLibraryException(
"can not change the library path because the file \"" + libraryPath + "\" does not exist.");
}
_libraryFileName = libraryPath;
_features = null;
}
#endif
}
#endif
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class DkmUtilities
{
private static readonly Guid s_symUnmanagedReaderClassId = Guid.Parse("B4CE6286-2A6B-3712-A3B7-1EE1DAD467B5");
internal unsafe delegate IntPtr GetMetadataBytesPtrFunction(AssemblyIdentity assemblyIdentity, out uint uSize);
// Return the set of managed module instances from the AppDomain.
private static IEnumerable<DkmClrModuleInstance> GetModulesInAppDomain(this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain)
{
if (appDomain.IsUnloaded)
{
return SpecializedCollections.EmptyEnumerable<DkmClrModuleInstance>();
}
var appDomainId = appDomain.Id;
// GetModuleInstances() may include instances of DkmClrNcContainerModuleInstance
// which are containers of managed module instances (see GetEmbeddedModules())
// but not managed modules themselves. Since GetModuleInstances() will include the
// embedded modules, we can simply ignore DkmClrNcContainerModuleInstances.
return runtime.GetModuleInstances().
OfType<DkmClrModuleInstance>().
Where(module =>
{
var moduleAppDomain = module.AppDomain;
return !moduleAppDomain.IsUnloaded && (moduleAppDomain.Id == appDomainId);
});
}
internal unsafe static ImmutableArray<MetadataBlock> GetMetadataBlocks(this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain)
{
var builder = ArrayBuilder<MetadataBlock>.GetInstance();
IntPtr ptr;
uint size;
foreach (DkmClrModuleInstance module in runtime.GetModulesInAppDomain(appDomain))
{
MetadataBlock block;
try
{
ptr = module.GetMetaDataBytesPtr(out size);
Debug.Assert(size > 0);
block = GetMetadataBlock(ptr, size);
}
catch (Exception e) when (MetadataUtilities.IsBadOrMissingMetadataException(e, module.FullName))
{
continue;
}
Debug.Assert(block.ModuleVersionId == module.Mvid);
builder.Add(block);
}
// Include "intrinsic method" assembly.
ptr = runtime.GetIntrinsicAssemblyMetaDataBytesPtr(out size);
builder.Add(GetMetadataBlock(ptr, size));
return builder.ToImmutableAndFree();
}
internal static ImmutableArray<MetadataBlock> GetMetadataBlocks(GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities)
{
ArrayBuilder<MetadataBlock> builder = null;
foreach (AssemblyIdentity missingAssemblyIdentity in missingAssemblyIdentities)
{
MetadataBlock block;
try
{
uint size;
IntPtr ptr;
ptr = getMetaDataBytesPtrFunction(missingAssemblyIdentity, out size);
Debug.Assert(size > 0);
block = GetMetadataBlock(ptr, size);
}
catch (Exception e) when (MetadataUtilities.IsBadOrMissingMetadataException(e, missingAssemblyIdentity.GetDisplayName()))
{
continue;
}
if (builder == null)
{
builder = ArrayBuilder<MetadataBlock>.GetInstance();
}
builder.Add(block);
}
return builder == null ? ImmutableArray<MetadataBlock>.Empty : builder.ToImmutableAndFree();
}
internal static ImmutableArray<AssemblyReaders> MakeAssemblyReaders(this DkmClrInstructionAddress instructionAddress)
{
var builder = ArrayBuilder<AssemblyReaders>.GetInstance();
foreach (DkmClrModuleInstance module in instructionAddress.RuntimeInstance.GetModulesInAppDomain(instructionAddress.ModuleInstance.AppDomain))
{
var symReader = module.GetSymReader();
if (symReader == null)
{
continue;
}
MetadataReader reader;
unsafe
{
try
{
uint size;
IntPtr ptr;
ptr = module.GetMetaDataBytesPtr(out size);
Debug.Assert(size > 0);
reader = new MetadataReader((byte*)ptr, (int)size);
}
catch (Exception e) when (MetadataUtilities.IsBadOrMissingMetadataException(e, module.FullName))
{
continue;
}
}
builder.Add(new AssemblyReaders(reader, symReader));
}
return builder.ToImmutableAndFree();
}
private unsafe static MetadataBlock GetMetadataBlock(IntPtr ptr, uint size)
{
var reader = new MetadataReader((byte*)ptr, (int)size);
var moduleDef = reader.GetModuleDefinition();
var moduleVersionId = reader.GetGuid(moduleDef.Mvid);
var generationId = reader.GetGuid(moduleDef.GenerationId);
return new MetadataBlock(moduleVersionId, generationId, ptr, (int)size);
}
internal static object GetSymReader(this DkmClrModuleInstance clrModule)
{
var module = clrModule.Module; // Null if there are no symbols.
return (module == null) ? null : module.GetSymbolInterface(s_symUnmanagedReaderClassId);
}
internal static DkmCompiledClrInspectionQuery ToQueryResult(
this CompileResult compResult,
DkmCompilerId languageId,
ResultProperties resultProperties,
DkmClrRuntimeInstance runtimeInstance)
{
if (compResult == null)
{
return null;
}
Debug.Assert(compResult.Assembly != null);
Debug.Assert(compResult.TypeName != null);
Debug.Assert(compResult.MethodName != null);
return DkmCompiledClrInspectionQuery.Create(
runtimeInstance,
Binary: new ReadOnlyCollection<byte>(compResult.Assembly),
DataContainer: null,
LanguageId: languageId,
TypeName: compResult.TypeName,
MethodName: compResult.MethodName,
FormatSpecifiers: compResult.FormatSpecifiers,
CompilationFlags: resultProperties.Flags,
ResultCategory: resultProperties.Category,
Access: resultProperties.AccessType,
StorageType: resultProperties.StorageType,
TypeModifierFlags: resultProperties.ModifierFlags,
CustomTypeInfo: compResult.GetCustomTypeInfo().ToDkmClrCustomTypeInfo());
}
internal static ResultProperties GetResultProperties<TSymbol>(this TSymbol symbol, DkmClrCompilationResultFlags flags, bool isConstant)
where TSymbol : ISymbol
{
var haveSymbol = symbol != null;
var category = haveSymbol
? GetResultCategory(symbol.Kind)
: DkmEvaluationResultCategory.Data;
var accessType = haveSymbol
? GetResultAccessType(symbol.DeclaredAccessibility)
: DkmEvaluationResultAccessType.None;
var storageType = haveSymbol && symbol.IsStatic
? DkmEvaluationResultStorageType.Static
: DkmEvaluationResultStorageType.None;
var modifierFlags = DkmEvaluationResultTypeModifierFlags.None;
if (isConstant)
{
modifierFlags = DkmEvaluationResultTypeModifierFlags.Constant;
}
else if (!haveSymbol)
{
// No change.
}
else if (symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride)
{
modifierFlags = DkmEvaluationResultTypeModifierFlags.Virtual;
}
else if (symbol.Kind == SymbolKind.Field && ((IFieldSymbol)symbol).IsVolatile)
{
modifierFlags = DkmEvaluationResultTypeModifierFlags.Volatile;
}
// CONSIDER: for completeness, we could check for [MethodImpl(MethodImplOptions.Synchronized)]
// and set DkmEvaluationResultTypeModifierFlags.Synchronized, but it doesn't seem to have any
// impact on the UI. It is exposed through the DTE, but cscompee didn't set the flag either.
return new ResultProperties(flags, category, accessType, storageType, modifierFlags);
}
private static DkmEvaluationResultCategory GetResultCategory(SymbolKind kind)
{
switch (kind)
{
case SymbolKind.Method:
return DkmEvaluationResultCategory.Method;
case SymbolKind.Property:
return DkmEvaluationResultCategory.Property;
default:
return DkmEvaluationResultCategory.Data;
}
}
private static DkmEvaluationResultAccessType GetResultAccessType(Accessibility accessibility)
{
switch (accessibility)
{
case Accessibility.Public:
return DkmEvaluationResultAccessType.Public;
case Accessibility.Protected:
return DkmEvaluationResultAccessType.Protected;
case Accessibility.Private:
return DkmEvaluationResultAccessType.Private;
case Accessibility.Internal:
case Accessibility.ProtectedOrInternal: // Dev12 treats this as "internal"
case Accessibility.ProtectedAndInternal: // Dev12 treats this as "internal"
return DkmEvaluationResultAccessType.Internal;
case Accessibility.NotApplicable:
return DkmEvaluationResultAccessType.None;
default:
throw ExceptionUtilities.UnexpectedValue(accessibility);
}
}
internal static bool Includes(this DkmVariableInfoFlags flags, DkmVariableInfoFlags desired)
{
return (flags & desired) == desired;
}
internal static TMetadataContext GetMetadataContext<TMetadataContext>(this DkmClrAppDomain appDomain)
where TMetadataContext : struct
{
var dataItem = appDomain.GetDataItem<MetadataContextItem<TMetadataContext>>();
return (dataItem == null) ? default(TMetadataContext) : dataItem.MetadataContext;
}
internal static void SetMetadataContext<TMetadataContext>(this DkmClrAppDomain appDomain, TMetadataContext context)
where TMetadataContext : struct
{
appDomain.SetDataItem(DkmDataCreationDisposition.CreateAlways, new MetadataContextItem<TMetadataContext>(context));
}
internal static void RemoveMetadataContext<TMetadataContext>(this DkmClrAppDomain appDomain)
where TMetadataContext : struct
{
appDomain.RemoveDataItem<MetadataContextItem<TMetadataContext>>();
}
private sealed class MetadataContextItem<TMetadataContext> : DkmDataItem
where TMetadataContext : struct
{
internal readonly TMetadataContext MetadataContext;
internal MetadataContextItem(TMetadataContext metadataContext)
{
this.MetadataContext = metadataContext;
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Drawables;
using osu.Game.Collections;
using osu.Game.Graphics;
using osu.Game.Graphics.Backgrounds;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Select.Carousel
{
public class DrawableCarouselBeatmap : DrawableCarouselItem, IHasContextMenu
{
public const float CAROUSEL_BEATMAP_SPACING = 5;
/// <summary>
/// The height of a carousel beatmap, including vertical spacing.
/// </summary>
public const float HEIGHT = height + CAROUSEL_BEATMAP_SPACING;
private const float height = MAX_HEIGHT * 0.6f;
private readonly BeatmapInfo beatmapInfo;
private Sprite background;
private Action<BeatmapInfo> startRequested;
private Action<BeatmapInfo> editRequested;
private Action<BeatmapInfo> hideRequested;
private Triangles triangles;
private StarCounter starCounter;
[Resolved(CanBeNull = true)]
private BeatmapSetOverlay beatmapOverlay { get; set; }
[Resolved]
private BeatmapDifficultyCache difficultyCache { get; set; }
[Resolved(CanBeNull = true)]
private CollectionManager collectionManager { get; set; }
[Resolved(CanBeNull = true)]
private ManageCollectionsDialog manageCollectionsDialog { get; set; }
private IBindable<StarDifficulty?> starDifficultyBindable;
private CancellationTokenSource starDifficultyCancellationSource;
public DrawableCarouselBeatmap(CarouselBeatmap panel)
{
beatmapInfo = panel.BeatmapInfo;
Item = panel;
}
[BackgroundDependencyLoader(true)]
private void load(BeatmapManager manager, SongSelect songSelect)
{
Header.Height = height;
if (songSelect != null)
{
startRequested = b => songSelect.FinaliseSelection(b);
if (songSelect.AllowEditing)
editRequested = songSelect.Edit;
}
if (manager != null)
hideRequested = manager.Hide;
Header.Children = new Drawable[]
{
background = new Box
{
RelativeSizeAxes = Axes.Both,
},
triangles = new Triangles
{
TriangleScale = 2,
RelativeSizeAxes = Axes.Both,
ColourLight = Color4Extensions.FromHex(@"3a7285"),
ColourDark = Color4Extensions.FromHex(@"123744")
},
new FillFlowContainer
{
Padding = new MarginPadding(5),
Direction = FillDirection.Horizontal,
AutoSizeAxes = Axes.Both,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Children = new Drawable[]
{
new DifficultyIcon(beatmapInfo, shouldShowTooltip: false)
{
Scale = new Vector2(1.8f),
},
new FillFlowContainer
{
Padding = new MarginPadding { Left = 5 },
Direction = FillDirection.Vertical,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new FillFlowContainer
{
Direction = FillDirection.Horizontal,
Spacing = new Vector2(4, 0),
AutoSizeAxes = Axes.Both,
Children = new[]
{
new OsuSpriteText
{
Text = beatmapInfo.DifficultyName,
Font = OsuFont.GetFont(size: 20),
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft
},
new OsuSpriteText
{
Text = "mapped by",
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft
},
new OsuSpriteText
{
Text = $"{(beatmapInfo.Metadata ?? beatmapInfo.BeatmapSet.Metadata).Author.Username}",
Font = OsuFont.GetFont(italics: true),
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft
},
}
},
new FillFlowContainer
{
Direction = FillDirection.Horizontal,
Spacing = new Vector2(4, 0),
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new TopLocalRank(beatmapInfo)
{
Scale = new Vector2(0.8f),
Size = new Vector2(40, 20)
},
starCounter = new StarCounter
{
Scale = new Vector2(0.8f),
}
}
}
}
}
}
}
};
}
protected override void Selected()
{
base.Selected();
MovementContainer.MoveToX(-50, 500, Easing.OutExpo);
background.Colour = ColourInfo.GradientVertical(
new Color4(20, 43, 51, 255),
new Color4(40, 86, 102, 255));
triangles.Colour = Color4.White;
}
protected override void Deselected()
{
base.Deselected();
MovementContainer.MoveToX(0, 500, Easing.OutExpo);
background.Colour = new Color4(20, 43, 51, 255);
triangles.Colour = OsuColour.Gray(0.5f);
}
protected override bool OnClick(ClickEvent e)
{
if (Item.State.Value == CarouselItemState.Selected)
startRequested?.Invoke(beatmapInfo);
return base.OnClick(e);
}
protected override void ApplyState()
{
if (Item.State.Value != CarouselItemState.Collapsed && Alpha == 0)
starCounter.ReplayAnimation();
starDifficultyCancellationSource?.Cancel();
// Only compute difficulty when the item is visible.
if (Item.State.Value != CarouselItemState.Collapsed)
{
// We've potentially cancelled the computation above so a new bindable is required.
starDifficultyBindable = difficultyCache.GetBindableDifficulty(beatmapInfo, (starDifficultyCancellationSource = new CancellationTokenSource()).Token);
starDifficultyBindable.BindValueChanged(d =>
{
starCounter.Current = (float)(d.NewValue?.Stars ?? 0);
}, true);
}
base.ApplyState();
}
public MenuItem[] ContextMenuItems
{
get
{
List<MenuItem> items = new List<MenuItem>();
if (startRequested != null)
items.Add(new OsuMenuItem("Play", MenuItemType.Highlighted, () => startRequested(beatmapInfo)));
if (editRequested != null)
items.Add(new OsuMenuItem("Edit", MenuItemType.Standard, () => editRequested(beatmapInfo)));
if (beatmapInfo.OnlineID.HasValue && beatmapOverlay != null)
items.Add(new OsuMenuItem("Details...", MenuItemType.Standard, () => beatmapOverlay.FetchAndShowBeatmap(beatmapInfo.OnlineID.Value)));
if (collectionManager != null)
{
var collectionItems = collectionManager.Collections.Select(createCollectionMenuItem).ToList();
if (manageCollectionsDialog != null)
collectionItems.Add(new OsuMenuItem("Manage...", MenuItemType.Standard, manageCollectionsDialog.Show));
items.Add(new OsuMenuItem("Collections") { Items = collectionItems });
}
if (hideRequested != null)
items.Add(new OsuMenuItem("Hide", MenuItemType.Destructive, () => hideRequested(beatmapInfo)));
return items.ToArray();
}
}
private MenuItem createCollectionMenuItem(BeatmapCollection collection)
{
return new ToggleMenuItem(collection.Name.Value, MenuItemType.Standard, s =>
{
if (s)
collection.Beatmaps.Add(beatmapInfo);
else
collection.Beatmaps.Remove(beatmapInfo);
})
{
State = { Value = collection.Beatmaps.Contains(beatmapInfo) }
};
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
starDifficultyCancellationSource?.Cancel();
}
}
}
| |
using System.Collections.Generic;
namespace Pathfinding {
/** Represents a collection of GraphNodes. It allows for fast lookups of the closest node to a point */
public class PointKDTree {
// TODO: Make constant
public static int LeafSize = 10;
Node[] tree = new Node[16];
int numNodes = 0;
readonly List<GraphNode> largeList = new List<GraphNode>();
readonly Stack<List<GraphNode> > listCache = new Stack<List<GraphNode> >();
static readonly IComparer<GraphNode>[] comparers = new IComparer<GraphNode>[] { new CompareX(), new CompareY(), new CompareZ() };
struct Node {
public List<GraphNode> data;
public int split;
public byte splitAxis;
}
// Pretty ugly with one class for each axis, but it has been verified to make the tree around 5% faster
class CompareX : IComparer<GraphNode> {
public int Compare (GraphNode lhs, GraphNode rhs) { return lhs.position.x.CompareTo(rhs.position.x); }
}
class CompareY : IComparer<GraphNode> {
public int Compare (GraphNode lhs, GraphNode rhs) { return lhs.position.y.CompareTo(rhs.position.y); }
}
class CompareZ : IComparer<GraphNode> {
public int Compare (GraphNode lhs, GraphNode rhs) { return lhs.position.z.CompareTo(rhs.position.z); }
}
public PointKDTree() {
tree[1] = new Node { data = GetOrCreateList() };
}
/** Add the node to the tree */
public void Add (GraphNode node) {
numNodes++;
Add(node, 1);
}
/** Rebuild the tree starting with all nodes in the array between index start (inclusive) and end (exclusive) */
public void Rebuild (GraphNode[] nodes, int start, int end) {
if (start < 0 || end < start || end > nodes.Length)
throw new System.ArgumentException();
for (int i = 0; i < tree.Length; i++) {
if (tree[i].data != null) {
tree[i].data.Clear();
listCache.Push(tree[i].data);
tree[i].data = null;
}
}
numNodes = end - start;
Build(1, new List<GraphNode>(nodes), start, end);
}
List<GraphNode> GetOrCreateList () {
// Note, the lists will never become larger than this initial capacity, so possibly they should be replaced by arrays
return listCache.Count > 0 ? listCache.Pop() : new List<GraphNode>(LeafSize*2 + 1);
}
int Size (int index) {
return tree[index].data != null ? tree[index].data.Count : Size(2 * index) + Size(2 * index + 1);
}
void CollectAndClear (int index, List<GraphNode> buffer) {
var nodes = tree[index].data;
if (nodes != null) {
tree[index] = new Node();
for (int i = 0; i < nodes.Count; i++) buffer.Add(nodes[i]);
nodes.Clear();
listCache.Push(nodes);
} else {
CollectAndClear(index*2, buffer);
CollectAndClear(index*2 + 1, buffer);
}
}
static int MaxAllowedSize (int numNodes, int depth) {
// Allow a node to be 2.5 times as full as it should ideally be
// but do not allow it to contain more than 3/4ths of the total number of nodes
// (important to make sure nodes near the top of the tree also get rebalanced).
// A node should ideally contain numNodes/2^depth nodes below it (^ is exponentiation, not xor)
return System.Math.Min(((5 * numNodes) / 2) >> depth, (3 * numNodes) / 4);
}
void Rebalance (int index) {
CollectAndClear(index, largeList);
Build(index, largeList, 0, largeList.Count);
largeList.Clear();
}
void EnsureSize (int index) {
if (index >= tree.Length) {
var newLeaves = new Node[System.Math.Max(index + 1, tree.Length*2)];
tree.CopyTo(newLeaves, 0);
tree = newLeaves;
}
}
void Build (int index, List<GraphNode> nodes, int start, int end) {
EnsureSize(index);
if (end - start <= LeafSize) {
tree[index].data = GetOrCreateList();
for (int i = start; i < end; i++)
tree[index].data.Add(nodes[i]);
} else {
Int3 mn, mx;
mn = mx = nodes[start].position;
for (int i = start; i < end; i++) {
var p = nodes[i].position;
mn = new Int3(System.Math.Min(mn.x, p.x), System.Math.Min(mn.y, p.y), System.Math.Min(mn.z, p.z));
mx = new Int3(System.Math.Max(mx.x, p.x), System.Math.Max(mx.y, p.y), System.Math.Max(mx.z, p.z));
}
Int3 diff = mx - mn;
var axis = diff.x > diff.y ? (diff.x > diff.z ? 0 : 2) : (diff.y > diff.z ? 1 : 2);
nodes.Sort(start, end - start, comparers[axis]);
int mid = (start+end)/2;
tree[index].split = (nodes[mid-1].position[axis] + nodes[mid].position[axis] + 1)/2;
tree[index].splitAxis = (byte)axis;
Build(index*2 + 0, nodes, start, mid);
Build(index*2 + 1, nodes, mid, end);
}
}
void Add (GraphNode point, int index, int depth = 0) {
// Move down in the tree until the leaf node is found that this point is inside of
while (tree[index].data == null) {
index = 2 * index + (point.position[tree[index].splitAxis] < tree[index].split ? 0 : 1);
depth++;
}
// Add the point to the leaf node
tree[index].data.Add(point);
// Check if the leaf node is large enough that we need to do some rebalancing
if (tree[index].data.Count > LeafSize*2) {
int levelsUp = 0;
// Search upwards for nodes that are too large and should be rebalanced
// Rebalance the node above the node that had a too large size so that it can
// move children over to the sibling
while (depth - levelsUp > 0 && Size(index >> levelsUp) > MaxAllowedSize(numNodes, depth-levelsUp)) {
levelsUp++;
}
Rebalance(index >> levelsUp);
}
}
/** Closest node to the point which satisfies the constraint */
public GraphNode GetNearest (Int3 point, NNConstraint constraint) {
GraphNode best = null;
long bestSqrDist = long.MaxValue;
GetNearestInternal(1, point, constraint, ref best, ref bestSqrDist);
return best;
}
void GetNearestInternal (int index, Int3 point, NNConstraint constraint, ref GraphNode best, ref long bestSqrDist) {
var data = tree[index].data;
if (data != null) {
for (int i = data.Count-1; i >= 0; i--) {
var dist = (data[i].position - point).sqrMagnitudeLong;
if (dist < bestSqrDist && (constraint == null || constraint.Suitable(data[i]))) {
bestSqrDist = dist;
best = data[i];
}
}
} else {
var dist = (long)(point[tree[index].splitAxis] - tree[index].split);
var childIndex = 2 * index + (dist < 0 ? 0 : 1);
GetNearestInternal(childIndex, point, constraint, ref best, ref bestSqrDist);
// Try the other one if it is possible to find a valid node on the other side
if (dist*dist < bestSqrDist) {
// childIndex ^ 1 will flip the last bit, so if childIndex is odd, then childIndex ^ 1 will be even
GetNearestInternal(childIndex ^ 0x1, point, constraint, ref best, ref bestSqrDist);
}
}
}
/** Add all nodes within a squared distance of the point to the buffer */
public void GetInRange (Int3 point, long sqrRadius, List<GraphNode> buffer) {
GetInRangeInternal(1, point, sqrRadius, buffer);
}
void GetInRangeInternal (int index, Int3 point, long sqrRadius, List<GraphNode> buffer) {
var data = tree[index].data;
if (data != null) {
for (int i = data.Count-1; i >= 0; i--) {
var dist = (data[i].position - point).sqrMagnitudeLong;
if (dist < sqrRadius) {
buffer.Add(data[i]);
}
}
} else {
var dist = (long)(point[tree[index].splitAxis] - tree[index].split);
var childIndex = 2 * index + (dist < 0 ? 0 : 1);
GetInRangeInternal(childIndex, point, sqrRadius, buffer);
// Try the other one if it is possible to find a valid node on the other side
if (dist*dist < sqrRadius) {
// childIndex ^ 1 will flip the last bit, so if childIndex is odd, then childIndex ^ 1 will be even
GetInRangeInternal(childIndex ^ 0x1, point, sqrRadius, buffer);
}
}
}
}
}
| |
// 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.
#region Assembly System.Windows.Forms.dll, v4.0.30319
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Windows.Forms.dll
#endregion
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Runtime.InteropServices;
namespace System.Windows.Forms {
// Summary:
// Specifies key codes and modifiers.
[Flags]
[ComVisible(true)]
[Editor("System.Windows.Forms.Design.ShortcutKeysEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
//[TypeConverter(typeof(KeysConverter))]
public enum Keys {
// Summary:
// The bitmask to extract modifiers from a key value.
Modifiers = -65536,
//
// Summary:
// No key pressed.
None = 0,
//
// Summary:
// The left mouse button.
LButton = 1,
//
// Summary:
// The right mouse button.
RButton = 2,
//
// Summary:
// The CANCEL key.
Cancel = 3,
//
// Summary:
// The middle mouse button (three-button mouse).
MButton = 4,
//
// Summary:
// The first x mouse button (five-button mouse).
XButton1 = 5,
//
// Summary:
// The second x mouse button (five-button mouse).
XButton2 = 6,
//
// Summary:
// The BACKSPACE key.
Back = 8,
//
// Summary:
// The TAB key.
Tab = 9,
//
// Summary:
// The LINEFEED key.
LineFeed = 10,
//
// Summary:
// The CLEAR key.
Clear = 12,
//
// Summary:
// The ENTER key.
Enter = 13,
//
// Summary:
// The RETURN key.
Return = 13,
//
// Summary:
// The SHIFT key.
ShiftKey = 16,
//
// Summary:
// The CTRL key.
ControlKey = 17,
//
// Summary:
// The ALT key.
Menu = 18,
//
// Summary:
// The PAUSE key.
Pause = 19,
//
// Summary:
// The CAPS LOCK key.
CapsLock = 20,
//
// Summary:
// The CAPS LOCK key.
Capital = 20,
//
// Summary:
// The IME Kana mode key.
KanaMode = 21,
//
// Summary:
// The IME Hanguel mode key. (maintained for compatibility; use HangulMode)
HanguelMode = 21,
//
// Summary:
// The IME Hangul mode key.
HangulMode = 21,
//
// Summary:
// The IME Junja mode key.
JunjaMode = 23,
//
// Summary:
// The IME final mode key.
FinalMode = 24,
//
// Summary:
// The IME Kanji mode key.
KanjiMode = 25,
//
// Summary:
// The IME Hanja mode key.
HanjaMode = 25,
//
// Summary:
// The ESC key.
Escape = 27,
//
// Summary:
// The IME convert key.
IMEConvert = 28,
//
// Summary:
// The IME nonconvert key.
IMENonconvert = 29,
//
// Summary:
// The IME accept key. Obsolete, use System.Windows.Forms.Keys.IMEAccept instead.
IMEAceept = 30,
//
// Summary:
// The IME accept key, replaces System.Windows.Forms.Keys.IMEAceept.
IMEAccept = 30,
//
// Summary:
// The IME mode change key.
IMEModeChange = 31,
//
// Summary:
// The SPACEBAR key.
Space = 32,
//
// Summary:
// The PAGE UP key.
Prior = 33,
//
// Summary:
// The PAGE UP key.
PageUp = 33,
//
// Summary:
// The PAGE DOWN key.
Next = 34,
//
// Summary:
// The PAGE DOWN key.
PageDown = 34,
//
// Summary:
// The END key.
End = 35,
//
// Summary:
// The HOME key.
Home = 36,
//
// Summary:
// The LEFT ARROW key.
Left = 37,
//
// Summary:
// The UP ARROW key.
Up = 38,
//
// Summary:
// The RIGHT ARROW key.
Right = 39,
//
// Summary:
// The DOWN ARROW key.
Down = 40,
//
// Summary:
// The SELECT key.
Select = 41,
//
// Summary:
// The PRINT key.
Print = 42,
//
// Summary:
// The EXECUTE key.
Execute = 43,
//
// Summary:
// The PRINT SCREEN key.
PrintScreen = 44,
//
// Summary:
// The PRINT SCREEN key.
Snapshot = 44,
//
// Summary:
// The INS key.
Insert = 45,
//
// Summary:
// The DEL key.
Delete = 46,
//
// Summary:
// The HELP key.
Help = 47,
//
// Summary:
// The 0 key.
D0 = 48,
//
// Summary:
// The 1 key.
D1 = 49,
//
// Summary:
// The 2 key.
D2 = 50,
//
// Summary:
// The 3 key.
D3 = 51,
//
// Summary:
// The 4 key.
D4 = 52,
//
// Summary:
// The 5 key.
D5 = 53,
//
// Summary:
// The 6 key.
D6 = 54,
//
// Summary:
// The 7 key.
D7 = 55,
//
// Summary:
// The 8 key.
D8 = 56,
//
// Summary:
// The 9 key.
D9 = 57,
//
// Summary:
// The A key.
A = 65,
//
// Summary:
// The B key.
B = 66,
//
// Summary:
// The C key.
C = 67,
//
// Summary:
// The D key.
D = 68,
//
// Summary:
// The E key.
E = 69,
//
// Summary:
// The F key.
F = 70,
//
// Summary:
// The G key.
G = 71,
//
// Summary:
// The H key.
H = 72,
//
// Summary:
// The I key.
I = 73,
//
// Summary:
// The J key.
J = 74,
//
// Summary:
// The K key.
K = 75,
//
// Summary:
// The L key.
L = 76,
//
// Summary:
// The M key.
M = 77,
//
// Summary:
// The N key.
N = 78,
//
// Summary:
// The O key.
O = 79,
//
// Summary:
// The P key.
P = 80,
//
// Summary:
// The Q key.
Q = 81,
//
// Summary:
// The R key.
R = 82,
//
// Summary:
// The S key.
S = 83,
//
// Summary:
// The T key.
T = 84,
//
// Summary:
// The U key.
U = 85,
//
// Summary:
// The V key.
V = 86,
//
// Summary:
// The W key.
W = 87,
//
// Summary:
// The X key.
X = 88,
//
// Summary:
// The Y key.
Y = 89,
//
// Summary:
// The Z key.
Z = 90,
//
// Summary:
// The left Windows logo key (Microsoft Natural Keyboard).
LWin = 91,
//
// Summary:
// The right Windows logo key (Microsoft Natural Keyboard).
RWin = 92,
//
// Summary:
// The application key (Microsoft Natural Keyboard).
Apps = 93,
//
// Summary:
// The computer sleep key.
Sleep = 95,
//
// Summary:
// The 0 key on the numeric keypad.
NumPad0 = 96,
//
// Summary:
// The 1 key on the numeric keypad.
NumPad1 = 97,
//
// Summary:
// The 2 key on the numeric keypad.
NumPad2 = 98,
//
// Summary:
// The 3 key on the numeric keypad.
NumPad3 = 99,
//
// Summary:
// The 4 key on the numeric keypad.
NumPad4 = 100,
//
// Summary:
// The 5 key on the numeric keypad.
NumPad5 = 101,
//
// Summary:
// The 6 key on the numeric keypad.
NumPad6 = 102,
//
// Summary:
// The 7 key on the numeric keypad.
NumPad7 = 103,
//
// Summary:
// The 8 key on the numeric keypad.
NumPad8 = 104,
//
// Summary:
// The 9 key on the numeric keypad.
NumPad9 = 105,
//
// Summary:
// The multiply key.
Multiply = 106,
//
// Summary:
// The add key.
Add = 107,
//
// Summary:
// The separator key.
Separator = 108,
//
// Summary:
// The subtract key.
Subtract = 109,
//
// Summary:
// The decimal key.
Decimal = 110,
//
// Summary:
// The divide key.
Divide = 111,
//
// Summary:
// The F1 key.
F1 = 112,
//
// Summary:
// The F2 key.
F2 = 113,
//
// Summary:
// The F3 key.
F3 = 114,
//
// Summary:
// The F4 key.
F4 = 115,
//
// Summary:
// The F5 key.
F5 = 116,
//
// Summary:
// The F6 key.
F6 = 117,
//
// Summary:
// The F7 key.
F7 = 118,
//
// Summary:
// The F8 key.
F8 = 119,
//
// Summary:
// The F9 key.
F9 = 120,
//
// Summary:
// The F10 key.
F10 = 121,
//
// Summary:
// The F11 key.
F11 = 122,
//
// Summary:
// The F12 key.
F12 = 123,
//
// Summary:
// The F13 key.
F13 = 124,
//
// Summary:
// The F14 key.
F14 = 125,
//
// Summary:
// The F15 key.
F15 = 126,
//
// Summary:
// The F16 key.
F16 = 127,
//
// Summary:
// The F17 key.
F17 = 128,
//
// Summary:
// The F18 key.
F18 = 129,
//
// Summary:
// The F19 key.
F19 = 130,
//
// Summary:
// The F20 key.
F20 = 131,
//
// Summary:
// The F21 key.
F21 = 132,
//
// Summary:
// The F22 key.
F22 = 133,
//
// Summary:
// The F23 key.
F23 = 134,
//
// Summary:
// The F24 key.
F24 = 135,
//
// Summary:
// The NUM LOCK key.
NumLock = 144,
//
// Summary:
// The SCROLL LOCK key.
Scroll = 145,
//
// Summary:
// The left SHIFT key.
LShiftKey = 160,
//
// Summary:
// The right SHIFT key.
RShiftKey = 161,
//
// Summary:
// The left CTRL key.
LControlKey = 162,
//
// Summary:
// The right CTRL key.
RControlKey = 163,
//
// Summary:
// The left ALT key.
LMenu = 164,
//
// Summary:
// The right ALT key.
RMenu = 165,
//
// Summary:
// The browser back key (Windows 2000 or later).
BrowserBack = 166,
//
// Summary:
// The browser forward key (Windows 2000 or later).
BrowserForward = 167,
//
// Summary:
// The browser refresh key (Windows 2000 or later).
BrowserRefresh = 168,
//
// Summary:
// The browser stop key (Windows 2000 or later).
BrowserStop = 169,
//
// Summary:
// The browser search key (Windows 2000 or later).
BrowserSearch = 170,
//
// Summary:
// The browser favorites key (Windows 2000 or later).
BrowserFavorites = 171,
//
// Summary:
// The browser home key (Windows 2000 or later).
BrowserHome = 172,
//
// Summary:
// The volume mute key (Windows 2000 or later).
VolumeMute = 173,
//
// Summary:
// The volume down key (Windows 2000 or later).
VolumeDown = 174,
//
// Summary:
// The volume up key (Windows 2000 or later).
VolumeUp = 175,
//
// Summary:
// The media next track key (Windows 2000 or later).
MediaNextTrack = 176,
//
// Summary:
// The media previous track key (Windows 2000 or later).
MediaPreviousTrack = 177,
//
// Summary:
// The media Stop key (Windows 2000 or later).
MediaStop = 178,
//
// Summary:
// The media play pause key (Windows 2000 or later).
MediaPlayPause = 179,
//
// Summary:
// The launch mail key (Windows 2000 or later).
LaunchMail = 180,
//
// Summary:
// The select media key (Windows 2000 or later).
SelectMedia = 181,
//
// Summary:
// The start application one key (Windows 2000 or later).
LaunchApplication1 = 182,
//
// Summary:
// The start application two key (Windows 2000 or later).
LaunchApplication2 = 183,
//
// Summary:
// The OEM 1 key.
Oem1 = 186,
//
// Summary:
// The OEM Semicolon key on a US standard keyboard (Windows 2000 or later).
OemSemicolon = 186,
//
// Summary:
// The OEM plus key on any country/region keyboard (Windows 2000 or later).
Oemplus = 187,
//
// Summary:
// The OEM comma key on any country/region keyboard (Windows 2000 or later).
Oemcomma = 188,
//
// Summary:
// The OEM minus key on any country/region keyboard (Windows 2000 or later).
OemMinus = 189,
//
// Summary:
// The OEM period key on any country/region keyboard (Windows 2000 or later).
OemPeriod = 190,
//
// Summary:
// The OEM question mark key on a US standard keyboard (Windows 2000 or later).
OemQuestion = 191,
//
// Summary:
// The OEM 2 key.
Oem2 = 191,
//
// Summary:
// The OEM tilde key on a US standard keyboard (Windows 2000 or later).
Oemtilde = 192,
//
// Summary:
// The OEM 3 key.
Oem3 = 192,
//
// Summary:
// The OEM 4 key.
Oem4 = 219,
//
// Summary:
// The OEM open bracket key on a US standard keyboard (Windows 2000 or later).
OemOpenBrackets = 219,
//
// Summary:
// The OEM pipe key on a US standard keyboard (Windows 2000 or later).
OemPipe = 220,
//
// Summary:
// The OEM 5 key.
Oem5 = 220,
//
// Summary:
// The OEM 6 key.
Oem6 = 221,
//
// Summary:
// The OEM close bracket key on a US standard keyboard (Windows 2000 or later).
OemCloseBrackets = 221,
//
// Summary:
// The OEM 7 key.
Oem7 = 222,
//
// Summary:
// The OEM singled/double quote key on a US standard keyboard (Windows 2000
// or later).
OemQuotes = 222,
//
// Summary:
// The OEM 8 key.
Oem8 = 223,
//
// Summary:
// The OEM 102 key.
Oem102 = 226,
//
// Summary:
// The OEM angle bracket or backslash key on the RT 102 key keyboard (Windows
// 2000 or later).
OemBackslash = 226,
//
// Summary:
// The PROCESS KEY key.
ProcessKey = 229,
//
// Summary:
// Used to pass Unicode characters as if they were keystrokes. The Packet key
// value is the low word of a 32-bit virtual-key value used for non-keyboard
// input methods.
Packet = 231,
//
// Summary:
// The ATTN key.
Attn = 246,
//
// Summary:
// The CRSEL key.
Crsel = 247,
//
// Summary:
// The EXSEL key.
Exsel = 248,
//
// Summary:
// The ERASE EOF key.
EraseEof = 249,
//
// Summary:
// The PLAY key.
Play = 250,
//
// Summary:
// The ZOOM key.
Zoom = 251,
//
// Summary:
// A constant reserved for future use.
NoName = 252,
//
// Summary:
// The PA1 key.
Pa1 = 253,
//
// Summary:
// The CLEAR key.
OemClear = 254,
//
// Summary:
// The bitmask to extract a key code from a key value.
KeyCode = 65535,
//
// Summary:
// The SHIFT modifier key.
Shift = 65536,
//
// Summary:
// The CTRL modifier key.
Control = 131072,
//
// Summary:
// The ALT modifier key.
Alt = 262144,
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig
{
using System;
using System.Collections;
using System.Collections.Generic;
public class GrowOnlySet< TKey >
{
//
// State
//
private int[] m_buckets;
private int[] m_entries_HashCode; // Lower 31 bits of hash code, -1 if unused
private int[] m_entries_Next; // Index of next entry, -1 if last
private TKey[] m_entries_Key; // Key of entry
private int m_count;
private int m_version;
private IEqualityComparer< TKey > m_comparer;
//
// Constructor Methods
//
protected GrowOnlySet() : this( EqualityComparer< TKey >.Default )
{
}
internal GrowOnlySet( IEqualityComparer< TKey > comparer )
{
m_comparer = comparer;
}
//
// Helper Methods
//
public void Clear()
{
m_buckets = null;
m_entries_HashCode = null;
m_entries_Next = null;
m_entries_Key = null;
m_count = 0;
m_version++;
}
public void RefreshHashCodes()
{
for(int i = 0; i < m_count; i++)
{
m_entries_HashCode[i] = m_comparer.GetHashCode( m_entries_Key[i] ) & 0x7FFFFFFF;
}
RebuildBuckets();
}
public bool Insert( TKey key )
{
if(m_buckets == null)
{
Initialize( 0 );
}
int hashCode = m_comparer.GetHashCode( key ) & 0x7FFFFFFF;
int targetBucket = hashCode % m_buckets.Length;
for(int i = m_buckets[targetBucket]; i-- > 0; i = m_entries_Next[i])
{
if(m_entries_HashCode[i] == hashCode && m_comparer.Equals( m_entries_Key[i], key ))
{
return true;
}
}
if(m_count == m_entries_HashCode.Length)
{
Resize();
targetBucket = hashCode % m_buckets.Length;
}
int index = m_count++;
m_entries_HashCode[index] = hashCode;
m_entries_Next [index] = m_buckets[targetBucket];
m_entries_Key [index] = key;
m_buckets[targetBucket] = index + 1;
m_version++;
return false;
}
public TKey MakeUnique( TKey key )
{
TKey oldKey;
if(Contains( key, out oldKey ))
{
return oldKey;
}
Insert( key );
return key;
}
public bool Contains( TKey key )
{
return FindEntry( key ) >= 0;
}
public bool Contains( TKey key ,
out TKey value )
{
int i = FindEntry( key );
if(i >= 0)
{
value = m_entries_Key[i];
return true;
}
value = default( TKey );
return false;
}
public Enumerator GetEnumerator()
{
return new Enumerator( this, m_entries_Key );
}
public void Merge( GrowOnlySet< TKey > target )
{
int num = target.m_count;
TKey[] keys = target.m_entries_Key;
for(int i = 0; i < num; i++)
{
this.Insert( keys[i] );
}
}
public TKey[] ToArray()
{
TKey[] res = new TKey[m_count];
if(m_count > 0)
{
Array.Copy( m_entries_Key, res, m_count );
}
return res;
}
public void Load( TKey[] keys )
{
int size = keys.Length;
Initialize( size );
m_count = size;
m_version++;
Array.Copy( keys, m_entries_Key, size );
RefreshHashCodes();
}
//--//
private void Initialize( int capacity )
{
int size = HashHelpers.GetPrime( capacity );
m_buckets = new int [size];
m_entries_HashCode = new int [size];
m_entries_Next = new int [size];
m_entries_Key = new TKey[size];
}
private void Resize()
{
int newSize = HashHelpers.GetPrime( m_count * 2 );
int[] newBuckets = new int [newSize];
int[] newEntries_HashCode = new int [newSize];
int[] newEntries_Next = new int [newSize];
TKey[] newEntries_Key = new TKey[newSize];
Array.Copy( m_entries_HashCode, 0, newEntries_HashCode, 0, m_count );
Array.Copy( m_entries_Key , 0, newEntries_Key , 0, m_count );
m_buckets = newBuckets;
m_entries_HashCode = newEntries_HashCode;
m_entries_Next = newEntries_Next;
m_entries_Key = newEntries_Key;
RebuildBuckets();
}
private void RebuildBuckets()
{
if(m_buckets != null)
{
int size = m_buckets.Length;
Array.Clear( m_buckets, 0, size );
for(int i = 0; i < m_count; i++)
{
int bucket = m_entries_HashCode[i] % size;
m_entries_Next[i] = m_buckets[bucket];
m_buckets[bucket] = i + 1;
}
}
}
private int FindEntry( TKey key )
{
if(m_buckets != null)
{
int hashCode = m_comparer.GetHashCode( key ) & 0x7FFFFFFF;
for(int i = m_buckets[hashCode % m_buckets.Length]; i-- > 0; i = m_entries_Next[i])
{
if(m_entries_HashCode[i] == hashCode && m_comparer.Equals( m_entries_Key[i], key ))
{
return i;
}
}
}
return -1;
}
//--//
//
// Access Methods
//
public int Count
{
get
{
return m_count;
}
}
public GrowOnlySet< TKey > CloneSettings()
{
return new GrowOnlySet< TKey >( m_comparer );
}
public GrowOnlySet< TKey > Clone()
{
GrowOnlySet< TKey > copy = CloneSettings();
if(m_count > 0)
{
copy.m_buckets = ArrayUtility.CopyNotNullArray( m_buckets );
copy.m_entries_HashCode = ArrayUtility.CopyNotNullArray( m_entries_HashCode );
copy.m_entries_Next = ArrayUtility.CopyNotNullArray( m_entries_Next );
copy.m_entries_Key = ArrayUtility.CopyNotNullArray( m_entries_Key );
copy.m_count = m_count;
}
return copy;
}
//--//
//
// Debug Methods
//
public void Dump()
{
for(int i = 0; i < m_count; i++)
{
Console.WriteLine( "{0} = {1}", i, m_entries_Key[i] );
}
}
//--//--//--//--//--//--//--//--//
public struct Enumerator
{
//
// State
//
private GrowOnlySet< TKey > m_dictionary;
private int m_index;
private int m_version;
private TKey[] m_values;
//
// Constructor Methods
//
internal Enumerator( GrowOnlySet< TKey > dictionary ,
TKey[] values )
{
m_dictionary = dictionary;
m_version = dictionary.m_version;
m_index = 0;
m_values = values;
}
public void Dispose()
{
}
public bool MoveNext()
{
if(m_version != m_dictionary.m_version)
{
throw new Exception( "Dictionary changed" );
}
if(m_index < m_dictionary.m_count)
{
m_index++;
return true;
}
return false;
}
public TKey Current
{
get
{
return m_values[m_index-1];
}
}
void Reset()
{
if(m_version != m_dictionary.m_version)
{
throw new Exception( "Dictionary changed" );
}
m_index = 0;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using Xunit;
using Test.Cryptography;
using System.Security.Cryptography.Pkcs.Tests;
namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests
{
public static partial class DecryptTests
{
public static bool SupportsCngCertificates { get; } = (!PlatformDetection.IsFullFramework || PlatformDetection.IsNetfx462OrNewer());
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void Decrypt_IssuerAndSerial()
{
byte[] content = { 5, 112, 233, 43 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void Decrypt_Ski()
{
byte[] content = { 6, 3, 128, 33, 44 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.SubjectKeyIdentifier);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void Decrypt_Capi()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void Decrypt_256()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha256KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void Decrypt_384()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha384KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void Decrypt_512()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha512KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void Decrypt_SignedWithinEnveloped()
{
byte[] content =
("3082032506092a864886f70d010702a082031630820312020101310b300906052b0e03021a0500301206092a864886f70d01"
+ "0701a0050403010203a08202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e"
+ "03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135303730"
+ "3030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243617069"
+ "3130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03"
+ "e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6"
+ "c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4"
+ "111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e"
+ "311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca3009"
+ "06052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c593166"
+ "2d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957"
+ "d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a4296463181d73081d4020101"
+ "3032301e311c301a060355040313135253414b65795472616e73666572436170693102105d2ffff863babc9b4d3c80ab178a"
+ "4cca300906052b0e03021a0500300d06092a864886f70d010101050004818031a718ea1483c88494661e1d3dedfea0a3d97e"
+ "eb64c3e093a628b257c0cfc183ecf11697ac84f2af882b8de0c793572af38dc15d1b6f3d8f2392ba1cc71210e177c146fd16"
+ "b77a583b6411e801d7a2640d612f2fe99d87e9718e0e505a7ab9536d71dbde329da21816ce7da1416a74a3e0a112b86b33af"
+ "336a2ba6ae2443d0ab").HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Signed), content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void Decrypt_EnvelopedWithinEnveloped()
{
byte[] content =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818013"
+ "dc0eb2984a445d04a1f6246b8fe41f1d24507548d449d454d5bb5e0638d75ed101bf78c0155a5d208eb746755fbccbc86923"
+ "8443760a9ae94770d6373e0197be23a6a891f0c522ca96b3e8008bf23547474b7e24e7f32e8134df3862d84f4dea2470548e"
+ "c774dd74f149a56cdd966e141122900d00ad9d10ea1848541294a1302b06092a864886f70d010701301406082a864886f70d"
+ "030704089c8119f6cf6b174c8008bcea3a10d0737eb9").HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7SignedEnveloped), content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void DecryptMultipleRecipients()
{
// Force Decrypt() to try multiple recipients. Ensure that a failure to find a matching cert in one doesn't cause it to quit early.
CertLoader[] certLoaders = new CertLoader[]
{
Certificates.RSAKeyTransfer1,
Certificates.RSAKeyTransfer2,
Certificates.RSAKeyTransfer3,
};
byte[] content = { 6, 3, 128, 33, 44 };
EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(content), new AlgorithmIdentifier(new Oid(Oids.Aes256)));
CmsRecipientCollection recipients = new CmsRecipientCollection();
foreach (CertLoader certLoader in certLoaders)
{
recipients.Add(new CmsRecipient(certLoader.GetCertificate()));
}
ecms.Encrypt(recipients);
byte[] encodedMessage = ecms.Encode();
ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
// How do we know that Decrypt() tries receipients in the order they appear in ecms.RecipientInfos? Because we wrote the implementation.
// Not that some future implementation can't ever change it but it's the best guess we have.
RecipientInfo me = ecms.RecipientInfos[2];
CertLoader matchingCertLoader = null;
for (int index = 0; index < recipients.Count; index++)
{
if (recipients[index].Certificate.Issuer == ((X509IssuerSerial)(me.RecipientIdentifier.Value)).IssuerName)
{
matchingCertLoader = certLoaders[index];
break;
}
}
Assert.NotNull(matchingCertLoader);
using (X509Certificate2 cert = matchingCertLoader.TryGetCertificateWithPrivateKey())
{
if (cert == null)
return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can.
X509Certificate2Collection extraStore = new X509Certificate2Collection();
extraStore.Add(cert);
ecms.Decrypt(extraStore);
}
ContentInfo contentInfo = ecms.ContentInfo;
Assert.Equal<byte>(content, contentInfo.Content);
}
private static void TestSimpleDecrypt_RoundTrip(CertLoader certLoader, ContentInfo contentInfo, string algorithmOidValue, SubjectIdentifierType type)
{
// Deep-copy the contentInfo since the real ContentInfo doesn't do this. This defends against a bad implementation changing
// our "expectedContentInfo" to match what it produces.
ContentInfo expectedContentInfo = new ContentInfo(new Oid(contentInfo.ContentType), (byte[])(contentInfo.Content.Clone()));
string certSubjectName;
byte[] encodedMessage;
using (X509Certificate2 certificate = certLoader.GetCertificate())
{
certSubjectName = certificate.Subject;
AlgorithmIdentifier alg = new AlgorithmIdentifier(new Oid(algorithmOidValue));
EnvelopedCms ecms = new EnvelopedCms(contentInfo, alg);
CmsRecipient cmsRecipient = new CmsRecipient(type, certificate);
ecms.Encrypt(cmsRecipient);
encodedMessage = ecms.Encode();
}
// We don't pass "certificate" down because it's expected that the certificate used for encrypting doesn't have a private key (part of the purpose of this test is
// to ensure that you don't need the recipient's private key to encrypt.) The decrypt phase will have to locate the matching cert with the private key.
VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo);
}
private static void VerifySimpleDecrypt(byte[] encodedMessage, CertLoader certLoader, ContentInfo expectedContent)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
using (X509Certificate2 cert = certLoader.TryGetCertificateWithPrivateKey())
{
if (cert == null)
return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can.
X509Certificate2Collection extraStore = new X509Certificate2Collection(cert);
ecms.Decrypt(extraStore);
ContentInfo contentInfo = ecms.ContentInfo;
Assert.Equal(expectedContent.ContentType.Value, contentInfo.ContentType.Value);
Assert.Equal<byte>(expectedContent.Content, contentInfo.Content);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class NonLiftedComparisonGreaterThanOrEqualNullableTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanOrEqualNullableByteTest(bool useInterpreter)
{
byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanOrEqualNullableByte(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanOrEqualNullableCharTest(bool useInterpreter)
{
char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanOrEqualNullableChar(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanOrEqualNullableDecimalTest(bool useInterpreter)
{
decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanOrEqualNullableDecimal(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanOrEqualNullableDoubleTest(bool useInterpreter)
{
double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanOrEqualNullableDouble(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanOrEqualNullableFloatTest(bool useInterpreter)
{
float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanOrEqualNullableFloat(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanOrEqualNullableIntTest(bool useInterpreter)
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanOrEqualNullableInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanOrEqualNullableLongTest(bool useInterpreter)
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanOrEqualNullableLong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanOrEqualNullableSByteTest(bool useInterpreter)
{
sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanOrEqualNullableSByte(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanOrEqualNullableShortTest(bool useInterpreter)
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanOrEqualNullableShort(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanOrEqualNullableUIntTest(bool useInterpreter)
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanOrEqualNullableUInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanOrEqualNullableULongTest(bool useInterpreter)
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanOrEqualNullableULong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanOrEqualNullableUShortTest(bool useInterpreter)
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanOrEqualNullableUShort(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyComparisonGreaterThanOrEqualNullableByte(byte? a, byte? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThanOrEqual(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a >= b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanOrEqualNullableChar(char? a, char? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThanOrEqual(
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a >= b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanOrEqualNullableDecimal(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThanOrEqual(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a >= b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanOrEqualNullableDouble(double? a, double? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThanOrEqual(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a >= b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanOrEqualNullableFloat(float? a, float? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThanOrEqual(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a >= b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanOrEqualNullableInt(int? a, int? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThanOrEqual(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a >= b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanOrEqualNullableLong(long? a, long? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThanOrEqual(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a >= b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanOrEqualNullableSByte(sbyte? a, sbyte? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThanOrEqual(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a >= b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanOrEqualNullableShort(short? a, short? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThanOrEqual(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a >= b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanOrEqualNullableUInt(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThanOrEqual(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a >= b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanOrEqualNullableULong(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThanOrEqual(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a >= b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanOrEqualNullableUShort(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThanOrEqual(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a >= b;
bool result = f();
Assert.Equal(expected, result);
}
#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.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Serialization.External;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.Framework.Scenes.Serialization
{
/// <summary>
/// Serialize and deserialize scene objects.
/// </summary>
/// This should really be in OpenSim.Framework.Serialization but this would mean circular dependency problems
/// right now - hopefully this isn't forever.
public class SceneObjectSerializer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static IUserManagement m_UserManagement;
/// <summary>
/// Deserialize a scene object from the original xml format
/// </summary>
/// <param name="xmlData"></param>
/// <returns>The scene object deserialized. Null on failure.</returns>
public static SceneObjectGroup FromOriginalXmlFormat(string xmlData)
{
//m_log.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = System.Environment.TickCount;
try
{
StringReader sr;
XmlTextReader reader;
XmlNodeList parts;
XmlDocument doc;
int linkNum;
doc = new XmlDocument();
doc.LoadXml(xmlData);
parts = doc.GetElementsByTagName("RootPart");
if (parts.Count == 0)
throw new Exception("Invalid Xml format - no root part");
sr = new StringReader(parts[0].InnerXml);
reader = new XmlTextReader(sr);
SceneObjectGroup sceneObject = new SceneObjectGroup(SceneObjectPart.FromXml(reader));
reader.Close();
sr.Close();
parts = doc.GetElementsByTagName("Part");
for (int i = 0; i < parts.Count; i++)
{
sr = new StringReader(parts[i].InnerXml);
reader = new XmlTextReader(sr);
SceneObjectPart part = SceneObjectPart.FromXml(reader);
linkNum = part.LinkNum;
sceneObject.AddPart(part);
part.LinkNum = linkNum;
part.TrimPermissions();
reader.Close();
sr.Close();
}
// Script state may, or may not, exist. Not having any, is NOT
// ever a problem.
sceneObject.LoadScriptState(doc);
return sceneObject;
}
catch (Exception e)
{
m_log.ErrorFormat(
"[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, xmlData);
return null;
}
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject)
{
return ToOriginalXmlFormat(sceneObject, true);
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <param name="doScriptStates">Control whether script states are also serialized.</para>
/// <returns></returns>
public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject, bool doScriptStates)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
ToOriginalXmlFormat(sceneObject, writer, doScriptStates);
}
return sw.ToString();
}
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static void ToOriginalXmlFormat(SceneObjectGroup sceneObject, XmlTextWriter writer, bool doScriptStates)
{
ToOriginalXmlFormat(sceneObject, writer, doScriptStates, false);
}
public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject, string scriptedState)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
ToOriginalXmlFormat(sceneObject, writer, false, true);
writer.WriteRaw(scriptedState);
writer.WriteEndElement();
}
return sw.ToString();
}
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <param name="writer"></param>
/// <param name="noRootElement">If false, don't write the enclosing SceneObjectGroup element</param>
/// <returns></returns>
public static void ToOriginalXmlFormat(
SceneObjectGroup sceneObject, XmlTextWriter writer, bool doScriptStates, bool noRootElement)
{
// m_log.DebugFormat("[SERIALIZER]: Starting serialization of {0}", sceneObject.Name);
// int time = System.Environment.TickCount;
if (!noRootElement)
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
writer.WriteStartElement(String.Empty, "RootPart", String.Empty);
ToXmlFormat(sceneObject.RootPart, writer);
writer.WriteEndElement();
writer.WriteStartElement(String.Empty, "OtherParts", String.Empty);
SceneObjectPart[] parts = sceneObject.Parts;
for (int i = 0; i < parts.Length; i++)
{
SceneObjectPart part = parts[i];
if (part.UUID != sceneObject.RootPart.UUID)
{
writer.WriteStartElement(String.Empty, "Part", String.Empty);
ToXmlFormat(part, writer);
writer.WriteEndElement();
}
}
writer.WriteEndElement(); // OtherParts
if (doScriptStates)
sceneObject.SaveScriptedState(writer);
if (!noRootElement)
writer.WriteEndElement(); // SceneObjectGroup
// m_log.DebugFormat("[SERIALIZER]: Finished serialization of SOG {0}, {1}ms", sceneObject.Name, System.Environment.TickCount - time);
}
protected static void ToXmlFormat(SceneObjectPart part, XmlTextWriter writer)
{
SOPToXml2(writer, part, new Dictionary<string, object>());
}
public static SceneObjectGroup FromXml2Format(string xmlData)
{
//m_log.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = System.Environment.TickCount;
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlData);
XmlNodeList parts = doc.GetElementsByTagName("SceneObjectPart");
if (parts.Count == 0)
{
m_log.ErrorFormat("[SERIALIZER]: Deserialization of xml failed: No SceneObjectPart nodes. xml was " + xmlData);
return null;
}
StringReader sr = new StringReader(parts[0].OuterXml);
XmlTextReader reader = new XmlTextReader(sr);
SceneObjectGroup sceneObject = new SceneObjectGroup(SceneObjectPart.FromXml(reader));
reader.Close();
sr.Close();
// Then deal with the rest
for (int i = 1; i < parts.Count; i++)
{
sr = new StringReader(parts[i].OuterXml);
reader = new XmlTextReader(sr);
SceneObjectPart part = SceneObjectPart.FromXml(reader);
int originalLinkNum = part.LinkNum;
sceneObject.AddPart(part);
// SceneObjectGroup.AddPart() tries to be smart and automatically set the LinkNum.
// We override that here
if (originalLinkNum != 0)
part.LinkNum = originalLinkNum;
reader.Close();
sr.Close();
}
XmlNodeList keymotion = doc.GetElementsByTagName("KeyframeMotion");
if (keymotion.Count > 0)
sceneObject.RootPart.KeyframeMotion = KeyframeMotion.FromData(sceneObject, Convert.FromBase64String(keymotion[0].InnerText));
else
sceneObject.RootPart.KeyframeMotion = null;
// Script state may, or may not, exist. Not having any, is NOT
// ever a problem.
sceneObject.LoadScriptState(doc);
return sceneObject;
}
catch (Exception e)
{
m_log.ErrorFormat("[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, xmlData);
return null;
}
}
/// <summary>
/// Serialize a scene object to the 'xml2' format.
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static string ToXml2Format(SceneObjectGroup sceneObject)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
SOGToXml2(writer, sceneObject, new Dictionary<string,object>());
}
return sw.ToString();
}
}
#region manual serialization
private static Dictionary<string, Action<SceneObjectPart, XmlTextReader>> m_SOPXmlProcessors
= new Dictionary<string, Action<SceneObjectPart, XmlTextReader>>();
private static Dictionary<string, Action<TaskInventoryItem, XmlTextReader>> m_TaskInventoryXmlProcessors
= new Dictionary<string, Action<TaskInventoryItem, XmlTextReader>>();
private static Dictionary<string, Action<PrimitiveBaseShape, XmlTextReader>> m_ShapeXmlProcessors
= new Dictionary<string, Action<PrimitiveBaseShape, XmlTextReader>>();
static SceneObjectSerializer()
{
#region SOPXmlProcessors initialization
m_SOPXmlProcessors.Add("AllowedDrop", ProcessAllowedDrop);
m_SOPXmlProcessors.Add("CreatorID", ProcessCreatorID);
m_SOPXmlProcessors.Add("CreatorData", ProcessCreatorData);
m_SOPXmlProcessors.Add("FolderID", ProcessFolderID);
m_SOPXmlProcessors.Add("InventorySerial", ProcessInventorySerial);
m_SOPXmlProcessors.Add("TaskInventory", ProcessTaskInventory);
m_SOPXmlProcessors.Add("UUID", ProcessUUID);
m_SOPXmlProcessors.Add("LocalId", ProcessLocalId);
m_SOPXmlProcessors.Add("Name", ProcessName);
m_SOPXmlProcessors.Add("Material", ProcessMaterial);
m_SOPXmlProcessors.Add("PassTouches", ProcessPassTouches);
m_SOPXmlProcessors.Add("PassCollisions", ProcessPassCollisions);
m_SOPXmlProcessors.Add("RegionHandle", ProcessRegionHandle);
m_SOPXmlProcessors.Add("ScriptAccessPin", ProcessScriptAccessPin);
m_SOPXmlProcessors.Add("GroupPosition", ProcessGroupPosition);
m_SOPXmlProcessors.Add("OffsetPosition", ProcessOffsetPosition);
m_SOPXmlProcessors.Add("RotationOffset", ProcessRotationOffset);
m_SOPXmlProcessors.Add("Velocity", ProcessVelocity);
m_SOPXmlProcessors.Add("AngularVelocity", ProcessAngularVelocity);
m_SOPXmlProcessors.Add("Acceleration", ProcessAcceleration);
m_SOPXmlProcessors.Add("Description", ProcessDescription);
m_SOPXmlProcessors.Add("Color", ProcessColor);
m_SOPXmlProcessors.Add("Text", ProcessText);
m_SOPXmlProcessors.Add("SitName", ProcessSitName);
m_SOPXmlProcessors.Add("TouchName", ProcessTouchName);
m_SOPXmlProcessors.Add("LinkNum", ProcessLinkNum);
m_SOPXmlProcessors.Add("ClickAction", ProcessClickAction);
m_SOPXmlProcessors.Add("Shape", ProcessShape);
m_SOPXmlProcessors.Add("Scale", ProcessScale);
m_SOPXmlProcessors.Add("SitTargetOrientation", ProcessSitTargetOrientation);
m_SOPXmlProcessors.Add("SitTargetPosition", ProcessSitTargetPosition);
m_SOPXmlProcessors.Add("SitTargetPositionLL", ProcessSitTargetPositionLL);
m_SOPXmlProcessors.Add("SitTargetOrientationLL", ProcessSitTargetOrientationLL);
m_SOPXmlProcessors.Add("ParentID", ProcessParentID);
m_SOPXmlProcessors.Add("CreationDate", ProcessCreationDate);
m_SOPXmlProcessors.Add("Category", ProcessCategory);
m_SOPXmlProcessors.Add("SalePrice", ProcessSalePrice);
m_SOPXmlProcessors.Add("ObjectSaleType", ProcessObjectSaleType);
m_SOPXmlProcessors.Add("OwnershipCost", ProcessOwnershipCost);
m_SOPXmlProcessors.Add("GroupID", ProcessGroupID);
m_SOPXmlProcessors.Add("OwnerID", ProcessOwnerID);
m_SOPXmlProcessors.Add("LastOwnerID", ProcessLastOwnerID);
m_SOPXmlProcessors.Add("BaseMask", ProcessBaseMask);
m_SOPXmlProcessors.Add("OwnerMask", ProcessOwnerMask);
m_SOPXmlProcessors.Add("GroupMask", ProcessGroupMask);
m_SOPXmlProcessors.Add("EveryoneMask", ProcessEveryoneMask);
m_SOPXmlProcessors.Add("NextOwnerMask", ProcessNextOwnerMask);
m_SOPXmlProcessors.Add("Flags", ProcessFlags);
m_SOPXmlProcessors.Add("CollisionSound", ProcessCollisionSound);
m_SOPXmlProcessors.Add("CollisionSoundVolume", ProcessCollisionSoundVolume);
m_SOPXmlProcessors.Add("MediaUrl", ProcessMediaUrl);
m_SOPXmlProcessors.Add("DynAttrs", ProcessDynAttrs);
m_SOPXmlProcessors.Add("TextureAnimation", ProcessTextureAnimation);
m_SOPXmlProcessors.Add("ParticleSystem", ProcessParticleSystem);
m_SOPXmlProcessors.Add("PayPrice0", ProcessPayPrice0);
m_SOPXmlProcessors.Add("PayPrice1", ProcessPayPrice1);
m_SOPXmlProcessors.Add("PayPrice2", ProcessPayPrice2);
m_SOPXmlProcessors.Add("PayPrice3", ProcessPayPrice3);
m_SOPXmlProcessors.Add("PayPrice4", ProcessPayPrice4);
m_SOPXmlProcessors.Add("PhysicsShapeType", ProcessPhysicsShapeType);
m_SOPXmlProcessors.Add("Density", ProcessDensity);
m_SOPXmlProcessors.Add("Friction", ProcessFriction);
m_SOPXmlProcessors.Add("Bounce", ProcessBounce);
m_SOPXmlProcessors.Add("GravityModifier", ProcessGravityModifier);
#endregion
#region TaskInventoryXmlProcessors initialization
m_TaskInventoryXmlProcessors.Add("AssetID", ProcessTIAssetID);
m_TaskInventoryXmlProcessors.Add("BasePermissions", ProcessTIBasePermissions);
m_TaskInventoryXmlProcessors.Add("CreationDate", ProcessTICreationDate);
m_TaskInventoryXmlProcessors.Add("CreatorID", ProcessTICreatorID);
m_TaskInventoryXmlProcessors.Add("CreatorData", ProcessTICreatorData);
m_TaskInventoryXmlProcessors.Add("Description", ProcessTIDescription);
m_TaskInventoryXmlProcessors.Add("EveryonePermissions", ProcessTIEveryonePermissions);
m_TaskInventoryXmlProcessors.Add("Flags", ProcessTIFlags);
m_TaskInventoryXmlProcessors.Add("GroupID", ProcessTIGroupID);
m_TaskInventoryXmlProcessors.Add("GroupPermissions", ProcessTIGroupPermissions);
m_TaskInventoryXmlProcessors.Add("InvType", ProcessTIInvType);
m_TaskInventoryXmlProcessors.Add("ItemID", ProcessTIItemID);
m_TaskInventoryXmlProcessors.Add("OldItemID", ProcessTIOldItemID);
m_TaskInventoryXmlProcessors.Add("LastOwnerID", ProcessTILastOwnerID);
m_TaskInventoryXmlProcessors.Add("Name", ProcessTIName);
m_TaskInventoryXmlProcessors.Add("NextPermissions", ProcessTINextPermissions);
m_TaskInventoryXmlProcessors.Add("OwnerID", ProcessTIOwnerID);
m_TaskInventoryXmlProcessors.Add("CurrentPermissions", ProcessTICurrentPermissions);
m_TaskInventoryXmlProcessors.Add("ParentID", ProcessTIParentID);
m_TaskInventoryXmlProcessors.Add("ParentPartID", ProcessTIParentPartID);
m_TaskInventoryXmlProcessors.Add("PermsGranter", ProcessTIPermsGranter);
m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask);
m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType);
m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged);
#endregion
#region ShapeXmlProcessors initialization
m_ShapeXmlProcessors.Add("ProfileCurve", ProcessShpProfileCurve);
m_ShapeXmlProcessors.Add("TextureEntry", ProcessShpTextureEntry);
m_ShapeXmlProcessors.Add("ExtraParams", ProcessShpExtraParams);
m_ShapeXmlProcessors.Add("PathBegin", ProcessShpPathBegin);
m_ShapeXmlProcessors.Add("PathCurve", ProcessShpPathCurve);
m_ShapeXmlProcessors.Add("PathEnd", ProcessShpPathEnd);
m_ShapeXmlProcessors.Add("PathRadiusOffset", ProcessShpPathRadiusOffset);
m_ShapeXmlProcessors.Add("PathRevolutions", ProcessShpPathRevolutions);
m_ShapeXmlProcessors.Add("PathScaleX", ProcessShpPathScaleX);
m_ShapeXmlProcessors.Add("PathScaleY", ProcessShpPathScaleY);
m_ShapeXmlProcessors.Add("PathShearX", ProcessShpPathShearX);
m_ShapeXmlProcessors.Add("PathShearY", ProcessShpPathShearY);
m_ShapeXmlProcessors.Add("PathSkew", ProcessShpPathSkew);
m_ShapeXmlProcessors.Add("PathTaperX", ProcessShpPathTaperX);
m_ShapeXmlProcessors.Add("PathTaperY", ProcessShpPathTaperY);
m_ShapeXmlProcessors.Add("PathTwist", ProcessShpPathTwist);
m_ShapeXmlProcessors.Add("PathTwistBegin", ProcessShpPathTwistBegin);
m_ShapeXmlProcessors.Add("PCode", ProcessShpPCode);
m_ShapeXmlProcessors.Add("ProfileBegin", ProcessShpProfileBegin);
m_ShapeXmlProcessors.Add("ProfileEnd", ProcessShpProfileEnd);
m_ShapeXmlProcessors.Add("ProfileHollow", ProcessShpProfileHollow);
m_ShapeXmlProcessors.Add("Scale", ProcessShpScale);
m_ShapeXmlProcessors.Add("State", ProcessShpState);
m_ShapeXmlProcessors.Add("ProfileShape", ProcessShpProfileShape);
m_ShapeXmlProcessors.Add("HollowShape", ProcessShpHollowShape);
m_ShapeXmlProcessors.Add("SculptTexture", ProcessShpSculptTexture);
m_ShapeXmlProcessors.Add("SculptType", ProcessShpSculptType);
m_ShapeXmlProcessors.Add("SculptData", ProcessShpSculptData);
m_ShapeXmlProcessors.Add("FlexiSoftness", ProcessShpFlexiSoftness);
m_ShapeXmlProcessors.Add("FlexiTension", ProcessShpFlexiTension);
m_ShapeXmlProcessors.Add("FlexiDrag", ProcessShpFlexiDrag);
m_ShapeXmlProcessors.Add("FlexiGravity", ProcessShpFlexiGravity);
m_ShapeXmlProcessors.Add("FlexiWind", ProcessShpFlexiWind);
m_ShapeXmlProcessors.Add("FlexiForceX", ProcessShpFlexiForceX);
m_ShapeXmlProcessors.Add("FlexiForceY", ProcessShpFlexiForceY);
m_ShapeXmlProcessors.Add("FlexiForceZ", ProcessShpFlexiForceZ);
m_ShapeXmlProcessors.Add("LightColorR", ProcessShpLightColorR);
m_ShapeXmlProcessors.Add("LightColorG", ProcessShpLightColorG);
m_ShapeXmlProcessors.Add("LightColorB", ProcessShpLightColorB);
m_ShapeXmlProcessors.Add("LightColorA", ProcessShpLightColorA);
m_ShapeXmlProcessors.Add("LightRadius", ProcessShpLightRadius);
m_ShapeXmlProcessors.Add("LightCutoff", ProcessShpLightCutoff);
m_ShapeXmlProcessors.Add("LightFalloff", ProcessShpLightFalloff);
m_ShapeXmlProcessors.Add("LightIntensity", ProcessShpLightIntensity);
m_ShapeXmlProcessors.Add("FlexiEntry", ProcessShpFlexiEntry);
m_ShapeXmlProcessors.Add("LightEntry", ProcessShpLightEntry);
m_ShapeXmlProcessors.Add("SculptEntry", ProcessShpSculptEntry);
m_ShapeXmlProcessors.Add("Media", ProcessShpMedia);
#endregion
}
#region SOPXmlProcessors
private static void ProcessAllowedDrop(SceneObjectPart obj, XmlTextReader reader)
{
obj.AllowedDrop = Util.ReadBoolean(reader);
}
private static void ProcessCreatorID(SceneObjectPart obj, XmlTextReader reader)
{
obj.CreatorID = Util.ReadUUID(reader, "CreatorID");
}
private static void ProcessCreatorData(SceneObjectPart obj, XmlTextReader reader)
{
obj.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty);
}
private static void ProcessFolderID(SceneObjectPart obj, XmlTextReader reader)
{
obj.FolderID = Util.ReadUUID(reader, "FolderID");
}
private static void ProcessInventorySerial(SceneObjectPart obj, XmlTextReader reader)
{
obj.InventorySerial = (uint)reader.ReadElementContentAsInt("InventorySerial", String.Empty);
}
private static void ProcessTaskInventory(SceneObjectPart obj, XmlTextReader reader)
{
obj.TaskInventory = ReadTaskInventory(reader, "TaskInventory");
}
private static void ProcessUUID(SceneObjectPart obj, XmlTextReader reader)
{
obj.UUID = Util.ReadUUID(reader, "UUID");
}
private static void ProcessLocalId(SceneObjectPart obj, XmlTextReader reader)
{
obj.LocalId = (uint)reader.ReadElementContentAsLong("LocalId", String.Empty);
}
private static void ProcessName(SceneObjectPart obj, XmlTextReader reader)
{
obj.Name = reader.ReadElementString("Name");
}
private static void ProcessMaterial(SceneObjectPart obj, XmlTextReader reader)
{
obj.Material = (byte)reader.ReadElementContentAsInt("Material", String.Empty);
}
private static void ProcessPassTouches(SceneObjectPart obj, XmlTextReader reader)
{
obj.PassTouches = Util.ReadBoolean(reader);
}
private static void ProcessPassCollisions(SceneObjectPart obj, XmlTextReader reader)
{
obj.PassCollisions = Util.ReadBoolean(reader);
}
private static void ProcessRegionHandle(SceneObjectPart obj, XmlTextReader reader)
{
obj.RegionHandle = (ulong)reader.ReadElementContentAsLong("RegionHandle", String.Empty);
}
private static void ProcessScriptAccessPin(SceneObjectPart obj, XmlTextReader reader)
{
obj.ScriptAccessPin = reader.ReadElementContentAsInt("ScriptAccessPin", String.Empty);
}
private static void ProcessGroupPosition(SceneObjectPart obj, XmlTextReader reader)
{
obj.GroupPosition = Util.ReadVector(reader, "GroupPosition");
}
private static void ProcessOffsetPosition(SceneObjectPart obj, XmlTextReader reader)
{
obj.OffsetPosition = Util.ReadVector(reader, "OffsetPosition"); ;
}
private static void ProcessRotationOffset(SceneObjectPart obj, XmlTextReader reader)
{
obj.RotationOffset = Util.ReadQuaternion(reader, "RotationOffset");
}
private static void ProcessVelocity(SceneObjectPart obj, XmlTextReader reader)
{
obj.Velocity = Util.ReadVector(reader, "Velocity");
}
private static void ProcessAngularVelocity(SceneObjectPart obj, XmlTextReader reader)
{
obj.AngularVelocity = Util.ReadVector(reader, "AngularVelocity");
}
private static void ProcessAcceleration(SceneObjectPart obj, XmlTextReader reader)
{
obj.Acceleration = Util.ReadVector(reader, "Acceleration");
}
private static void ProcessDescription(SceneObjectPart obj, XmlTextReader reader)
{
obj.Description = reader.ReadElementString("Description");
}
private static void ProcessColor(SceneObjectPart obj, XmlTextReader reader)
{
reader.ReadStartElement("Color");
if (reader.Name == "R")
{
float r = reader.ReadElementContentAsFloat("R", String.Empty);
float g = reader.ReadElementContentAsFloat("G", String.Empty);
float b = reader.ReadElementContentAsFloat("B", String.Empty);
float a = reader.ReadElementContentAsFloat("A", String.Empty);
obj.Color = Color.FromArgb((int)a, (int)r, (int)g, (int)b);
reader.ReadEndElement();
}
}
private static void ProcessText(SceneObjectPart obj, XmlTextReader reader)
{
obj.Text = reader.ReadElementString("Text", String.Empty);
}
private static void ProcessSitName(SceneObjectPart obj, XmlTextReader reader)
{
obj.SitName = reader.ReadElementString("SitName", String.Empty);
}
private static void ProcessTouchName(SceneObjectPart obj, XmlTextReader reader)
{
obj.TouchName = reader.ReadElementString("TouchName", String.Empty);
}
private static void ProcessLinkNum(SceneObjectPart obj, XmlTextReader reader)
{
obj.LinkNum = reader.ReadElementContentAsInt("LinkNum", String.Empty);
}
private static void ProcessClickAction(SceneObjectPart obj, XmlTextReader reader)
{
obj.ClickAction = (byte)reader.ReadElementContentAsInt("ClickAction", String.Empty);
}
private static void ProcessPhysicsShapeType(SceneObjectPart obj, XmlTextReader reader)
{
obj.PhysicsShapeType = (byte)reader.ReadElementContentAsInt("PhysicsShapeType", String.Empty);
}
private static void ProcessDensity(SceneObjectPart obj, XmlTextReader reader)
{
obj.Density = reader.ReadElementContentAsFloat("Density", String.Empty);
}
private static void ProcessFriction(SceneObjectPart obj, XmlTextReader reader)
{
obj.Friction = reader.ReadElementContentAsFloat("Friction", String.Empty);
}
private static void ProcessBounce(SceneObjectPart obj, XmlTextReader reader)
{
obj.Restitution = reader.ReadElementContentAsFloat("Bounce", String.Empty);
}
private static void ProcessGravityModifier(SceneObjectPart obj, XmlTextReader reader)
{
obj.GravityModifier = reader.ReadElementContentAsFloat("GravityModifier", String.Empty);
}
private static void ProcessShape(SceneObjectPart obj, XmlTextReader reader)
{
List<string> errorNodeNames;
obj.Shape = ReadShape(reader, "Shape", out errorNodeNames);
if (errorNodeNames != null)
{
m_log.DebugFormat(
"[SceneObjectSerializer]: Parsing PrimitiveBaseShape for object part {0} {1} encountered errors in properties {2}.",
obj.Name, obj.UUID, string.Join(", ", errorNodeNames.ToArray()));
}
}
private static void ProcessScale(SceneObjectPart obj, XmlTextReader reader)
{
obj.Scale = Util.ReadVector(reader, "Scale");
}
private static void ProcessSitTargetOrientation(SceneObjectPart obj, XmlTextReader reader)
{
obj.SitTargetOrientation = Util.ReadQuaternion(reader, "SitTargetOrientation");
}
private static void ProcessSitTargetPosition(SceneObjectPart obj, XmlTextReader reader)
{
obj.SitTargetPosition = Util.ReadVector(reader, "SitTargetPosition");
}
private static void ProcessSitTargetPositionLL(SceneObjectPart obj, XmlTextReader reader)
{
obj.SitTargetPositionLL = Util.ReadVector(reader, "SitTargetPositionLL");
}
private static void ProcessSitTargetOrientationLL(SceneObjectPart obj, XmlTextReader reader)
{
obj.SitTargetOrientationLL = Util.ReadQuaternion(reader, "SitTargetOrientationLL");
}
private static void ProcessParentID(SceneObjectPart obj, XmlTextReader reader)
{
string str = reader.ReadElementContentAsString("ParentID", String.Empty);
obj.ParentID = Convert.ToUInt32(str);
}
private static void ProcessCreationDate(SceneObjectPart obj, XmlTextReader reader)
{
obj.CreationDate = reader.ReadElementContentAsInt("CreationDate", String.Empty);
}
private static void ProcessCategory(SceneObjectPart obj, XmlTextReader reader)
{
obj.Category = (uint)reader.ReadElementContentAsInt("Category", String.Empty);
}
private static void ProcessSalePrice(SceneObjectPart obj, XmlTextReader reader)
{
obj.SalePrice = reader.ReadElementContentAsInt("SalePrice", String.Empty);
}
private static void ProcessObjectSaleType(SceneObjectPart obj, XmlTextReader reader)
{
obj.ObjectSaleType = (byte)reader.ReadElementContentAsInt("ObjectSaleType", String.Empty);
}
private static void ProcessOwnershipCost(SceneObjectPart obj, XmlTextReader reader)
{
obj.OwnershipCost = reader.ReadElementContentAsInt("OwnershipCost", String.Empty);
}
private static void ProcessGroupID(SceneObjectPart obj, XmlTextReader reader)
{
obj.GroupID = Util.ReadUUID(reader, "GroupID");
}
private static void ProcessOwnerID(SceneObjectPart obj, XmlTextReader reader)
{
obj.OwnerID = Util.ReadUUID(reader, "OwnerID");
}
private static void ProcessLastOwnerID(SceneObjectPart obj, XmlTextReader reader)
{
obj.LastOwnerID = Util.ReadUUID(reader, "LastOwnerID");
}
private static void ProcessBaseMask(SceneObjectPart obj, XmlTextReader reader)
{
obj.BaseMask = (uint)reader.ReadElementContentAsInt("BaseMask", String.Empty);
}
private static void ProcessOwnerMask(SceneObjectPart obj, XmlTextReader reader)
{
obj.OwnerMask = (uint)reader.ReadElementContentAsInt("OwnerMask", String.Empty);
}
private static void ProcessGroupMask(SceneObjectPart obj, XmlTextReader reader)
{
obj.GroupMask = (uint)reader.ReadElementContentAsInt("GroupMask", String.Empty);
}
private static void ProcessEveryoneMask(SceneObjectPart obj, XmlTextReader reader)
{
obj.EveryoneMask = (uint)reader.ReadElementContentAsInt("EveryoneMask", String.Empty);
}
private static void ProcessNextOwnerMask(SceneObjectPart obj, XmlTextReader reader)
{
obj.NextOwnerMask = (uint)reader.ReadElementContentAsInt("NextOwnerMask", String.Empty);
}
private static void ProcessFlags(SceneObjectPart obj, XmlTextReader reader)
{
obj.Flags = Util.ReadEnum<PrimFlags>(reader, "Flags");
}
private static void ProcessCollisionSound(SceneObjectPart obj, XmlTextReader reader)
{
obj.CollisionSound = Util.ReadUUID(reader, "CollisionSound");
}
private static void ProcessCollisionSoundVolume(SceneObjectPart obj, XmlTextReader reader)
{
obj.CollisionSoundVolume = reader.ReadElementContentAsFloat("CollisionSoundVolume", String.Empty);
}
private static void ProcessMediaUrl(SceneObjectPart obj, XmlTextReader reader)
{
obj.MediaUrl = reader.ReadElementContentAsString("MediaUrl", String.Empty);
}
private static void ProcessDynAttrs(SceneObjectPart obj, XmlTextReader reader)
{
obj.DynAttrs.ReadXml(reader);
}
private static void ProcessTextureAnimation(SceneObjectPart obj, XmlTextReader reader)
{
obj.TextureAnimation = Convert.FromBase64String(reader.ReadElementContentAsString("TextureAnimation", String.Empty));
}
private static void ProcessParticleSystem(SceneObjectPart obj, XmlTextReader reader)
{
obj.ParticleSystem = Convert.FromBase64String(reader.ReadElementContentAsString("ParticleSystem", String.Empty));
}
private static void ProcessPayPrice0(SceneObjectPart obj, XmlTextReader reader)
{
obj.PayPrice[0] = (int)reader.ReadElementContentAsInt("PayPrice0", String.Empty);
}
private static void ProcessPayPrice1(SceneObjectPart obj, XmlTextReader reader)
{
obj.PayPrice[1] = (int)reader.ReadElementContentAsInt("PayPrice1", String.Empty);
}
private static void ProcessPayPrice2(SceneObjectPart obj, XmlTextReader reader)
{
obj.PayPrice[2] = (int)reader.ReadElementContentAsInt("PayPrice2", String.Empty);
}
private static void ProcessPayPrice3(SceneObjectPart obj, XmlTextReader reader)
{
obj.PayPrice[3] = (int)reader.ReadElementContentAsInt("PayPrice3", String.Empty);
}
private static void ProcessPayPrice4(SceneObjectPart obj, XmlTextReader reader)
{
obj.PayPrice[4] = (int)reader.ReadElementContentAsInt("PayPrice4", String.Empty);
}
#endregion
#region TaskInventoryXmlProcessors
private static void ProcessTIAssetID(TaskInventoryItem item, XmlTextReader reader)
{
item.AssetID = Util.ReadUUID(reader, "AssetID");
}
private static void ProcessTIBasePermissions(TaskInventoryItem item, XmlTextReader reader)
{
item.BasePermissions = (uint)reader.ReadElementContentAsInt("BasePermissions", String.Empty);
}
private static void ProcessTICreationDate(TaskInventoryItem item, XmlTextReader reader)
{
item.CreationDate = (uint)reader.ReadElementContentAsInt("CreationDate", String.Empty);
}
private static void ProcessTICreatorID(TaskInventoryItem item, XmlTextReader reader)
{
item.CreatorID = Util.ReadUUID(reader, "CreatorID");
}
private static void ProcessTICreatorData(TaskInventoryItem item, XmlTextReader reader)
{
item.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty);
}
private static void ProcessTIDescription(TaskInventoryItem item, XmlTextReader reader)
{
item.Description = reader.ReadElementContentAsString("Description", String.Empty);
}
private static void ProcessTIEveryonePermissions(TaskInventoryItem item, XmlTextReader reader)
{
item.EveryonePermissions = (uint)reader.ReadElementContentAsInt("EveryonePermissions", String.Empty);
}
private static void ProcessTIFlags(TaskInventoryItem item, XmlTextReader reader)
{
item.Flags = (uint)reader.ReadElementContentAsInt("Flags", String.Empty);
}
private static void ProcessTIGroupID(TaskInventoryItem item, XmlTextReader reader)
{
item.GroupID = Util.ReadUUID(reader, "GroupID");
}
private static void ProcessTIGroupPermissions(TaskInventoryItem item, XmlTextReader reader)
{
item.GroupPermissions = (uint)reader.ReadElementContentAsInt("GroupPermissions", String.Empty);
}
private static void ProcessTIInvType(TaskInventoryItem item, XmlTextReader reader)
{
item.InvType = reader.ReadElementContentAsInt("InvType", String.Empty);
}
private static void ProcessTIItemID(TaskInventoryItem item, XmlTextReader reader)
{
item.ItemID = Util.ReadUUID(reader, "ItemID");
}
private static void ProcessTIOldItemID(TaskInventoryItem item, XmlTextReader reader)
{
item.OldItemID = Util.ReadUUID(reader, "OldItemID");
}
private static void ProcessTILastOwnerID(TaskInventoryItem item, XmlTextReader reader)
{
item.LastOwnerID = Util.ReadUUID(reader, "LastOwnerID");
}
private static void ProcessTIName(TaskInventoryItem item, XmlTextReader reader)
{
item.Name = reader.ReadElementContentAsString("Name", String.Empty);
}
private static void ProcessTINextPermissions(TaskInventoryItem item, XmlTextReader reader)
{
item.NextPermissions = (uint)reader.ReadElementContentAsInt("NextPermissions", String.Empty);
}
private static void ProcessTIOwnerID(TaskInventoryItem item, XmlTextReader reader)
{
item.OwnerID = Util.ReadUUID(reader, "OwnerID");
}
private static void ProcessTICurrentPermissions(TaskInventoryItem item, XmlTextReader reader)
{
item.CurrentPermissions = (uint)reader.ReadElementContentAsInt("CurrentPermissions", String.Empty);
}
private static void ProcessTIParentID(TaskInventoryItem item, XmlTextReader reader)
{
item.ParentID = Util.ReadUUID(reader, "ParentID");
}
private static void ProcessTIParentPartID(TaskInventoryItem item, XmlTextReader reader)
{
item.ParentPartID = Util.ReadUUID(reader, "ParentPartID");
}
private static void ProcessTIPermsGranter(TaskInventoryItem item, XmlTextReader reader)
{
item.PermsGranter = Util.ReadUUID(reader, "PermsGranter");
}
private static void ProcessTIPermsMask(TaskInventoryItem item, XmlTextReader reader)
{
item.PermsMask = reader.ReadElementContentAsInt("PermsMask", String.Empty);
}
private static void ProcessTIType(TaskInventoryItem item, XmlTextReader reader)
{
item.Type = reader.ReadElementContentAsInt("Type", String.Empty);
}
private static void ProcessTIOwnerChanged(TaskInventoryItem item, XmlTextReader reader)
{
item.OwnerChanged = Util.ReadBoolean(reader);
}
#endregion
#region ShapeXmlProcessors
private static void ProcessShpProfileCurve(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.ProfileCurve = (byte)reader.ReadElementContentAsInt("ProfileCurve", String.Empty);
}
private static void ProcessShpTextureEntry(PrimitiveBaseShape shp, XmlTextReader reader)
{
byte[] teData = Convert.FromBase64String(reader.ReadElementString("TextureEntry"));
shp.Textures = new Primitive.TextureEntry(teData, 0, teData.Length);
}
private static void ProcessShpExtraParams(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.ExtraParams = Convert.FromBase64String(reader.ReadElementString("ExtraParams"));
}
private static void ProcessShpPathBegin(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathBegin = (ushort)reader.ReadElementContentAsInt("PathBegin", String.Empty);
}
private static void ProcessShpPathCurve(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathCurve = (byte)reader.ReadElementContentAsInt("PathCurve", String.Empty);
}
private static void ProcessShpPathEnd(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathEnd = (ushort)reader.ReadElementContentAsInt("PathEnd", String.Empty);
}
private static void ProcessShpPathRadiusOffset(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathRadiusOffset = (sbyte)reader.ReadElementContentAsInt("PathRadiusOffset", String.Empty);
}
private static void ProcessShpPathRevolutions(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathRevolutions = (byte)reader.ReadElementContentAsInt("PathRevolutions", String.Empty);
}
private static void ProcessShpPathScaleX(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathScaleX = (byte)reader.ReadElementContentAsInt("PathScaleX", String.Empty);
}
private static void ProcessShpPathScaleY(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathScaleY = (byte)reader.ReadElementContentAsInt("PathScaleY", String.Empty);
}
private static void ProcessShpPathShearX(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathShearX = (byte)reader.ReadElementContentAsInt("PathShearX", String.Empty);
}
private static void ProcessShpPathShearY(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathShearY = (byte)reader.ReadElementContentAsInt("PathShearY", String.Empty);
}
private static void ProcessShpPathSkew(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathSkew = (sbyte)reader.ReadElementContentAsInt("PathSkew", String.Empty);
}
private static void ProcessShpPathTaperX(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathTaperX = (sbyte)reader.ReadElementContentAsInt("PathTaperX", String.Empty);
}
private static void ProcessShpPathTaperY(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathTaperY = (sbyte)reader.ReadElementContentAsInt("PathTaperY", String.Empty);
}
private static void ProcessShpPathTwist(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathTwist = (sbyte)reader.ReadElementContentAsInt("PathTwist", String.Empty);
}
private static void ProcessShpPathTwistBegin(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathTwistBegin = (sbyte)reader.ReadElementContentAsInt("PathTwistBegin", String.Empty);
}
private static void ProcessShpPCode(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PCode = (byte)reader.ReadElementContentAsInt("PCode", String.Empty);
}
private static void ProcessShpProfileBegin(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.ProfileBegin = (ushort)reader.ReadElementContentAsInt("ProfileBegin", String.Empty);
}
private static void ProcessShpProfileEnd(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.ProfileEnd = (ushort)reader.ReadElementContentAsInt("ProfileEnd", String.Empty);
}
private static void ProcessShpProfileHollow(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.ProfileHollow = (ushort)reader.ReadElementContentAsInt("ProfileHollow", String.Empty);
}
private static void ProcessShpScale(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.Scale = Util.ReadVector(reader, "Scale");
}
private static void ProcessShpState(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.State = (byte)reader.ReadElementContentAsInt("State", String.Empty);
}
private static void ProcessShpProfileShape(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.ProfileShape = Util.ReadEnum<ProfileShape>(reader, "ProfileShape");
}
private static void ProcessShpHollowShape(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.HollowShape = Util.ReadEnum<HollowShape>(reader, "HollowShape");
}
private static void ProcessShpSculptTexture(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.SculptTexture = Util.ReadUUID(reader, "SculptTexture");
}
private static void ProcessShpSculptType(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.SculptType = (byte)reader.ReadElementContentAsInt("SculptType", String.Empty);
}
private static void ProcessShpSculptData(PrimitiveBaseShape shp, XmlTextReader reader)
{
// m_log.DebugFormat("[SCENE OBJECT SERIALIZER]: Setting sculpt data length {0}", shp.SculptData.Length);
shp.SculptData = Convert.FromBase64String(reader.ReadElementString("SculptData"));
}
private static void ProcessShpFlexiSoftness(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiSoftness = reader.ReadElementContentAsInt("FlexiSoftness", String.Empty);
}
private static void ProcessShpFlexiTension(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiTension = reader.ReadElementContentAsFloat("FlexiTension", String.Empty);
}
private static void ProcessShpFlexiDrag(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiDrag = reader.ReadElementContentAsFloat("FlexiDrag", String.Empty);
}
private static void ProcessShpFlexiGravity(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiGravity = reader.ReadElementContentAsFloat("FlexiGravity", String.Empty);
}
private static void ProcessShpFlexiWind(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiWind = reader.ReadElementContentAsFloat("FlexiWind", String.Empty);
}
private static void ProcessShpFlexiForceX(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiForceX = reader.ReadElementContentAsFloat("FlexiForceX", String.Empty);
}
private static void ProcessShpFlexiForceY(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiForceY = reader.ReadElementContentAsFloat("FlexiForceY", String.Empty);
}
private static void ProcessShpFlexiForceZ(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiForceZ = reader.ReadElementContentAsFloat("FlexiForceZ", String.Empty);
}
private static void ProcessShpLightColorR(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightColorR = reader.ReadElementContentAsFloat("LightColorR", String.Empty);
}
private static void ProcessShpLightColorG(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightColorG = reader.ReadElementContentAsFloat("LightColorG", String.Empty);
}
private static void ProcessShpLightColorB(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightColorB = reader.ReadElementContentAsFloat("LightColorB", String.Empty);
}
private static void ProcessShpLightColorA(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightColorA = reader.ReadElementContentAsFloat("LightColorA", String.Empty);
}
private static void ProcessShpLightRadius(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightRadius = reader.ReadElementContentAsFloat("LightRadius", String.Empty);
}
private static void ProcessShpLightCutoff(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightCutoff = reader.ReadElementContentAsFloat("LightCutoff", String.Empty);
}
private static void ProcessShpLightFalloff(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightFalloff = reader.ReadElementContentAsFloat("LightFalloff", String.Empty);
}
private static void ProcessShpLightIntensity(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightIntensity = reader.ReadElementContentAsFloat("LightIntensity", String.Empty);
}
private static void ProcessShpFlexiEntry(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiEntry = Util.ReadBoolean(reader);
}
private static void ProcessShpLightEntry(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightEntry = Util.ReadBoolean(reader);
}
private static void ProcessShpSculptEntry(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.SculptEntry = Util.ReadBoolean(reader);
}
private static void ProcessShpMedia(PrimitiveBaseShape shp, XmlTextReader reader)
{
string value = reader.ReadElementContentAsString("Media", String.Empty);
shp.Media = PrimitiveBaseShape.MediaList.FromXml(value);
}
#endregion
////////// Write /////////
public static void SOGToXml2(XmlTextWriter writer, SceneObjectGroup sog, Dictionary<string, object>options)
{
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
SOPToXml2(writer, sog.RootPart, options);
writer.WriteStartElement(String.Empty, "OtherParts", String.Empty);
sog.ForEachPart(delegate(SceneObjectPart sop)
{
if (sop.UUID != sog.RootPart.UUID)
SOPToXml2(writer, sop, options);
});
writer.WriteEndElement();
if (sog.RootPart.KeyframeMotion != null)
{
Byte[] data = sog.RootPart.KeyframeMotion.Serialize();
writer.WriteStartElement(String.Empty, "KeyframeMotion", String.Empty);
writer.WriteBase64(data, 0, data.Length);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
public static void SOPToXml2(XmlTextWriter writer, SceneObjectPart sop, Dictionary<string, object> options)
{
writer.WriteStartElement("SceneObjectPart");
writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
writer.WriteElementString("AllowedDrop", sop.AllowedDrop.ToString().ToLower());
WriteUUID(writer, "CreatorID", sop.CreatorID, options);
if (sop.CreatorData != null && sop.CreatorData != string.Empty)
writer.WriteElementString("CreatorData", sop.CreatorData);
else if (options.ContainsKey("home"))
{
if (m_UserManagement == null)
m_UserManagement = sop.ParentGroup.Scene.RequestModuleInterface<IUserManagement>();
string name = m_UserManagement.GetUserName(sop.CreatorID);
writer.WriteElementString("CreatorData", (string)options["home"] + ";" + name);
}
WriteUUID(writer, "FolderID", sop.FolderID, options);
writer.WriteElementString("InventorySerial", sop.InventorySerial.ToString());
WriteTaskInventory(writer, sop.TaskInventory, options, sop.ParentGroup.Scene);
WriteUUID(writer, "UUID", sop.UUID, options);
writer.WriteElementString("LocalId", sop.LocalId.ToString());
writer.WriteElementString("Name", sop.Name);
writer.WriteElementString("Material", sop.Material.ToString());
writer.WriteElementString("PassTouches", sop.PassTouches.ToString().ToLower());
writer.WriteElementString("PassCollisions", sop.PassCollisions.ToString().ToLower());
writer.WriteElementString("RegionHandle", sop.RegionHandle.ToString());
writer.WriteElementString("ScriptAccessPin", sop.ScriptAccessPin.ToString());
WriteVector(writer, "GroupPosition", sop.GroupPosition);
WriteVector(writer, "OffsetPosition", sop.OffsetPosition);
WriteQuaternion(writer, "RotationOffset", sop.RotationOffset);
WriteVector(writer, "Velocity", sop.Velocity);
WriteVector(writer, "AngularVelocity", sop.AngularVelocity);
WriteVector(writer, "Acceleration", sop.Acceleration);
writer.WriteElementString("Description", sop.Description);
writer.WriteStartElement("Color");
writer.WriteElementString("R", sop.Color.R.ToString(Utils.EnUsCulture));
writer.WriteElementString("G", sop.Color.G.ToString(Utils.EnUsCulture));
writer.WriteElementString("B", sop.Color.B.ToString(Utils.EnUsCulture));
writer.WriteElementString("A", sop.Color.A.ToString(Utils.EnUsCulture));
writer.WriteEndElement();
writer.WriteElementString("Text", sop.Text);
writer.WriteElementString("SitName", sop.SitName);
writer.WriteElementString("TouchName", sop.TouchName);
writer.WriteElementString("LinkNum", sop.LinkNum.ToString());
writer.WriteElementString("ClickAction", sop.ClickAction.ToString());
WriteShape(writer, sop.Shape, options);
WriteVector(writer, "Scale", sop.Scale);
WriteQuaternion(writer, "SitTargetOrientation", sop.SitTargetOrientation);
WriteVector(writer, "SitTargetPosition", sop.SitTargetPosition);
WriteVector(writer, "SitTargetPositionLL", sop.SitTargetPositionLL);
WriteQuaternion(writer, "SitTargetOrientationLL", sop.SitTargetOrientationLL);
writer.WriteElementString("ParentID", sop.ParentID.ToString());
writer.WriteElementString("CreationDate", sop.CreationDate.ToString());
writer.WriteElementString("Category", sop.Category.ToString());
writer.WriteElementString("SalePrice", sop.SalePrice.ToString());
writer.WriteElementString("ObjectSaleType", sop.ObjectSaleType.ToString());
writer.WriteElementString("OwnershipCost", sop.OwnershipCost.ToString());
WriteUUID(writer, "GroupID", sop.GroupID, options);
UUID ownerID = options.ContainsKey("wipe-owners") ? UUID.Zero : sop.OwnerID;
WriteUUID(writer, "OwnerID", ownerID, options);
UUID lastOwnerID = options.ContainsKey("wipe-owners") ? UUID.Zero : sop.LastOwnerID;
WriteUUID(writer, "LastOwnerID", lastOwnerID, options);
writer.WriteElementString("BaseMask", sop.BaseMask.ToString());
writer.WriteElementString("OwnerMask", sop.OwnerMask.ToString());
writer.WriteElementString("GroupMask", sop.GroupMask.ToString());
writer.WriteElementString("EveryoneMask", sop.EveryoneMask.ToString());
writer.WriteElementString("NextOwnerMask", sop.NextOwnerMask.ToString());
WriteFlags(writer, "Flags", sop.Flags.ToString(), options);
WriteUUID(writer, "CollisionSound", sop.CollisionSound, options);
writer.WriteElementString("CollisionSoundVolume", sop.CollisionSoundVolume.ToString());
if (sop.MediaUrl != null)
writer.WriteElementString("MediaUrl", sop.MediaUrl.ToString());
if (sop.DynAttrs.CountNamespaces > 0)
{
writer.WriteStartElement("DynAttrs");
sop.DynAttrs.WriteXml(writer);
writer.WriteEndElement();
}
WriteBytes(writer, "TextureAnimation", sop.TextureAnimation);
WriteBytes(writer, "ParticleSystem", sop.ParticleSystem);
writer.WriteElementString("PayPrice0", sop.PayPrice[0].ToString());
writer.WriteElementString("PayPrice1", sop.PayPrice[1].ToString());
writer.WriteElementString("PayPrice2", sop.PayPrice[2].ToString());
writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString());
writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString());
if(sop.PhysicsShapeType != sop.DefaultPhysicsShapeType())
writer.WriteElementString("PhysicsShapeType", sop.PhysicsShapeType.ToString().ToLower());
if (sop.Density != 1000.0f)
writer.WriteElementString("Density", sop.Density.ToString().ToLower());
if (sop.Friction != 0.6f)
writer.WriteElementString("Friction", sop.Friction.ToString().ToLower());
if (sop.Restitution != 0.5f)
writer.WriteElementString("Bounce", sop.Restitution.ToString().ToLower());
if (sop.GravityModifier != 1.0f)
writer.WriteElementString("GravityModifier", sop.GravityModifier.ToString().ToLower());
writer.WriteEndElement();
}
static void WriteUUID(XmlTextWriter writer, string name, UUID id, Dictionary<string, object> options)
{
writer.WriteStartElement(name);
if (options.ContainsKey("old-guids"))
writer.WriteElementString("Guid", id.ToString());
else
writer.WriteElementString("UUID", id.ToString());
writer.WriteEndElement();
}
static void WriteVector(XmlTextWriter writer, string name, Vector3 vec)
{
writer.WriteStartElement(name);
writer.WriteElementString("X", vec.X.ToString(Utils.EnUsCulture));
writer.WriteElementString("Y", vec.Y.ToString(Utils.EnUsCulture));
writer.WriteElementString("Z", vec.Z.ToString(Utils.EnUsCulture));
writer.WriteEndElement();
}
static void WriteQuaternion(XmlTextWriter writer, string name, Quaternion quat)
{
writer.WriteStartElement(name);
writer.WriteElementString("X", quat.X.ToString(Utils.EnUsCulture));
writer.WriteElementString("Y", quat.Y.ToString(Utils.EnUsCulture));
writer.WriteElementString("Z", quat.Z.ToString(Utils.EnUsCulture));
writer.WriteElementString("W", quat.W.ToString(Utils.EnUsCulture));
writer.WriteEndElement();
}
static void WriteBytes(XmlTextWriter writer, string name, byte[] data)
{
writer.WriteStartElement(name);
byte[] d;
if (data != null)
d = data;
else
d = Utils.EmptyBytes;
writer.WriteBase64(d, 0, d.Length);
writer.WriteEndElement(); // name
}
static void WriteFlags(XmlTextWriter writer, string name, string flagsStr, Dictionary<string, object> options)
{
// Older versions of serialization can't cope with commas, so we eliminate the commas
writer.WriteElementString(name, flagsStr.Replace(",", ""));
}
public static void WriteTaskInventory(XmlTextWriter writer, TaskInventoryDictionary tinv, Dictionary<string, object> options, Scene scene)
{
if (tinv.Count > 0) // otherwise skip this
{
writer.WriteStartElement("TaskInventory");
foreach (TaskInventoryItem item in tinv.Values)
{
writer.WriteStartElement("TaskInventoryItem");
WriteUUID(writer, "AssetID", item.AssetID, options);
writer.WriteElementString("BasePermissions", item.BasePermissions.ToString());
writer.WriteElementString("CreationDate", item.CreationDate.ToString());
WriteUUID(writer, "CreatorID", item.CreatorID, options);
if (item.CreatorData != null && item.CreatorData != string.Empty)
writer.WriteElementString("CreatorData", item.CreatorData);
else if (options.ContainsKey("home"))
{
if (m_UserManagement == null)
m_UserManagement = scene.RequestModuleInterface<IUserManagement>();
string name = m_UserManagement.GetUserName(item.CreatorID);
writer.WriteElementString("CreatorData", (string)options["home"] + ";" + name);
}
writer.WriteElementString("Description", item.Description);
writer.WriteElementString("EveryonePermissions", item.EveryonePermissions.ToString());
writer.WriteElementString("Flags", item.Flags.ToString());
WriteUUID(writer, "GroupID", item.GroupID, options);
writer.WriteElementString("GroupPermissions", item.GroupPermissions.ToString());
writer.WriteElementString("InvType", item.InvType.ToString());
WriteUUID(writer, "ItemID", item.ItemID, options);
WriteUUID(writer, "OldItemID", item.OldItemID, options);
UUID lastOwnerID = options.ContainsKey("wipe-owners") ? UUID.Zero : item.LastOwnerID;
WriteUUID(writer, "LastOwnerID", lastOwnerID, options);
writer.WriteElementString("Name", item.Name);
writer.WriteElementString("NextPermissions", item.NextPermissions.ToString());
UUID ownerID = options.ContainsKey("wipe-owners") ? UUID.Zero : item.OwnerID;
WriteUUID(writer, "OwnerID", ownerID, options);
writer.WriteElementString("CurrentPermissions", item.CurrentPermissions.ToString());
WriteUUID(writer, "ParentID", item.ParentID, options);
WriteUUID(writer, "ParentPartID", item.ParentPartID, options);
WriteUUID(writer, "PermsGranter", item.PermsGranter, options);
writer.WriteElementString("PermsMask", item.PermsMask.ToString());
writer.WriteElementString("Type", item.Type.ToString());
writer.WriteElementString("OwnerChanged", item.OwnerChanged.ToString().ToLower());
writer.WriteEndElement(); // TaskInventoryItem
}
writer.WriteEndElement(); // TaskInventory
}
}
public static void WriteShape(XmlTextWriter writer, PrimitiveBaseShape shp, Dictionary<string, object> options)
{
if (shp != null)
{
writer.WriteStartElement("Shape");
writer.WriteElementString("ProfileCurve", shp.ProfileCurve.ToString());
writer.WriteStartElement("TextureEntry");
byte[] te;
if (shp.TextureEntry != null)
te = shp.TextureEntry;
else
te = Utils.EmptyBytes;
writer.WriteBase64(te, 0, te.Length);
writer.WriteEndElement(); // TextureEntry
writer.WriteStartElement("ExtraParams");
byte[] ep;
if (shp.ExtraParams != null)
ep = shp.ExtraParams;
else
ep = Utils.EmptyBytes;
writer.WriteBase64(ep, 0, ep.Length);
writer.WriteEndElement(); // ExtraParams
writer.WriteElementString("PathBegin", shp.PathBegin.ToString());
writer.WriteElementString("PathCurve", shp.PathCurve.ToString());
writer.WriteElementString("PathEnd", shp.PathEnd.ToString());
writer.WriteElementString("PathRadiusOffset", shp.PathRadiusOffset.ToString());
writer.WriteElementString("PathRevolutions", shp.PathRevolutions.ToString());
writer.WriteElementString("PathScaleX", shp.PathScaleX.ToString());
writer.WriteElementString("PathScaleY", shp.PathScaleY.ToString());
writer.WriteElementString("PathShearX", shp.PathShearX.ToString());
writer.WriteElementString("PathShearY", shp.PathShearY.ToString());
writer.WriteElementString("PathSkew", shp.PathSkew.ToString());
writer.WriteElementString("PathTaperX", shp.PathTaperX.ToString());
writer.WriteElementString("PathTaperY", shp.PathTaperY.ToString());
writer.WriteElementString("PathTwist", shp.PathTwist.ToString());
writer.WriteElementString("PathTwistBegin", shp.PathTwistBegin.ToString());
writer.WriteElementString("PCode", shp.PCode.ToString());
writer.WriteElementString("ProfileBegin", shp.ProfileBegin.ToString());
writer.WriteElementString("ProfileEnd", shp.ProfileEnd.ToString());
writer.WriteElementString("ProfileHollow", shp.ProfileHollow.ToString());
writer.WriteElementString("State", shp.State.ToString());
WriteFlags(writer, "ProfileShape", shp.ProfileShape.ToString(), options);
WriteFlags(writer, "HollowShape", shp.HollowShape.ToString(), options);
WriteUUID(writer, "SculptTexture", shp.SculptTexture, options);
writer.WriteElementString("SculptType", shp.SculptType.ToString());
writer.WriteStartElement("SculptData");
byte[] sd;
if (shp.SculptData != null)
sd = shp.SculptData;
else
sd = Utils.EmptyBytes;
writer.WriteBase64(sd, 0, sd.Length);
writer.WriteEndElement(); // SculptData
writer.WriteElementString("FlexiSoftness", shp.FlexiSoftness.ToString());
writer.WriteElementString("FlexiTension", shp.FlexiTension.ToString());
writer.WriteElementString("FlexiDrag", shp.FlexiDrag.ToString());
writer.WriteElementString("FlexiGravity", shp.FlexiGravity.ToString());
writer.WriteElementString("FlexiWind", shp.FlexiWind.ToString());
writer.WriteElementString("FlexiForceX", shp.FlexiForceX.ToString());
writer.WriteElementString("FlexiForceY", shp.FlexiForceY.ToString());
writer.WriteElementString("FlexiForceZ", shp.FlexiForceZ.ToString());
writer.WriteElementString("LightColorR", shp.LightColorR.ToString());
writer.WriteElementString("LightColorG", shp.LightColorG.ToString());
writer.WriteElementString("LightColorB", shp.LightColorB.ToString());
writer.WriteElementString("LightColorA", shp.LightColorA.ToString());
writer.WriteElementString("LightRadius", shp.LightRadius.ToString());
writer.WriteElementString("LightCutoff", shp.LightCutoff.ToString());
writer.WriteElementString("LightFalloff", shp.LightFalloff.ToString());
writer.WriteElementString("LightIntensity", shp.LightIntensity.ToString());
writer.WriteElementString("FlexiEntry", shp.FlexiEntry.ToString().ToLower());
writer.WriteElementString("LightEntry", shp.LightEntry.ToString().ToLower());
writer.WriteElementString("SculptEntry", shp.SculptEntry.ToString().ToLower());
if (shp.Media != null)
writer.WriteElementString("Media", shp.Media.ToXml());
writer.WriteEndElement(); // Shape
}
}
public static SceneObjectPart Xml2ToSOP(XmlTextReader reader)
{
SceneObjectPart obj = new SceneObjectPart();
reader.ReadStartElement("SceneObjectPart");
ExternalRepresentationUtils.ExecuteReadProcessors(
obj,
m_SOPXmlProcessors,
reader,
(o, nodeName, e)
=> m_log.DebugFormat(
"[SceneObjectSerializer]: Exception while parsing {0} in object {1} {2}: {3}{4}",
((SceneObjectPart)o).Name, ((SceneObjectPart)o).UUID, nodeName, e.Message, e.StackTrace));
reader.ReadEndElement(); // SceneObjectPart
//m_log.DebugFormat("[XXX]: parsed SOP {0} - {1}", obj.Name, obj.UUID);
return obj;
}
public static TaskInventoryDictionary ReadTaskInventory(XmlTextReader reader, string name)
{
TaskInventoryDictionary tinv = new TaskInventoryDictionary();
if (reader.IsEmptyElement)
{
reader.Read();
return tinv;
}
reader.ReadStartElement(name, String.Empty);
while (reader.Name == "TaskInventoryItem")
{
reader.ReadStartElement("TaskInventoryItem", String.Empty); // TaskInventory
TaskInventoryItem item = new TaskInventoryItem();
ExternalRepresentationUtils.ExecuteReadProcessors(
item,
m_TaskInventoryXmlProcessors,
reader);
reader.ReadEndElement(); // TaskInventoryItem
tinv.Add(item.ItemID, item);
}
if (reader.NodeType == XmlNodeType.EndElement)
reader.ReadEndElement(); // TaskInventory
return tinv;
}
/// <summary>
/// Read a shape from xml input
/// </summary>
/// <param name="reader"></param>
/// <param name="name">The name of the xml element containing the shape</param>
/// <param name="errors">a list containing the failing node names. If no failures then null.</param>
/// <returns>The shape parsed</returns>
public static PrimitiveBaseShape ReadShape(XmlTextReader reader, string name, out List<string> errorNodeNames)
{
List<string> internalErrorNodeNames = null;
PrimitiveBaseShape shape = new PrimitiveBaseShape();
if (reader.IsEmptyElement)
{
reader.Read();
errorNodeNames = null;
return shape;
}
reader.ReadStartElement(name, String.Empty); // Shape
ExternalRepresentationUtils.ExecuteReadProcessors(
shape,
m_ShapeXmlProcessors,
reader,
(o, nodeName, e)
=>
{
// m_log.DebugFormat(
// "[SceneObjectSerializer]: Exception while parsing Shape property {0}: {1}{2}",
// nodeName, e.Message, e.StackTrace);
if (internalErrorNodeNames == null)
internalErrorNodeNames = new List<string>();
internalErrorNodeNames.Add(nodeName);
}
);
reader.ReadEndElement(); // Shape
errorNodeNames = internalErrorNodeNames;
return shape;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.Sql;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Serialization.Formatters.Binary;
using MySql.Data.MySqlClient;
using Analysis.EDM;
namespace SirCachealot.Database
{
class MySqlDBlockStore : MarshalByRefObject, DBlockStore
{
private MySqlConnection mySql;
private MySqlCommand mySqlComm;
private string kConnectionString = "Server=127.0.0.1;Uid=root;Pwd=atomic1;default command timeout=300;";
public long QueryCount;
public long DBlockCount;
public UInt32[] GetUIDsByCluster(string clusterName, UInt32[] fromUIDs)
{
QueryCount++;
return GetByStringParameter("CLUSTER", clusterName, fromUIDs);
}
public UInt32[] GetUIDsByCluster(string clusterName)
{
QueryCount++;
return GetByStringParameter("CLUSTER", clusterName);
}
public UInt32[] GetUIDsByBlock(string clusterName, int clusterIndex, UInt32[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE CLUSTER = ?cluster AND CLUSTERINDEX = ?index AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?cluster", clusterName);
mySqlComm.Parameters.AddWithValue("?index", clusterIndex);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByBlock(string clusterName, int clusterIndex)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE CLUSTER = ?cluster AND CLUSTERINDEX = ?index";
mySqlComm.Parameters.AddWithValue("?cluster", clusterName);
mySqlComm.Parameters.AddWithValue("?index", clusterIndex);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByTag(string tag, UInt32[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT DISTINCT UID FROM DBLOCKS, TAGS WHERE TAGS.TAG = ?tag AND " +
"TAGS.CLUSTER = DBLOCKS.CLUSTER AND " +
"TAGS.CLUSTERINDEX = DBLOCKS.CLUSTERINDEX AND UID IN " + MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?tag", tag);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByTag(string tag)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT DISTINCT UID FROM DBLOCKS, TAGS WHERE TAGS.TAG = ?tag AND " +
"TAGS.CLUSTER = DBLOCKS.CLUSTER AND " +
"TAGS.CLUSTERINDEX = DBLOCKS.CLUSTERINDEX";
mySqlComm.Parameters.AddWithValue("?tag", tag);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByAnalysisTag(string tag, UInt32[] fromUIDs)
{
QueryCount++;
return GetByStringParameter("ATAG", tag, fromUIDs);
}
public UInt32[] GetUIDsByAnalysisTag(string tag)
{
QueryCount++;
return GetByStringParameter("ATAG", tag);
}
public UInt32[] GetUIDsByMachineState(bool eState, bool bState, bool rfState, uint[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE ESTATE = ?eState AND BSTATE = ?bState " +
"AND RFSTATE = ?rfState AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?eState", eState);
mySqlComm.Parameters.AddWithValue("?bState", bState);
mySqlComm.Parameters.AddWithValue("?rfState", rfState);
return GetUIDsFromCommand(mySqlComm);
}
public uint[] GetUIDsByMachineState(bool eState, bool bState, bool rfState)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS WHERE ESTATE = ?eState AND " +
"RFSTATE = ?rfState AND BSTATE = ?bState";
mySqlComm.Parameters.AddWithValue("?eState", eState);
mySqlComm.Parameters.AddWithValue("?bState", bState);
mySqlComm.Parameters.AddWithValue("?rfState", rfState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByEState(bool eState, UInt32[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE ESTATE = ?eState AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?eState", eState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByEState(bool eState)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS WHERE ESTATE = ?eState";
mySqlComm.Parameters.AddWithValue("?eState", eState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByBState(bool bState, UInt32[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE BSTATE = ?bState AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?bState", bState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByBState(bool bState)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS WHERE BSTATE = ?bState";
mySqlComm.Parameters.AddWithValue("?bState", bState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByRFState(bool rfState, UInt32[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE RFSTATE = ?rfState AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?rfState", rfState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByRFState(bool rfState)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS WHERE RFSTATE = ?rfState";
mySqlComm.Parameters.AddWithValue("?rfState", rfState);
return GetUIDsFromCommand(mySqlComm);
}
public uint[] GetUIDsByDateRange(DateTime start, DateTime end, uint[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE BLOCKTIME >= ?start AND BLOCKTIME < ?end AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?start", start);
mySqlComm.Parameters.AddWithValue("?end", end);
return GetUIDsFromCommand(mySqlComm);
}
public uint[] GetUIDsByDateRange(DateTime start, DateTime end)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS WHERE BLOCKTIME >= ?start AND BLOCKTIME < ?end";
mySqlComm.Parameters.AddWithValue("?start", start);
mySqlComm.Parameters.AddWithValue("?end", end);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByVoltageRange(double low, double high, UInt32[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE EPLUS >= ?low AND EPLUS < ?high AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?low", low);
mySqlComm.Parameters.AddWithValue("?high", high);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByVoltageRange(double low, double high)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE EPLUS >= ?low AND EPLUS < ?high";
mySqlComm.Parameters.AddWithValue("?low", low);
mySqlComm.Parameters.AddWithValue("?high", high);
return GetUIDsFromCommand(mySqlComm);
}
public uint[] GetUIDsByPredicate(PredicateFunction func, uint[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS WHERE UID IN " + MakeSQLArrayString(fromUIDs);
UInt32[] uids = GetUIDsFromCommand(mySqlComm);
List<UInt32> matchedUIDs = new List<UInt32>();
foreach (UInt32 uid in uids)
{
DemodulatedBlock db = GetDBlock(uid);
if (func(db)) matchedUIDs.Add(uid);
}
return matchedUIDs.ToArray();
}
public DemodulatedBlock GetDBlock(uint uid)
{
DBlockCount++;
byte[] dbb;
MySqlDataReader rd = executeReader("SELECT DBDAT FROM DBLOCKDATA WHERE UID = " + uid);
DemodulatedBlock db;
if (rd.Read())
{
dbb = (byte[])rd["DBDAT"];
db = deserializeDBlockFromByteArray(dbb);
rd.Close();
}
else
{
rd.Close();
throw new BlockNotFoundException();
}
return db;
}
// this method temporarily is locked so that only one thread at a time can execute.
// I need to fix a db problem concerning the UIDs before unlocking it.
// Hopefully it won't hurt the performance too badly.
private object dbAddLock = new object();
public UInt32 AddDBlock(DemodulatedBlock db)
{
lock (dbAddLock)
{
mySqlComm = mySql.CreateCommand();
// extract the data that we're going to put in the sql database
string clusterName = db.Config.Settings["cluster"] as string;
int clusterIndex = (int)db.Config.Settings["clusterIndex"];
string aTag = db.DemodulationConfig.AnalysisTag;
bool eState = (bool)db.Config.Settings["eState"];
bool bState = (bool)db.Config.Settings["bState"];
bool rfState = (bool)db.Config.Settings["rfState"];
DateTime timeStamp = db.TimeStamp;
double ePlus = (double)db.Config.Settings["ePlus"];
double eMinus = (double)db.Config.Settings["eMinus"];
byte[] dBlockBytes = serializeDBlockAsByteArray(db);
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"INSERT INTO DBLOCKS " +
"VALUES(?uint, ?cluster, ?clusterIndex, ?aTag, ?eState, ?bState, ?rfState, ?ts, " +
"?ePlus, ?eMinus);";
// the uid column is defined auto_increment
mySqlComm.Parameters.AddWithValue("?uint", null);
mySqlComm.Parameters.AddWithValue("?cluster", clusterName);
mySqlComm.Parameters.AddWithValue("?clusterIndex", clusterIndex);
mySqlComm.Parameters.AddWithValue("?aTag", aTag);
mySqlComm.Parameters.AddWithValue("?eState", eState);
mySqlComm.Parameters.AddWithValue("?bState", bState);
mySqlComm.Parameters.AddWithValue("?rfState", rfState);
mySqlComm.Parameters.AddWithValue("?ts", timeStamp);
mySqlComm.Parameters.AddWithValue("?ePlus", ePlus);
mySqlComm.Parameters.AddWithValue("?eMinus", eMinus);
mySqlComm.ExecuteNonQuery();
mySqlComm.Parameters.Clear();
UInt32 uid = (UInt32)mySqlComm.LastInsertedId;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"INSERT INTO DBLOCKDATA VALUES(?uint, ?dblock);";
mySqlComm.Parameters.AddWithValue("?uint", uid);
mySqlComm.Parameters.AddWithValue("?dblock", dBlockBytes);
mySqlComm.ExecuteNonQuery();
mySqlComm.Parameters.Clear();
return uid;
}
}
public void RemoveDBlock(UInt32 uid)
{
executeNonQuery("DELETE FROM DBLOCKS WHERE UID = " + uid);
executeNonQuery("DELETE FROM DBLOCKDATA WHERE UID = " + uid);
}
public UInt32[] GetAllUIDs()
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS";
return GetUIDsFromCommand(mySqlComm);
}
public void AddTagToBlock(string clusterName, int blockIndex, string tag)
{
QueryCount++;
executeNonQuery("INSERT INTO TAGS VALUES('" + clusterName + "', " + blockIndex + ", '" + tag + "')");
}
public void RemoveTagFromBlock(string clusterName, int blockIndex, string tag)
{
QueryCount++;
executeNonQuery(
"DELETE FROM TAGS WHERE CLUSTER = '" + clusterName + "' AND CLUSTERINDEX = " + blockIndex +
" AND TAG = '" + tag + "'"
);
}
public UInt32[] GetTaggedIndicesForCluster(string clusterName, string tag)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT DISTINCT TAGS.CLUSTERINDEX FROM TAGS, DBLOCKS WHERE TAGS.CLUSTER = ?cluster AND " +
"TAGS.TAG = ?tag AND TAGS.CLUSTER = DBLOCKS.CLUSTER AND TAGS.CLUSTERINDEX = " +
"DBLOCKS.CLUSTERINDEX";
mySqlComm.Parameters.AddWithValue("?cluster", clusterName);
mySqlComm.Parameters.AddWithValue("?tag", tag);
return GetUIntsFromCommand(mySqlComm, "CLUSTERINDEX");
}
private string MakeSQLArrayString(UInt32[] uids)
{
StringBuilder sqlArray = new StringBuilder("(");
for (int i = 0; i < uids.Length - 1; i++)
{
sqlArray.Append(uids[i]);
sqlArray.Append(", ");
}
sqlArray.Append(uids[uids.Length - 1]);
sqlArray.Append(")");
return sqlArray.ToString();
}
private UInt32[] GetByStringParameter(string parameter, string val)
{
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS WHERE " + parameter + " = ?val";
mySqlComm.Parameters.AddWithValue("?val", val);
return GetUIDsFromCommand(mySqlComm);
}
private UInt32[] GetByStringParameter(string parameter, string val, UInt32[] fromUIDs)
{
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE " + parameter +
" = ?val AND UID IN " + MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?val", val);
return GetUIDsFromCommand(mySqlComm);
}
private UInt32[] GetUIDsFromCommand(MySqlCommand cm)
{
return GetUIntsFromCommand(cm, "UID");
}
private UInt32[] GetUIntsFromCommand(MySqlCommand cm, string column)
{
MySqlDataReader rd = cm.ExecuteReader();
List<UInt32> uids = new List<UInt32>();
while (rd.Read()) uids.Add((UInt32)rd[column]);
rd.Close();
return uids.ToArray();
}
internal void Start()
{
//TODO: support multiple DBs
// This creates a shared connection that is used for all query methods. As a result, the query
// methods are probably not currently thread-safe (maybe, need to check).
mySql = new MySqlConnection(kConnectionString);
mySql.Open();
mySqlComm = mySql.CreateCommand();
}
internal List<string> GetDatabaseList()
{
MySqlDataReader rd = executeReader("SHOW DATABASES;");
List<string> databases = new List<string>();
while (rd.Read()) databases.Add(rd.GetString(0));
rd.Close();
return databases;
}
internal void Connect(string dbName)
{
executeNonQuery("USE " + dbName + ";");
}
internal void CreateDatabase(string dbName)
{
executeNonQuery("CREATE DATABASE " + dbName + ";");
Connect(dbName);
executeNonQuery(
"CREATE TABLE DBLOCKS (UID INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
"CLUSTER VARCHAR(30), CLUSTERINDEX INT UNSIGNED, " +
"ATAG VARCHAR(30), ESTATE BOOL, BSTATE BOOL, RFSTATE BOOL, BLOCKTIME DATETIME, " +
"EPLUS DOUBLE, EMINUS DOUBLE, PRIMARY KEY (UID))"
);
executeNonQuery(
"CREATE TABLE TAGS (CLUSTER VARCHAR(30), CLUSTERINDEX INT UNSIGNED, TAG VARCHAR(30))"
);
executeNonQuery(
"CREATE TABLE DBLOCKDATA (UID INT UNSIGNED NOT NULL, DBDAT MEDIUMBLOB, PRIMARY KEY (UID))"
);
}
internal void Stop()
{
mySql.Close();
}
private int executeNonQuery(string command)
{
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = command;
return mySqlComm.ExecuteNonQuery();
}
private MySqlDataReader executeReader(string command)
{
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = command;
return mySqlComm.ExecuteReader();
}
private byte[] serializeDBlockAsByteArray(DemodulatedBlock db)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, db);
byte[] buffer = new Byte[ms.Length];
ms.Seek(0, SeekOrigin.Begin);
ms.Read(buffer, 0, (int)ms.Length);
ms.Close();
return buffer;
}
private DemodulatedBlock deserializeDBlockFromByteArray(byte[] ba)
{
MemoryStream ms = new MemoryStream(ba);
BinaryFormatter bf = new BinaryFormatter();
return (DemodulatedBlock)bf.Deserialize(ms);
}
}
}
| |
///
/// Author: Ahmed Lacevic
/// Date: 12/1/2007
/// Desc: This class represents a DBF file. You can create, open, update and save DBF files using this class and supporting classes.
/// Also, this class supports reading/writing from/to an internet forward only type of stream!
///
/// Revision History:
/// -----------------------------------
/// Author:
/// Date:
/// Desc:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace SocialExplorer.IO.FastDBF
{
/// <summary>
/// This class represents a DBF file. You can create new, open, update and save DBF files using this class and supporting classes.
/// Also, this class supports reading/writing from/to an internet forward only type of stream!
/// </summary>
/// <remarks>
/// TODO: add end of file byte '0x1A' !!!
/// We don't relly on that byte at all, and everything works with or without that byte, but it should be there by spec.
/// </remarks>
public class DbfFile
{
/// <summary>
/// Helps read/write dbf file header information.
/// </summary>
protected DbfHeader _header;
/// <summary>
/// flag that indicates whether the header was written or not...
/// </summary>
protected bool _headerWritten = false;
/// <summary>
/// Streams to read and write to the DBF file.
/// </summary>
protected Stream _dbfFile = null;
protected BinaryReader _dbfFileReader = null;
protected BinaryWriter _dbfFileWriter = null;
/// <summary>
/// By default use windows 1252 code page encoding.
/// </summary>
private Encoding encoding = Encoding.GetEncoding(1252);
/// <summary>
/// File that was opened, if one was opened at all.
/// </summary>
protected string _fileName = "";
/// <summary>
/// Number of records read using ReadNext() methods only. This applies only when we are using a forward-only stream.
/// mRecordsReadCount is used to keep track of record index. With a seek enabled stream,
/// we can always calculate index using stream position.
/// </summary>
protected long _recordsReadCount = 0;
/// <summary>
/// keep these values handy so we don't call functions on every read.
/// </summary>
protected bool _isForwardOnly = false;
protected bool _isReadOnly = false;
[Obsolete]
public DbfFile()
: this(Encoding.GetEncoding(1252))
{
}
public DbfFile(Encoding encoding)
{
this.encoding = encoding;
_header = new DbfHeader(encoding);
}
/// <summary>
/// Open a DBF from a FileStream. This can be a file or an internet connection stream. Make sure that it is positioned at start of DBF file.
/// Reading a DBF over the internet we can not determine size of the file, so we support HasMore(), ReadNext() interface.
/// RecordCount information in header can not be trusted always, since some packages store 0 there.
/// </summary>
/// <param name="ofs"></param>
public void Open(Stream ofs)
{
if (_dbfFile != null)
Close();
_dbfFile = ofs;
_dbfFileReader = null;
_dbfFileWriter = null;
if (_dbfFile.CanRead)
_dbfFileReader = new BinaryReader(_dbfFile, encoding);
if (_dbfFile.CanWrite)
_dbfFileWriter = new BinaryWriter(_dbfFile, encoding);
//reset position
_recordsReadCount = 0;
//assume header is not written
_headerWritten = false;
//read the header
if (ofs.CanRead)
{
//try to read the header...
try
{
_header.Read(_dbfFileReader);
_headerWritten = true;
}
catch (EndOfStreamException)
{
//could not read header, file is empty
_header = new DbfHeader(encoding);
_headerWritten = false;
}
}
if (_dbfFile != null)
{
_isReadOnly = !_dbfFile.CanWrite;
_isForwardOnly = !_dbfFile.CanSeek;
}
}
/// <summary>
/// Open a DBF file or create a new one.
/// </summary>
/// <param name="sPath">Full path to the file.</param>
/// <param name="mode"></param>
public void Open(string sPath, FileMode mode, FileAccess access, FileShare share)
{
_fileName = sPath;
Open(File.Open(sPath, mode, access, share));
}
/// <summary>
/// Open a DBF file or create a new one.
/// </summary>
/// <param name="sPath">Full path to the file.</param>
/// <param name="mode"></param>
public void Open(string sPath, FileMode mode, FileAccess access)
{
_fileName = sPath;
Open(File.Open(sPath, mode, access));
}
/// <summary>
/// Open a DBF file or create a new one.
/// </summary>
/// <param name="sPath">Full path to the file.</param>
/// <param name="mode"></param>
public void Open(string sPath, FileMode mode)
{
_fileName = sPath;
Open(File.Open(sPath, mode));
}
/// <summary>
/// Creates a new DBF 4 file. Overwrites if file exists! Use Open() function for more options.
/// </summary>
/// <param name="sPath"></param>
public void Create(string sPath)
{
Open(sPath, FileMode.Create, FileAccess.ReadWrite);
_headerWritten = false;
}
/// <summary>
/// Update header info, flush buffers and close streams. You should always call this method when you are done with a DBF file.
/// </summary>
public void Close()
{
//try to update the header if it has changed
//------------------------------------------
if (_header.IsDirty)
WriteHeader();
//Empty header...
//--------------------------------
_header = new DbfHeader(encoding);
_headerWritten = false;
//reset current record index
//--------------------------------
_recordsReadCount = 0;
//Close streams...
//--------------------------------
if (_dbfFileWriter != null)
{
_dbfFileWriter.Flush();
_dbfFileWriter.Close();
}
if (_dbfFileReader != null)
_dbfFileReader.Close();
if (_dbfFile != null)
{
_dbfFile.Close();
_dbfFile.Dispose();
}
//set streams to null
//--------------------------------
_dbfFileReader = null;
_dbfFileWriter = null;
_dbfFile = null;
_fileName = "";
}
/// <summary>
/// Returns true if we can not write to the DBF file stream.
/// </summary>
public bool IsReadOnly
{
get
{
return _isReadOnly;
/*
if (mDbfFile != null)
return !mDbfFile.CanWrite;
return true;
*/
}
}
/// <summary>
/// Returns true if we can not seek to different locations within the file, such as internet connections.
/// </summary>
public bool IsForwardOnly
{
get
{
return _isForwardOnly;
/*
if(mDbfFile!=null)
return !mDbfFile.CanSeek;
return false;
*/
}
}
/// <summary>
/// Returns the name of the filestream.
/// </summary>
public string FileName
{
get
{
return _fileName;
}
}
/// <summary>
/// Read next record and fill data into parameter oFillRecord. Returns true if a record was read, otherwise false.
/// </summary>
/// <param name="oFillRecord"></param>
/// <returns></returns>
public bool ReadNext(DbfRecord oFillRecord)
{
//check if we can fill this record with data. it must match record size specified by header and number of columns.
//we are not checking whether it comes from another DBF file or not, we just need the same structure. Allow flexibility but be safe.
if (oFillRecord.Header != _header && (oFillRecord.Header.ColumnCount != _header.ColumnCount || oFillRecord.Header.RecordLength != _header.RecordLength))
throw new Exception("Record parameter does not have the same size and number of columns as the " +
"header specifies, so we are unable to read a record into oFillRecord. " +
"This is a programming error, have you mixed up DBF file objects?");
//DBF file reader can be null if stream is not readable...
if (_dbfFileReader == null)
throw new Exception("Read stream is null, either you have opened a stream that can not be " +
"read from (a write-only stream) or you have not opened a stream at all.");
//read next record...
bool bRead = oFillRecord.Read(_dbfFile);
if (bRead)
{
if (_isForwardOnly)
{
//zero based index! set before incrementing count.
oFillRecord.RecordIndex = _recordsReadCount;
_recordsReadCount++;
}
else
oFillRecord.RecordIndex = ((int)((_dbfFile.Position - _header.HeaderLength) / _header.RecordLength)) - 1;
}
return bRead;
}
/// <summary>
/// Tries to read a record and returns a new record object or null if nothing was read.
/// </summary>
/// <returns></returns>
public DbfRecord ReadNext()
{
//create a new record and fill it.
DbfRecord orec = new DbfRecord(_header);
return ReadNext(orec) ? orec : null;
}
/// <summary>
/// Reads a record specified by index into oFillRecord object. You can use this method
/// to read in and process records without creating and discarding record objects.
/// Note that you should check that your stream is not forward-only! If you have a forward only stream, use ReadNext() functions.
/// </summary>
/// <param name="index">Zero based record index.</param>
/// <param name="oFillRecord">Record object to fill, must have same size and number of fields as thid DBF file header!</param>
/// <remarks>
/// <returns>True if read a record was read, otherwise false. If you read end of file false will be returned and oFillRecord will NOT be modified!</returns>
/// The parameter record (oFillRecord) must match record size specified by the header and number of columns as well.
/// It does not have to come from the same header, but it must match the structure. We are not going as far as to check size of each field.
/// The idea is to be flexible but safe. It's a fine balance, these two are almost always at odds.
/// </remarks>
public bool Read(long index, DbfRecord oFillRecord)
{
//check if we can fill this record with data. it must match record size specified by header and number of columns.
//we are not checking whether it comes from another DBF file or not, we just need the same structure. Allow flexibility but be safe.
if (oFillRecord.Header != _header && (oFillRecord.Header.ColumnCount != _header.ColumnCount || oFillRecord.Header.RecordLength != _header.RecordLength))
throw new Exception("Record parameter does not have the same size and number of columns as the " +
"header specifies, so we are unable to read a record into oFillRecord. " +
"This is a programming error, have you mixed up DBF file objects?");
//DBF file reader can be null if stream is not readable...
if (_dbfFileReader == null)
throw new Exception("ReadStream is null, either you have opened a stream that can not be " +
"read from (a write-only stream) or you have not opened a stream at all.");
//move to the specified record, note that an exception will be thrown is stream is not seekable!
//This is ok, since we provide a function to check whether the stream is seekable.
long nSeekToPosition = _header.HeaderLength + (index * _header.RecordLength);
//check whether requested record exists. Subtract 1 from file length (there is a terminating character 1A at the end of the file)
//so if we hit end of file, there are no more records, so return false;
if (index < 0 || _dbfFile.Length - 1 <= nSeekToPosition)
return false;
//move to record and read
_dbfFile.Seek(nSeekToPosition, SeekOrigin.Begin);
//read the record
bool bRead = oFillRecord.Read(_dbfFile);
if (bRead)
oFillRecord.RecordIndex = index;
return bRead;
}
public bool ReadValue(int rowIndex, int columnIndex, out string result)
{
result = String.Empty;
DbfColumn ocol = _header[columnIndex];
//move to the specified record, note that an exception will be thrown is stream is not seekable!
//This is ok, since we provide a function to check whether the stream is seekable.
long nSeekToPosition = _header.HeaderLength + (rowIndex * _header.RecordLength) + ocol.DataAddress;
//check whether requested record exists. Subtract 1 from file length (there is a terminating character 1A at the end of the file)
//so if we hit end of file, there are no more records, so return false;
if (rowIndex < 0 || _dbfFile.Length - 1 <= nSeekToPosition)
return false;
//move to position and read
_dbfFile.Seek(nSeekToPosition, SeekOrigin.Begin);
//read the value
byte[] data = new byte[ocol.Length];
_dbfFile.Read(data, 0, ocol.Length);
result = new string(encoding.GetChars(data, 0, ocol.Length));
return true;
}
/// <summary>
/// Reads a record specified by index. This method requires the stream to be able to seek to position.
/// If you are using a http stream, or a stream that can not stream, use ReadNext() methods to read in all records.
/// </summary>
/// <param name="index">Zero based index.</param>
/// <returns>Null if record can not be read, otherwise returns a new record.</returns>
public DbfRecord Read(long index)
{
//create a new record and fill it.
DbfRecord orec = new DbfRecord(_header);
return Read(index, orec) ? orec : null;
}
/// <summary>
/// Write a record to file. If RecordIndex is present, record will be updated, otherwise a new record will be written.
/// Header will be output first if this is the first record being writen to file.
/// This method does not require stream seek capability to add a new record.
/// </summary>
/// <param name="orec"></param>
public void Write(DbfRecord orec)
{
//if header was never written, write it first, then output the record
if (!_headerWritten)
WriteHeader();
//if this is a new record (RecordIndex should be -1 in that case)
if (orec.RecordIndex < 0)
{
if (_dbfFileWriter.BaseStream.CanSeek)
{
//calculate number of records in file. do not rely on header's RecordCount property since client can change that value.
//also note that some DBF files do not have ending 0x1A byte, so we subtract 1 and round off
//instead of just cast since cast would just drop decimals.
int nNumRecords = (int)Math.Round(((double)(_dbfFile.Length - _header.HeaderLength - 1) / _header.RecordLength));
if (nNumRecords < 0)
nNumRecords = 0;
orec.RecordIndex = nNumRecords;
Update(orec);
_header.RecordCount++;
}
else
{
//we can not position this stream, just write out the new record.
orec.Write(_dbfFile);
_header.RecordCount++;
}
}
else
Update(orec);
}
public void Write(DbfRecord orec, bool bClearRecordAfterWrite)
{
Write(orec);
if (bClearRecordAfterWrite)
orec.Clear();
}
/// <summary>
/// Update a record. RecordIndex (zero based index) must be more than -1, otherwise an exception is thrown.
/// You can also use Write method which updates a record if it has RecordIndex or adds a new one if RecordIndex == -1.
/// RecordIndex is set automatically when you call any Read() methods on this class.
/// </summary>
/// <param name="orec"></param>
public void Update(DbfRecord orec)
{
//if header was never written, write it first, then output the record
if (!_headerWritten)
WriteHeader();
//Check if record has an index
if (orec.RecordIndex < 0)
throw new Exception("RecordIndex is not set, unable to update record. Set RecordIndex or call Write() method to add a new record to file.");
//Check if this record matches record size specified by header and number of columns.
//Client can pass a record from another DBF that is incompatible with this one and that would corrupt the file.
if (orec.Header != _header && (orec.Header.ColumnCount != _header.ColumnCount || orec.Header.RecordLength != _header.RecordLength))
throw new Exception("Record parameter does not have the same size and number of columns as the " +
"header specifies. Writing this record would corrupt the DBF file. " +
"This is a programming error, have you mixed up DBF file objects?");
//DBF file writer can be null if stream is not writable to...
if (_dbfFileWriter == null)
throw new Exception("Write stream is null. Either you have opened a stream that can not be " +
"writen to (a read-only stream) or you have not opened a stream at all.");
//move to the specified record, note that an exception will be thrown if stream is not seekable!
//This is ok, since we provide a function to check whether the stream is seekable.
long nSeekToPosition = (long)_header.HeaderLength + (long)((long)orec.RecordIndex * (long)_header.RecordLength);
//check whether we can seek to this position. Subtract 1 from file length (there is a terminating character 1A at the end of the file)
//so if we hit end of file, there are no more records, so return false;
if (_dbfFile.Length < nSeekToPosition)
throw new Exception("Invalid record position. Unable to save record.");
//move to record start
_dbfFile.Seek(nSeekToPosition, SeekOrigin.Begin);
//write
orec.Write(_dbfFile);
}
/// <summary>
/// Save header to file. Normally, you do not have to call this method, header is saved
/// automatically and updated when you close the file (if it changed).
/// </summary>
public bool WriteHeader()
{
//update header if possible
//--------------------------------
if (_dbfFileWriter != null)
{
if (_dbfFileWriter.BaseStream.CanSeek)
{
_dbfFileWriter.Seek(0, SeekOrigin.Begin);
_header.Write(_dbfFileWriter);
_headerWritten = true;
return true;
}
else
{
//if stream can not seek, then just write it out and that's it.
if (!_headerWritten)
_header.Write(_dbfFileWriter);
_headerWritten = true;
}
}
return false;
}
/// <summary>
/// Access DBF header with information on columns. Use this object for faster access to header.
/// Remove one layer of function calls by saving header reference and using it directly to access columns.
/// </summary>
public DbfHeader Header
{
get
{
return _header;
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("Hooks Test", "Oxide Team", 0.1)]
public class HooksTest : RustPlugin
{
int hookCount = 0;
int hooksVerified;
Dictionary<string, bool> hooksRemaining = new Dictionary<string, bool>();
public void HookCalled(string name)
{
if (!hooksRemaining.ContainsKey(name)) return;
hookCount--;
hooksVerified++;
PrintWarning("{0} is working. {1} hooks verified!", name, hooksVerified);
hooksRemaining.Remove(name);
if (hookCount == 0)
PrintWarning("All hooks verified!");
else
PrintWarning("{0} hooks remaining: " + string.Join(", ", hooksRemaining.Keys.ToArray()), hookCount);
}
private void Init()
{
hookCount = hooks.Count;
hooksRemaining = hooks.Keys.ToDictionary(k => k, k => true);
PrintWarning("{0} hook to test!", hookCount);
HookCalled("Init");
}
public void Loaded()
{
}
protected override void LoadDefaultConfig()
{
HookCalled("LoadDefaultConfig");
}
private void Unloaded()
{
HookCalled("Unloaded");
// TODO: Unload plugin and store state in config
}
private void ModifyTags(string oldtags)
{
HookCalled("ModifyTags");
// TODO: Modify tags, either remove or add
}
private void BuildServerTags(IList<string> tags)
{
HookCalled("BuildServerTags");
// TODO: Print new tags
}
private void OnFrame()
{
HookCalled("OnFrame");
}
private void OnTick()
{
HookCalled("OnTick");
}
private void OnTerrainInitialized()
{
HookCalled("OnTerrainInitialized");
}
private void OnServerInitialized()
{
HookCalled("OnServerInitialized");
}
private void OnServerSave()
{
HookCalled("OnServerSave");
}
private void OnServerShutdown()
{
HookCalled("OnServerShutdown");
}
private void OnRunCommand(ConsoleSystem.Arg arg)
{
HookCalled("OnRunCommand");
// TODO: Run test command
// TODO: Print command messages
}
private void OnUserApprove(Network.Connection connection)
{
HookCalled("OnUserApprove");
}
private void CanClientLogin(Network.Connection connection)
{
HookCalled("CanClientLogin");
}
private void OnPlayerConnected(Network.Message packet)
{
HookCalled("OnPlayerConnected");
// TODO: Print player connected
}
private void OnPlayerDisconnected(BasePlayer player)
{
HookCalled("OnPlayerDisconnected");
// TODO: Print player disconnected
}
private void OnFindSpawnPoint()
{
HookCalled("OnFindSpawnPoint");
// TODO: Print spawn point
}
private void OnPlayerRespawned(BasePlayer player)
{
HookCalled("OnPlayerRespawned");
// TODO: Print respawn location
// TODO: Print start metabolism values
// TODO: Give admin items for testing
}
private void OnRunPlayerMetabolism(PlayerMetabolism metabolism)
{
HookCalled("OnRunPlayerMetabolism");
// TODO: Print new metabolism values
}
private void OnItemCraft(ItemCraftTask item)
{
HookCalled("OnItemCraft");
// TODO: Print item crafting
}
private void OnItemDeployed(Deployer deployer, BaseEntity deployedEntity)
{
HookCalled("OnItemDeployed");
// TODO: Print item deployed
}
private void OnItemAddedToContainer(ItemContainer container, Item item)
{
HookCalled("OnItemAddedToContainer");
// TODO: Print item added
}
private void OnItemRemovedFromContainer(ItemContainer container, Item item)
{
HookCalled("OnItemRemovedToContainer");
// TODO: Print item removed
}
private void OnConsumableUse(Item item)
{
HookCalled("OnConsumableUse");
// TODO: Print consumable item used
}
private void OnConsumeFuel(BaseOven oven, Item fuel, ItemModBurnable burnable)
{
HookCalled("OnConsumeFuel");
// TODO: Print fuel consumed
}
private void OnGather(ResourceDispenser dispenser, BaseEntity entity, Item item)
{
HookCalled("OnGather");
// TODO: Print item to be gathered
}
private void CanUseDoor(BasePlayer player, BaseLock door)
//private void CanUseDoor(BasePlayer player, CodeLock doorCode)
//private void CanUseDoor(BasePlayer player, KeyLock doorKey)
{
HookCalled("CanUseDoor");
}
private void OnEntityTakeDamage(MonoBehaviour entity, HitInfo hitInfo)
{
HookCalled("OnEntityTakeDamage");
}
private void OnEntityBuilt(Planner planner, GameObject gameObject)
{
HookCalled("OnEntityBuilt");
}
private void OnEntityDeath(MonoBehaviour entity, HitInfo hitInfo)
{
HookCalled("OnEntityDeath");
// TODO: Print player died
// TODO: Automatically respawn admin after X time
}
private void OnEntityEnter(TriggerBase triggerBase, BaseEntity entity)
{
HookCalled("OnEntityEnter");
}
private void OnEntityLeave(TriggerBase triggerBase, BaseEntity entity)
{
HookCalled("OnEntityLeave");
}
private void OnEntitySpawned(MonoBehaviour entity)
{
HookCalled("OnEntitySpawned");
}
private void OnPlayerInit(BasePlayer player)
{
HookCalled("OnPlayerInit");
// TODO: Force admin to spawn/wakeup
}
private void OnPlayerChat(ConsoleSystem.Arg arg)
{
HookCalled("OnPlayerChat");
}
private void OnPlayerLoot(PlayerLoot lootInventory, BaseEntity targetEntity)
//private void OnPlayerLoot(PlayerLoot lootInventory, BasePlayer targetPlayer)
//private void OnPlayerLoot(PlayerLoot lootInventory, Item targetItem)
{
HookCalled("OnPlayerLoot");
}
private void OnPlayerInput(BasePlayer player, InputState input)
{
HookCalled("OnPlayerInput");
}
private void OnBuildingBlockUpgrade(BuildingBlock block, BasePlayer player, BuildingGrade.Enum grade)
{
HookCalled("OnBuildingBlockUpgrade");
}
private void OnBuildingBlockRotate(BuildingBlock block, BasePlayer player)
{
HookCalled("OnBuildingBlockRotate");
}
private void OnBuildingBlockDemolish(BuildingBlock block, BasePlayer player)
{
HookCalled("OnBuildingBlockDemolish");
}
}
}
| |
/*
* Copyright 2020 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.
*/
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Threading;
using Xunit;
[CollectionDefinition(nameof(KmsFixture))]
public class KmsFixture : IDisposable, ICollectionFixture<KmsFixture>
{
public string ProjectId { get; }
public ProjectName ProjectName { get; }
public string LocationId { get; }
public LocationName LocationName { get; }
public string KeyRingId { get; }
public KeyRingName KeyRingName { get; }
public string AsymmetricDecryptKeyId { get; }
public CryptoKeyName AsymmetricDecryptKeyName { get; }
public string AsymmetricSignEcKeyId { get; }
public CryptoKeyName AsymmetricSignEcKeyName { get; }
public string AsymmetricSignRsaKeyId { get; }
public CryptoKeyName AsymmetricSignRsaKeyName { get; }
public string HsmKeyId { get; }
public CryptoKeyName HsmKeyName { get; }
public string MacKeyId { get; }
public CryptoKeyName MacKeyName { get; }
public string SymmetricKeyId { get; }
public CryptoKeyName SymmetricKeyName { get; }
public KmsFixture()
{
ProjectId = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");
if (string.IsNullOrEmpty(ProjectId))
{
throw new Exception("missing GOOGLE_PROJECT_ID");
}
ProjectName = new ProjectName(ProjectId);
LocationId = "us-east1";
LocationName = new LocationName(ProjectId, LocationId);
KeyRingId = RandomId();
KeyRingName = new KeyRingName(ProjectId, LocationId, KeyRingId);
CreateKeyRing(KeyRingId);
AsymmetricDecryptKeyId = RandomId();
AsymmetricDecryptKeyName = new CryptoKeyName(ProjectId, LocationId, KeyRingId, AsymmetricDecryptKeyId);
CreateAsymmetricDecryptKey(AsymmetricDecryptKeyId);
AsymmetricSignEcKeyId = RandomId();
AsymmetricSignEcKeyName = new CryptoKeyName(ProjectId, LocationId, KeyRingId, AsymmetricSignEcKeyId);
CreateAsymmetricSignEcKey(AsymmetricSignEcKeyId);
AsymmetricSignRsaKeyId = RandomId();
AsymmetricSignRsaKeyName = new CryptoKeyName(ProjectId, LocationId, KeyRingId, AsymmetricSignRsaKeyId);
CreateAsymmetricSignRsaKey(AsymmetricSignRsaKeyId);
HsmKeyId = RandomId();
HsmKeyName = new CryptoKeyName(ProjectId, LocationId, KeyRingId, HsmKeyId);
CreateHsmKey(HsmKeyId);
MacKeyId = RandomId();
MacKeyName = new CryptoKeyName(ProjectId, LocationId, KeyRingId, MacKeyId);
CreateMacKey(MacKeyId);
SymmetricKeyId = RandomId();
SymmetricKeyName = new CryptoKeyName(ProjectId, LocationId, KeyRingId, SymmetricKeyId);
CreateSymmetricKey(SymmetricKeyId);
}
public void Dispose()
{
DisposeKeyRing(KeyRingId);
}
public void DisposeKeyRing(string keyRingId)
{
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
var listKeysRequest = new ListCryptoKeysRequest
{
ParentAsKeyRingName = new KeyRingName(ProjectId, LocationId, keyRingId),
};
foreach (var key in client.ListCryptoKeys(listKeysRequest))
{
if (key.RotationPeriod != null || key.NextRotationTime != null)
{
client.UpdateCryptoKey(new UpdateCryptoKeyRequest
{
CryptoKey = new CryptoKey
{
CryptoKeyName = key.CryptoKeyName,
RotationPeriod = null,
NextRotationTime = null,
},
UpdateMask = new FieldMask
{
Paths = { "rotation_period", "next_rotation_time" }
},
});
}
var listKeyVersionsRequest = new ListCryptoKeyVersionsRequest
{
ParentAsCryptoKeyName = key.CryptoKeyName,
Filter = "state != DESTROYED AND state != DESTROY_SCHEDULED",
};
foreach (var keyVersion in client.ListCryptoKeyVersions(listKeyVersionsRequest))
{
client.DestroyCryptoKeyVersion(new DestroyCryptoKeyVersionRequest
{
CryptoKeyVersionName = keyVersion.CryptoKeyVersionName,
});
}
}
}
public string RandomId()
{
return $"csharp-{System.Guid.NewGuid()}";
}
public KeyRing CreateKeyRing(string keyRingId)
{
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
return client.CreateKeyRing(new CreateKeyRingRequest
{
ParentAsLocationName = LocationName,
KeyRingId = keyRingId,
});
}
public CryptoKey CreateAsymmetricDecryptKey(string keyId)
{
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
var request = new CreateCryptoKeyRequest
{
ParentAsKeyRingName = KeyRingName,
CryptoKeyId = keyId,
CryptoKey = new CryptoKey
{
Purpose = CryptoKey.Types.CryptoKeyPurpose.AsymmetricDecrypt,
VersionTemplate = new CryptoKeyVersionTemplate
{
Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.RsaDecryptOaep2048Sha256,
},
},
};
request.CryptoKey.Labels["foo"] = "bar";
request.CryptoKey.Labels["zip"] = "zap";
return client.CreateCryptoKey(request);
}
public CryptoKey CreateAsymmetricSignEcKey(string keyId)
{
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
var request = new CreateCryptoKeyRequest
{
ParentAsKeyRingName = KeyRingName,
CryptoKeyId = keyId,
CryptoKey = new CryptoKey
{
Purpose = CryptoKey.Types.CryptoKeyPurpose.AsymmetricSign,
VersionTemplate = new CryptoKeyVersionTemplate
{
Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.EcSignP256Sha256,
},
},
};
request.CryptoKey.Labels["foo"] = "bar";
request.CryptoKey.Labels["zip"] = "zap";
return client.CreateCryptoKey(request);
}
public CryptoKey CreateAsymmetricSignRsaKey(string keyId)
{
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
var request = new CreateCryptoKeyRequest
{
ParentAsKeyRingName = KeyRingName,
CryptoKeyId = keyId,
CryptoKey = new CryptoKey
{
Purpose = CryptoKey.Types.CryptoKeyPurpose.AsymmetricSign,
VersionTemplate = new CryptoKeyVersionTemplate
{
Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.RsaSignPss2048Sha256,
},
},
};
request.CryptoKey.Labels["foo"] = "bar";
request.CryptoKey.Labels["zip"] = "zap";
return client.CreateCryptoKey(request);
}
public CryptoKey CreateHsmKey(string keyId)
{
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
var request = new CreateCryptoKeyRequest
{
ParentAsKeyRingName = KeyRingName,
CryptoKeyId = keyId,
CryptoKey = new CryptoKey
{
Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
VersionTemplate = new CryptoKeyVersionTemplate
{
Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
ProtectionLevel = ProtectionLevel.Hsm,
},
},
};
request.CryptoKey.Labels["foo"] = "bar";
request.CryptoKey.Labels["zip"] = "zap";
return client.CreateCryptoKey(request);
}
public CryptoKey CreateMacKey(string keyId)
{
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
var request = new CreateCryptoKeyRequest
{
ParentAsKeyRingName = KeyRingName,
CryptoKeyId = keyId,
CryptoKey = new CryptoKey
{
Purpose = CryptoKey.Types.CryptoKeyPurpose.Mac,
VersionTemplate = new CryptoKeyVersionTemplate
{
Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.HmacSha256,
ProtectionLevel = ProtectionLevel.Hsm,
},
},
};
request.CryptoKey.Labels["foo"] = "bar";
request.CryptoKey.Labels["zip"] = "zap";
return client.CreateCryptoKey(request);
}
public CryptoKey CreateSymmetricKey(string keyId)
{
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
var request = new CreateCryptoKeyRequest
{
ParentAsKeyRingName = KeyRingName,
CryptoKeyId = keyId,
CryptoKey = new CryptoKey
{
Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
VersionTemplate = new CryptoKeyVersionTemplate
{
Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
},
},
};
request.CryptoKey.Labels["foo"] = "bar";
request.CryptoKey.Labels["zip"] = "zap";
return client.CreateCryptoKey(request);
}
public CryptoKeyVersion CreateKeyVersion(string keyId)
{
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
var result = client.CreateCryptoKeyVersion(new CreateCryptoKeyVersionRequest
{
ParentAsCryptoKeyName = new CryptoKeyName(ProjectId, LocationId, KeyRingId, keyId),
});
for (var i = 1; i <= 5; i++)
{
var version = client.GetCryptoKeyVersion(new GetCryptoKeyVersionRequest
{
CryptoKeyVersionName = result.CryptoKeyVersionName,
});
if (version.State == CryptoKeyVersion.Types.CryptoKeyVersionState.Enabled)
{
return version;
}
Thread.Sleep(500 * i);
}
throw new TimeoutException($"{result.Name} not enabled within time");
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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.Text;
using System.Drawing;
using System.Diagnostics;
using Axiom.MathLib;
using Axiom.Core;
using Axiom.Input;
namespace Multiverse.Gui {
/// <summary>
/// Gui window
/// </summary>
public class Window {
// Create a logger for use in this class
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Window));
protected string name;
protected float alpha = 1.0f;
protected Window parent;
protected Window clipParent;
protected List<Window> children = new List<Window>();
protected Rect area = new Rect();
protected ColorRect colors;
protected SizeF maxSize;
protected bool visible = false;
protected float zValue = 0;
protected bool isActive = false;
/// <summary>
/// The list of QuadBuckets for this window, created when
/// the window was last dirtied
/// </summary>
protected List<QuadBucket> quadBuckets = new List<QuadBucket>();
/// <summary>
/// The frame number when the window was last dirtied.
/// Windows that have been recently dirtied are kept
/// separate from windows that were dirtied some time ago,
/// so we don't have to constantly regenerate the batches
/// that contain windows that were not recently dirtied
/// </summary>
public int rebuildFrame = 0;
/// <summary>
/// Set when anyone changes the window, it's properties or
/// where it's displayed.
/// </summary>
private bool dirty = true;
public event EventHandler Activated;
public event EventHandler Deactivated;
// Basic mouse events
public event MouseEventHandler MouseDown;
public event MouseEventHandler MouseMoved;
public event MouseEventHandler MouseUp;
// More complex events (inserted by GuiSystem)
public event MouseEventHandler MouseClicked;
public event MouseEventHandler MouseDoubleClicked;
// Basic key events
public event KeyboardEventHandler KeyUp;
public event KeyboardEventHandler KeyDown;
// More complex key events (inserted by GuiSystem)
public event KeyboardEventHandler KeyPress;
// Capture events - inserted by GuiSystem?
public event EventHandler CaptureGained;
public event EventHandler CaptureLost;
public Window(string name) {
this.name = name;
}
public Window() {
this.name = null;
}
// FIXME -- implement Window.Initialize()
public virtual void Initialize() {
}
public void AddChild(Window child) {
// Add the child to the front of the queue
child.parent = this;
if (clipParent != null)
child.clipParent = clipParent;
children.Insert(0, child);
}
public void RemoveChild(Window child) {
children.Remove(child);
child.parent = null;
child.clipParent = null;
}
public void RemoveChild(int index) {
Window child = children[index];
RemoveChild(child);
}
public Window GetChildAtIndex(int index) {
return children[index];
}
public void MoveToFront() {
Dirty = true;
if (parent != null)
parent.MoveToFront();
// Deactivate any siblings, and activate ourself.
Window activeSibling = null;
if (parent != null) {
for (int i = 0; i < parent.ChildCount; ++i) {
Window tmp = parent.GetChildAtIndex(i);
if (tmp.IsActive) {
activeSibling = tmp;
break;
}
}
}
if (activeSibling != this) {
if (parent != null) {
Window currentParent = parent;
Window currentClipParent = clipParent;
// Add and remove our window, so that we are at the front
currentParent.RemoveChild(this);
currentParent.AddChild(this);
// Restore our clipParent
clipParent = currentClipParent;
}
// Deactivate our sibling, and then activate ourself.
EventArgs args = new EventArgs();
if (activeSibling != null)
activeSibling.OnDeactivated(args);
this.OnActivated(args);
}
}
public void Activate() {
MoveToFront();
}
///<summary>
/// Find the suitable bucket for the quad in the list of
/// buckets. If create is false and you don't find it in
/// the list, create the bucket and add it to the list.
/// If create is false and the bucket doesn't exist, return
/// null.
///</summary>
public QuadBucket FindBucketForQuad(QuadInfo quad, List<QuadBucket> buckets, bool create) {
float z = quad.z;
int textureHandle = quad.texture.Handle;
int hashCode = (quad.clipRect != null ? quad.clipRect.GetHashCode() : 0);
QuadBucket quadBucket = null;
foreach (QuadBucket bucket in quadBuckets) {
if (bucket.z == z && bucket.textureHandle == textureHandle && bucket.clipRectHash == hashCode) {
quadBucket = bucket;
break;
}
}
if (create && quadBucket == null) {
quadBucket = new QuadBucket(z, textureHandle, hashCode, this);
buckets.Add(quadBucket);
}
return quadBucket;
}
///<summary>
/// The TextureAndClipRect value is interned, so we can just
/// look it up, and don't have to iterate.
///</summary>
public void AddQuad(QuadInfo quad) {
QuadBucket quadBucket = FindBucketForQuad(quad, quadBuckets, true);
quadBucket.quads.Add(quad);
}
public void SetChildrenDirty() {
foreach (Window child in children) {
child.Dirty = true;
child.SetChildrenDirty();
}
}
// For this window and all its children, mark the
// RenderBatches referenced by QuadBuckets to be rebuilt, and
// sever the connection between the QuadQueue and any
// RenderBatches it might have contributed to.
public void RequireRenderBatchRebuilds() {
foreach (QuadBucket quadBucket in quadBuckets)
quadBucket.RequireRenderBatchRebuilds();
foreach (Window child in children)
child.RequireRenderBatchRebuilds();
}
public void ClearQuadBuckets() {
foreach (QuadBucket quadBucket in quadBuckets)
quadBucket.RequireRenderBatchRebuilds();
quadBuckets.Clear();
}
public void Draw() {
if (!visible)
return;
Renderer.Instance.CurrentWindow = this;
if (Dirty) {
ClearQuadBuckets();
rebuildFrame = Renderer.Instance.FrameCounter;
DrawSelf(0);
Dirty = false;
}
Renderer.Instance.AddQuadBuckets(quadBuckets);
foreach (Window child in children)
child.Draw();
}
protected virtual void DrawSelf(float z) {
DrawImpl(area, null, z);
}
protected virtual void DrawSelf(Vector3 pos, Rect clipRect) {
DrawImpl(area, clipRect, pos.z);
}
// FIXME - Actually queue quads as needed for Window.DrawImpl
protected virtual void DrawImpl(Rect drawArea, Rect clipArea, float z) {
// Trace.TraceInformation("Drawing window: " + this.Name);
}
// Mouse events
protected internal virtual void OnMouseDown(MouseEventArgs args) {
if (this.MouseDown != null)
MouseDown(this, args);
}
protected internal virtual void OnMouseUp(MouseEventArgs args) {
if (this.MouseUp != null)
MouseUp(this, args);
}
protected internal virtual void OnMouseMoved(MouseEventArgs args) {
if (this.MouseMoved != null)
MouseMoved(this, args);
}
// Higher level mouse events
protected internal virtual void OnMouseClicked(MouseEventArgs args) {
if (this.MouseClicked != null)
MouseClicked(this, args);
}
protected internal virtual void OnMouseDoubleClicked(MouseEventArgs args) {
if (this.MouseDoubleClicked != null)
MouseDoubleClicked(this, args);
}
// Key events
protected internal virtual void OnKeyUp(KeyEventArgs args) {
if (this.KeyUp != null)
KeyUp(this, args);
}
protected internal virtual void OnKeyDown(KeyEventArgs args) {
if (this.KeyDown != null)
KeyDown(this, args);
}
// Higher level key events
protected internal virtual void OnKeyPress(KeyEventArgs args) {
if (this.KeyPress != null)
KeyPress(this, args);
}
protected internal virtual void OnActivated(EventArgs args) {
isActive = true;
if (this.Activated != null)
Activated(this, args);
}
protected internal virtual void OnDeactivated(EventArgs args) {
isActive = false;
foreach (Window child in children) {
if (child.IsActive)
child.OnDeactivated(args);
}
if (this.Deactivated != null)
Deactivated(this, args);
}
// Do these make sense?
protected internal virtual void OnCaptureGained(EventArgs args) {
if (this.CaptureGained != null)
CaptureGained(this, args);
}
protected internal virtual void OnCaptureLost(EventArgs args) {
if (this.CaptureLost != null)
CaptureLost(this, args);
}
public void CaptureInput() {
GuiSystem.Instance.CaptureInput(this);
}
public void ReleaseInput() {
GuiSystem.Instance.ReleaseInput(this);
}
// FIXME - implement Window.RequestRedraw
protected void RequestRedraw() {
}
// Convert a point (in screen pixels), to the offset
// for that same point as a child window.
public PointF ScreenToWindow(PointF pt) {
PointF derivedPos = this.DerivedPosition;
pt.X -= derivedPos.X;
pt.Y -= derivedPos.Y;
return pt;
}
// Rectangle that this window would cover
//public virtual Rect UnclippedPixelRect {
// get { return DerivedArea; }
//}
// Clipped variant of the above
public virtual Rect PixelRect {
get {
if (clipParent != null)
return clipParent.PixelRect.GetIntersection(DerivedArea);
return DerivedArea;
}
}
// Rectangle into which children can be drawn without
// interfering with a frame
public virtual Rect UnclippedInnerRect {
get { return DerivedArea; }
}
public virtual void SetAreaRect(Rect rect) {
area = rect;
}
public virtual float EffectiveAlpha {
get {
if (parent == null)
return alpha;
return alpha * parent.EffectiveAlpha;
}
}
/// <summary>
/// Convert a point coordinate within our window (where 0,0 is the
/// top left of our window) to an absolute screen position.
/// </summary>
/// <param name="pt">the coordinates within our window (in pixels)</param>
/// <returns>the coordinates in screen space (in pixels)</returns>
public PointF RelativeToAbsolute(PointF pt) {
PointF derivedPos = this.DerivedPosition;
pt.X += derivedPos.X;
pt.Y += derivedPos.Y;
return pt;
}
/// <summary>
/// Sets or gets the position of the top left corner of this widget
/// This is relative to the parent window.
/// </summary>
public PointF Position {
get {
return new PointF(area.Left, area.Top);
}
set {
Rect p = new Rect(value.X, value.X + area.Width, value.Y, value.Y + area.Height);
if (p != area) {
Dirty = true;
area = p;
}
}
}
public PointF DerivedPosition {
get {
if (parent == null)
return this.Position;
PointF derivedPos = parent.DerivedPosition;
PointF pos = this.Position;
pos.X += derivedPos.X;
pos.Y += derivedPos.Y;
return pos;
}
set {
PointF newPosition;
if (parent == null)
newPosition = value;
else
{
PointF derivedPos = parent.DerivedPosition;
PointF pos = value;
pos.X -= derivedPos.X;
pos.Y -= derivedPos.Y;
newPosition = pos;
}
if (this.Position != newPosition) {
Dirty = true;
this.Position = newPosition;
}
}
}
public Rect DerivedArea {
get {
if (parent == null)
return new Rect(area.Left, area.Right, area.Top, area.Bottom);
PointF p = parent.DerivedPosition;
return new Rect(p.X + area.Left,
p.X + area.Right,
p.Y + area.Top,
p.Y + area.Bottom);
}
}
public SizeF Size {
get {
return new SizeF(area.Right - area.Left, area.Bottom - area.Top);
}
set {
Rect newArea = new Rect(area.Left, area.Left + value.Width, area.Top, area.Top + value.Height);
if (newArea != area) {
Dirty = true;
area = newArea;
}
}
}
public float Height {
get {
return area.Height;
}
set
{
if (area.Height != value) {
Dirty = true;
area.Height = value;
}
}
}
public float Width {
get {
return area.Width;
}
set
{
if (area.Width != value) {
Dirty = true;
area.Width = value;
}
}
}
public SizeF MaximumSize {
get {
return maxSize;
}
set {
if (maxSize != value) {
Dirty = true;
maxSize = value;
}
}
}
public bool Visible {
get {
return visible;
}
set {
if (visible != value) {
visible = value;
// If we're now being made invisible, we must mark
// the RenderBatches of which we're a component to
// be rebuilt.
if (visible == false)
RequireRenderBatchRebuilds();
else
dirty = true;
}
}
}
public string Name {
get { return name; }
}
public int ChildCount {
get {
return children.Count;
}
}
public float Alpha {
get {
return alpha;
}
set {
if (alpha != value) {
Dirty = true;
alpha = value;
}
}
}
public Window Parent {
get {
return parent;
}
}
public float ZValue {
get {
return zValue;
}
set {
if (zValue != value) {
Dirty = true;
zValue = value;
}
}
}
public bool IsActive {
get {
return isActive;
}
}
/// <summary>
/// Get the deepest descendent window that is active
/// </summary>
public Window ActiveChild {
get {
if (!this.IsActive)
return null;
foreach (Window child in children)
if (child.IsActive)
return child.ActiveChild;
return this;
}
}
public bool Dirty {
get {
return dirty;
}
set {
if (dirty != value && !dirty) {
log.DebugFormat("Window.Dirty: Setting {0} dirty", name);
//log.DebugFormat("Window.Dirty: Setting {0} dirty\nStack Trace: {1}", name, new StackTrace(true));
}
dirty = value;
}
}
}
}
| |
namespace Swensen.Ior.Forms
{
using System.Drawing;
using System.Windows.Forms;
public class CustomColorScheme : ProfessionalColorTable
{
public override Color ButtonCheckedGradientBegin
{
get
{
return Color.FromArgb(0xC1, 210, 0xEE);
}
}
public override Color ButtonCheckedGradientEnd
{
get
{
return Color.FromArgb(0xC1, 210, 0xEE);
}
}
public override Color ButtonCheckedGradientMiddle
{
get
{
return Color.FromArgb(0xC1, 210, 0xEE);
}
}
public override Color ButtonPressedBorder
{
get
{
return Color.FromArgb(0x31, 0x6A, 0xC5);
}
}
public override Color ButtonPressedGradientBegin
{
get
{
return Color.FromArgb(0x98, 0xB5, 0xE2);
}
}
public override Color ButtonPressedGradientEnd
{
get
{
return Color.FromArgb(0x98, 0xB5, 0xE2);
}
}
public override Color ButtonPressedGradientMiddle
{
get
{
return Color.FromArgb(0x98, 0xB5, 0xE2);
}
}
public override Color ButtonSelectedBorder
{
get
{
return base.ButtonSelectedBorder;
}
}
public override Color ButtonSelectedGradientBegin
{
get
{
return Color.FromArgb(0xC1, 210, 0xEE);
}
}
public override Color ButtonSelectedGradientEnd
{
get
{
return Color.FromArgb(0xC1, 210, 0xEE);
}
}
public override Color ButtonSelectedGradientMiddle
{
get
{
return Color.FromArgb(0xC1, 210, 0xEE);
}
}
public override Color CheckBackground
{
get
{
return Color.FromArgb(0xE1, 230, 0xE8);
}
}
public override Color CheckPressedBackground
{
get
{
return Color.FromArgb(0x31, 0x6A, 0xC5);
}
}
public override Color CheckSelectedBackground
{
get
{
return Color.FromArgb(0x31, 0x6A, 0xC5);
}
}
public override Color GripDark
{
get
{
return Color.FromArgb(0xC1, 190, 0xB3);
}
}
public override Color GripLight
{
get
{
return Color.FromArgb(0xFF, 0xFF, 0xFF);
}
}
public override Color ImageMarginGradientBegin
{
get
{
return Color.FromArgb(251, 250, 247);
}
}
public override Color ImageMarginGradientEnd
{
get
{
return Color.FromArgb(0xBD, 0xBD, 0xA3);
}
}
public override Color ImageMarginGradientMiddle
{
get
{
return Color.FromArgb(0xEC, 0xE7, 0xE0);
}
}
public override Color ImageMarginRevealedGradientBegin
{
get
{
return Color.FromArgb(0xF7, 0xF6, 0xEF);
}
}
public override Color ImageMarginRevealedGradientEnd
{
get
{
return Color.FromArgb(230, 0xE3, 210);
}
}
public override Color ImageMarginRevealedGradientMiddle
{
get
{
return Color.FromArgb(0xF2, 240, 0xE4);
}
}
public override Color MenuBorder
{
get
{
return Color.FromArgb(0x8A, 0x86, 0x7A);
}
}
public override Color MenuItemBorder
{
get
{
return Color.FromArgb(0x31, 0x6A, 0xC5);
}
}
public override Color MenuItemPressedGradientBegin
{
get
{
return base.MenuItemPressedGradientBegin;
}
}
public override Color MenuItemPressedGradientEnd
{
get
{
return base.MenuItemPressedGradientEnd;
}
}
public override Color MenuItemPressedGradientMiddle
{
get
{
return base.MenuItemPressedGradientMiddle;
}
}
public override Color MenuItemSelected
{
get
{
return Color.FromArgb(0xC1, 210, 0xEE);
}
}
public override Color MenuItemSelectedGradientBegin
{
get
{
return Color.FromArgb(0xC1, 210, 0xEE);
}
}
public override Color MenuItemSelectedGradientEnd
{
get
{
return Color.FromArgb(0xC1, 210, 0xEE);
}
}
public override Color MenuStripGradientBegin
{
get
{
return Color.FromArgb(0xE5, 0xE5, 0xD7);
}
}
public override Color MenuStripGradientEnd
{
get
{
return Color.FromArgb(0xF4, 0xF2, 0xE8);
}
}
public override Color OverflowButtonGradientBegin
{
get
{
return Color.FromArgb(0xF3, 0xF2, 240);
}
}
public override Color OverflowButtonGradientEnd
{
get
{
return Color.FromArgb(0x92, 0x92, 0x76);
}
}
public override Color OverflowButtonGradientMiddle
{
get
{
return Color.FromArgb(0xE2, 0xE1, 0xDB);
}
}
public override Color RaftingContainerGradientBegin
{
get
{
return Color.FromArgb(0xE5, 0xE5, 0xD7);
}
}
public override Color RaftingContainerGradientEnd
{
get
{
return Color.FromArgb(0xF4, 0xF2, 0xE8);
}
}
public override Color SeparatorDark
{
get
{
return Color.FromArgb(0xC5, 0xC2, 0xB8);
}
}
public override Color SeparatorLight
{
get
{
return Color.FromArgb(0xFF, 0xFF, 0xFF);
}
}
public override Color ToolStripBorder
{
get
{
return Color.FromArgb(0xA3, 0xA3, 0x7C);
}
}
public override Color ToolStripDropDownBackground
{
get
{
return Color.FromArgb(0xFC, 0xFC, 0xF9);
}
}
public override Color ToolStripGradientBegin
{
get
{
return Color.FromArgb(0xF7, 0xF6, 0xEF);
}
}
public override Color ToolStripGradientEnd
{
get
{
return Color.FromArgb(192, 192, 168);
}
}
public override Color ToolStripGradientMiddle
{
get
{
return Color.FromArgb(0xF2, 240, 0xE4);
}
}
public override System.Drawing.Color ToolStripPanelGradientBegin
{
get
{
return Color.FromArgb(0xE5, 0xE5, 0xD7);
}
}
public override System.Drawing.Color ToolStripPanelGradientEnd
{
get
{
return Color.FromArgb(0xF4, 0xF2, 0xE8);
}
}
}
}
| |
// 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.Collections.Generic;
using System.IO;
using System.Xml;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Construction;
using Microsoft.Build.Shared;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using Xunit;
namespace Microsoft.Build.UnitTests.OM.Construction
{
/// <summary>
/// Tests for the ProjectImportElement class
/// </summary>
public class ProjectImportElement_Tests
{
/// <summary>
/// Read project with no imports
/// </summary>
[Fact]
public void ReadNone()
{
ProjectRootElement project = ProjectRootElement.Create();
Assert.Null(project.Imports.GetEnumerator().Current);
}
/// <summary>
/// Read import with no project attribute
/// </summary>
[Fact]
public void ReadInvalidMissingProject()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import/>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Read import with empty project attribute
/// </summary>
[Fact]
public void ReadInvalidEmptyProject()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project=''/>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Read import with unexpected attribute
/// </summary>
[Fact]
public void ReadInvalidAttribute()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='p' X='Y'/>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Read basic valid imports
/// </summary>
[Fact]
public void ReadBasic()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='i1.proj' />
<Import Project='i2.proj' Condition='c'/>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
List<ProjectImportElement> imports = Helpers.MakeList(project.Imports);
Assert.Equal(2, imports.Count);
Assert.Equal("i1.proj", imports[0].Project);
Assert.Equal("i2.proj", imports[1].Project);
Assert.Equal("c", imports[1].Condition);
}
/// <summary>
/// Set valid project on import
/// </summary>
[Fact]
public void SetProjectValid()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='i1.proj' />
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectImportElement import = (ProjectImportElement)Helpers.GetFirst(project.Children);
import.Project = "i1b.proj";
Assert.Equal("i1b.proj", import.Project);
}
/// <summary>
/// Set invalid empty project value on import
/// </summary>
[Fact]
public void SetProjectInvalidEmpty()
{
Assert.Throws<ArgumentException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='i1.proj' />
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectImportElement import = (ProjectImportElement)Helpers.GetFirst(project.Children);
import.Project = String.Empty;
}
);
}
/// <summary>
/// Setting the project attribute should dirty the project
/// </summary>
[Fact]
public void SettingProjectDirties()
{
string file1 = null;
string file2 = null;
try
{
file1 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
ProjectRootElement importProject1 = ProjectRootElement.Create();
importProject1.AddProperty("p", "v1");
importProject1.Save(file1);
file2 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
ProjectRootElement importProject2 = ProjectRootElement.Create();
importProject2.AddProperty("p", "v2");
importProject2.Save(file2);
string content = String.Format
(
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='{0}'/>
</Project>",
file1
);
Project project = new Project(XmlReader.Create(new StringReader(content)));
ProjectImportElement import = Helpers.GetFirst(project.Xml.Imports);
import.Project = file2;
Assert.Equal("v1", project.GetPropertyValue("p"));
project.ReevaluateIfNecessary();
Assert.Equal("v2", project.GetPropertyValue("p"));
}
finally
{
File.Delete(file1);
File.Delete(file2);
}
}
/// <summary>
/// Setting the condition should dirty the project
/// </summary>
[Fact]
public void SettingConditionDirties()
{
string file = null;
try
{
file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
ProjectRootElement importProject = ProjectRootElement.Create();
importProject.AddProperty("p", "v1");
importProject.Save(file);
string content = String.Format
(
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='{0}'/>
</Project>",
file
);
Project project = new Project(XmlReader.Create(new StringReader(content)));
ProjectImportElement import = Helpers.GetFirst(project.Xml.Imports);
import.Condition = "false";
Assert.Equal("v1", project.GetPropertyValue("p"));
project.ReevaluateIfNecessary();
Assert.Equal(String.Empty, project.GetPropertyValue("p"));
}
finally
{
File.Delete(file);
}
}
/// <summary>
/// Importing a project which has a relative path
/// </summary>
[Fact]
public void ImportWithRelativePath()
{
string tempPath = Path.GetTempPath();
string testTempPath = Path.Combine(tempPath, "UnitTestsPublicOm");
string projectfile = Path.Combine(testTempPath, "a.proj");
string targetsFile = Path.Combine(tempPath, "x.targets");
string projectfileContent = String.Format
(
@"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='{0}'/>
</Project>
",
testTempPath + "\\..\\x.targets"
);
string targetsfileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
</Project>
";
try
{
Directory.CreateDirectory(testTempPath);
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectfileContent)));
project.Save(projectfile);
project = ProjectRootElement.Create(XmlReader.Create(new StringReader(targetsfileContent)));
project.Save(targetsFile);
Project msbuildProject = new Project(projectfile);
}
finally
{
if (Directory.Exists(testTempPath))
{
FileUtilities.DeleteWithoutTrailingBackslash(testTempPath, true);
}
if (File.Exists(targetsFile))
{
File.Delete(targetsFile);
}
}
}
}
}
| |
// 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\General\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;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void AsByte()
{
var test = new VectorAs__AsByte();
// Validates basic functionality works
test.RunBasicScenario();
// Validates basic functionality works using the generic form, rather than the type-specific form of the method
test.RunGenericScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorAs__AsByte
{
private static readonly int LargestVectorSize = 16;
private static readonly int ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Vector128<Byte> value;
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<byte> byteResult = value.AsByte();
ValidateResult(byteResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<double> doubleResult = value.AsDouble();
ValidateResult(doubleResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<short> shortResult = value.AsInt16();
ValidateResult(shortResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<int> intResult = value.AsInt32();
ValidateResult(intResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<long> longResult = value.AsInt64();
ValidateResult(longResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<sbyte> sbyteResult = value.AsSByte();
ValidateResult(sbyteResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<float> floatResult = value.AsSingle();
ValidateResult(floatResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<ushort> ushortResult = value.AsUInt16();
ValidateResult(ushortResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<uint> uintResult = value.AsUInt32();
ValidateResult(uintResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<ulong> ulongResult = value.AsUInt64();
ValidateResult(ulongResult, value);
}
public void RunGenericScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario));
Vector128<Byte> value;
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<byte> byteResult = value.As<Byte, byte>();
ValidateResult(byteResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<double> doubleResult = value.As<Byte, double>();
ValidateResult(doubleResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<short> shortResult = value.As<Byte, short>();
ValidateResult(shortResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<int> intResult = value.As<Byte, int>();
ValidateResult(intResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<long> longResult = value.As<Byte, long>();
ValidateResult(longResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<sbyte> sbyteResult = value.As<Byte, sbyte>();
ValidateResult(sbyteResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<float> floatResult = value.As<Byte, float>();
ValidateResult(floatResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<ushort> ushortResult = value.As<Byte, ushort>();
ValidateResult(ushortResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<uint> uintResult = value.As<Byte, uint>();
ValidateResult(uintResult, value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
Vector128<ulong> ulongResult = value.As<Byte, ulong>();
ValidateResult(ulongResult, value);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Vector128<Byte> value;
value = Vector128.Create(TestLibrary.Generator.GetByte());
object byteResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsByte))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<byte>)(byteResult), value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
object doubleResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsDouble))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<double>)(doubleResult), value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
object shortResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsInt16))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<short>)(shortResult), value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
object intResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsInt32))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<int>)(intResult), value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
object longResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsInt64))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<long>)(longResult), value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
object sbyteResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsSByte))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<sbyte>)(sbyteResult), value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
object floatResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsSingle))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<float>)(floatResult), value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
object ushortResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsUInt16))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<ushort>)(ushortResult), value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
object uintResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsUInt32))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<uint>)(uintResult), value);
value = Vector128.Create(TestLibrary.Generator.GetByte());
object ulongResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsUInt64))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<ulong>)(ulongResult), value);
}
private void ValidateResult<T>(Vector128<T> result, Vector128<Byte> value, [CallerMemberName] string method = "")
where T : struct
{
Byte[] resultElements = new Byte[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref resultElements[0]), result);
Byte[] valueElements = new Byte[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref valueElements[0]), value);
ValidateResult(resultElements, valueElements, typeof(T), method);
}
private void ValidateResult(Byte[] resultElements, Byte[] valueElements, Type targetType, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < ElementCount; i++)
{
if (resultElements[i] != valueElements[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Byte>.As{targetType.Name}: {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Text;
using System.Threading;
using KERB_LOGON_SUBMIT_TYPE = Interop.SspiCli.KERB_LOGON_SUBMIT_TYPE;
using KERB_S4U_LOGON = Interop.SspiCli.KERB_S4U_LOGON;
using KerbS4uLogonFlags = Interop.SspiCli.KerbS4uLogonFlags;
using LUID = Interop.LUID;
using LSA_STRING = Interop.SspiCli.LSA_STRING;
using QUOTA_LIMITS = Interop.SspiCli.QUOTA_LIMITS;
using SECURITY_LOGON_TYPE = Interop.SspiCli.SECURITY_LOGON_TYPE;
using TOKEN_SOURCE = Interop.SspiCli.TOKEN_SOURCE;
using System.Runtime.Serialization;
namespace System.Security.Principal
{
[System.Runtime.InteropServices.ComVisible(true)]
public enum WindowsAccountType
{
Normal = 0,
Guest = 1,
System = 2,
Anonymous = 3
}
public class WindowsIdentity : ClaimsIdentity, IDisposable, ISerializable, IDeserializationCallback
{
private string _name = null;
private SecurityIdentifier _owner = null;
private SecurityIdentifier _user = null;
private IdentityReferenceCollection _groups = null;
private SafeAccessTokenHandle _safeTokenHandle = SafeAccessTokenHandle.InvalidHandle;
private string _authType = null;
private int _isAuthenticated = -1;
private volatile TokenImpersonationLevel _impersonationLevel;
private volatile bool _impersonationLevelInitialized;
public new const string DefaultIssuer = @"AD AUTHORITY";
private string _issuerName = DefaultIssuer;
private object _claimsIntiailizedLock = new object();
private volatile bool _claimsInitialized;
private List<Claim> _deviceClaims;
private List<Claim> _userClaims;
private static bool s_ignoreWindows8Properties;
public WindowsIdentity(IntPtr userToken) : this(userToken, null, -1) { }
public WindowsIdentity(IntPtr userToken, string type) : this(userToken, type, -1) { }
// The actual accType is ignored and always will be retrieved from the system.
public WindowsIdentity(IntPtr userToken, string type, WindowsAccountType acctType) : this(userToken, type, -1) { }
public WindowsIdentity(IntPtr userToken, string type, WindowsAccountType acctType, bool isAuthenticated)
: this(userToken, type, isAuthenticated ? 1 : 0) { }
protected WindowsIdentity(WindowsIdentity identity)
: base(identity, null, GetAuthType(identity), null, null)
{
bool mustDecrement = false;
try
{
if (!identity._safeTokenHandle.IsInvalid && identity._safeTokenHandle != SafeAccessTokenHandle.InvalidHandle && identity._safeTokenHandle.DangerousGetHandle() != IntPtr.Zero)
{
identity._safeTokenHandle.DangerousAddRef(ref mustDecrement);
if (!identity._safeTokenHandle.IsInvalid && identity._safeTokenHandle.DangerousGetHandle() != IntPtr.Zero)
CreateFromToken(identity._safeTokenHandle.DangerousGetHandle());
_authType = identity._authType;
_isAuthenticated = identity._isAuthenticated;
}
}
finally
{
if (mustDecrement)
identity._safeTokenHandle.DangerousRelease();
}
}
private WindowsIdentity(IntPtr userToken, string authType, int isAuthenticated)
: base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid)
{
CreateFromToken(userToken);
_authType = authType;
_isAuthenticated = isAuthenticated;
}
private WindowsIdentity()
: base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid)
{ }
/// <summary>
/// Initializes a new instance of the WindowsIdentity class for the user represented by the specified User Principal Name (UPN).
/// </summary>
/// <remarks>
/// Unlike the desktop version, we connect to Lsa only as an untrusted caller. We do not attempt to exploit Tcb privilege or adjust the current
/// thread privilege to include Tcb.
/// </remarks>
public WindowsIdentity(string sUserPrincipalName)
: base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid)
{
// Desktop compat: See comments below for why we don't validate sUserPrincipalName.
using (SafeLsaHandle lsaHandle = ConnectToLsa())
{
int packageId = LookupAuthenticationPackage(lsaHandle, Interop.SspiCli.AuthenticationPackageNames.MICROSOFT_KERBEROS_NAME_A);
// 8 byte or less name that indicates the source of the access token. This choice of name is visible to callers through the native GetTokenInformation() api
// so we'll use the same name the CLR used even though we're not actually the "CLR."
byte[] sourceName = { (byte)'C', (byte)'L', (byte)'R', (byte)0 };
TOKEN_SOURCE sourceContext;
if (!Interop.Advapi32.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier))
throw new SecurityException(new Win32Exception().Message);
sourceContext.SourceName = new byte[TOKEN_SOURCE.TOKEN_SOURCE_LENGTH];
Buffer.BlockCopy(sourceName, 0, sourceContext.SourceName, 0, sourceName.Length);
// Desktop compat: Desktop never null-checks sUserPrincipalName. Actual behavior is that the null makes it down to Encoding.Unicode.GetBytes() which then throws
// the ArgumentNullException (provided that the prior LSA calls didn't fail first.) To make this compat decision explicit, we'll null check ourselves
// and simulate the exception from Encoding.Unicode.GetBytes().
if (sUserPrincipalName == null)
throw new ArgumentNullException("s");
byte[] upnBytes = Encoding.Unicode.GetBytes(sUserPrincipalName);
if (upnBytes.Length > ushort.MaxValue)
{
// Desktop compat: LSA only allocates 16 bits to hold the UPN size. We should throw an exception here but unfortunately, the desktop did an unchecked cast to ushort,
// effectively truncating upnBytes to the first (N % 64K) bytes. We'll simulate the same behavior here (albeit in a way that makes it look less accidental.)
Array.Resize(ref upnBytes, upnBytes.Length & ushort.MaxValue);
}
unsafe
{
//
// Build the KERB_S4U_LOGON structure. Note that the LSA expects this entire
// structure to be contained within the same block of memory, so we need to allocate
// enough room for both the structure itself and the UPN string in a single buffer
// and do the marshalling into this buffer by hand.
//
int authenticationInfoLength = checked(sizeof(KERB_S4U_LOGON) + upnBytes.Length);
using (SafeLocalAllocHandle authenticationInfo = Interop.Kernel32.LocalAlloc(0, new UIntPtr(checked((uint)authenticationInfoLength))))
{
if (authenticationInfo.IsInvalid)
throw new OutOfMemoryException();
KERB_S4U_LOGON* pKerbS4uLogin = (KERB_S4U_LOGON*)(authenticationInfo.DangerousGetHandle());
pKerbS4uLogin->MessageType = KERB_LOGON_SUBMIT_TYPE.KerbS4ULogon;
pKerbS4uLogin->Flags = KerbS4uLogonFlags.None;
pKerbS4uLogin->ClientUpn.Length = pKerbS4uLogin->ClientUpn.MaximumLength = checked((ushort)upnBytes.Length);
IntPtr pUpnOffset = (IntPtr)(pKerbS4uLogin + 1);
pKerbS4uLogin->ClientUpn.Buffer = pUpnOffset;
Marshal.Copy(upnBytes, 0, pKerbS4uLogin->ClientUpn.Buffer, upnBytes.Length);
pKerbS4uLogin->ClientRealm.Length = pKerbS4uLogin->ClientRealm.MaximumLength = 0;
pKerbS4uLogin->ClientRealm.Buffer = IntPtr.Zero;
ushort sourceNameLength = checked((ushort)(sourceName.Length));
using (SafeLocalAllocHandle sourceNameBuffer = Interop.Kernel32.LocalAlloc(0, new UIntPtr(sourceNameLength)))
{
if (sourceNameBuffer.IsInvalid)
throw new OutOfMemoryException();
Marshal.Copy(sourceName, 0, sourceNameBuffer.DangerousGetHandle(), sourceName.Length);
LSA_STRING lsaOriginName = new LSA_STRING(sourceNameBuffer.DangerousGetHandle(), sourceNameLength);
SafeLsaReturnBufferHandle profileBuffer;
int profileBufferLength;
LUID logonId;
SafeAccessTokenHandle accessTokenHandle;
QUOTA_LIMITS quota;
int subStatus;
int ntStatus = Interop.SspiCli.LsaLogonUser(
lsaHandle,
ref lsaOriginName,
SECURITY_LOGON_TYPE.Network,
packageId,
authenticationInfo.DangerousGetHandle(),
authenticationInfoLength,
IntPtr.Zero,
ref sourceContext,
out profileBuffer,
out profileBufferLength,
out logonId,
out accessTokenHandle,
out quota,
out subStatus);
if (ntStatus == unchecked((int)Interop.StatusOptions.STATUS_ACCOUNT_RESTRICTION) && subStatus < 0)
ntStatus = subStatus;
if (ntStatus < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(ntStatus);
if (subStatus < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(subStatus);
if (profileBuffer != null)
profileBuffer.Dispose();
_safeTokenHandle = accessTokenHandle;
}
}
}
}
}
private static SafeLsaHandle ConnectToLsa()
{
SafeLsaHandle lsaHandle;
int ntStatus = Interop.SspiCli.LsaConnectUntrusted(out lsaHandle);
if (ntStatus < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(ntStatus);
return lsaHandle;
}
private static int LookupAuthenticationPackage(SafeLsaHandle lsaHandle, string packageName)
{
Debug.Assert(!string.IsNullOrEmpty(packageName));
unsafe
{
int packageId;
byte[] asciiPackageName = Encoding.ASCII.GetBytes(packageName);
fixed (byte* pAsciiPackageName = &asciiPackageName[0])
{
LSA_STRING lsaPackageName = new LSA_STRING((IntPtr)pAsciiPackageName, checked((ushort)(asciiPackageName.Length)));
int ntStatus = Interop.SspiCli.LsaLookupAuthenticationPackage(lsaHandle, ref lsaPackageName, out packageId);
if (ntStatus < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(ntStatus);
}
return packageId;
}
}
private static SafeAccessTokenHandle DuplicateAccessToken(IntPtr accessToken)
{
if (accessToken == IntPtr.Zero)
{
throw new ArgumentException(SR.Argument_TokenZero);
}
// Find out if the specified token is a valid.
uint dwLength = sizeof(uint);
if (!Interop.Advapi32.GetTokenInformation(
accessToken,
(uint)TokenInformationClass.TokenType,
IntPtr.Zero,
0,
out dwLength) &&
Marshal.GetLastWin32Error() == Interop.Errors.ERROR_INVALID_HANDLE)
{
throw new ArgumentException(SR.Argument_InvalidImpersonationToken);
}
SafeAccessTokenHandle duplicateAccessToken = SafeAccessTokenHandle.InvalidHandle;
IntPtr currentProcessHandle = Interop.Kernel32.GetCurrentProcess();
if (!Interop.Kernel32.DuplicateHandle(
currentProcessHandle,
accessToken,
currentProcessHandle,
ref duplicateAccessToken,
0,
true,
Interop.DuplicateHandleOptions.DUPLICATE_SAME_ACCESS))
{
throw new SecurityException(new Win32Exception().Message);
}
return duplicateAccessToken;
}
private static SafeAccessTokenHandle DuplicateAccessToken(SafeAccessTokenHandle accessToken)
{
if (accessToken.IsInvalid)
{
return accessToken;
}
bool refAdded = false;
try
{
accessToken.DangerousAddRef(ref refAdded);
return DuplicateAccessToken(accessToken.DangerousGetHandle());
}
finally
{
if (refAdded)
{
accessToken.DangerousRelease();
}
}
}
private void CreateFromToken(IntPtr userToken)
{
_safeTokenHandle = DuplicateAccessToken(userToken);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Public API has already shipped.")]
public WindowsIdentity(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
void IDeserializationCallback.OnDeserialization(object sender)
{
throw new PlatformNotSupportedException();
}
//
// Factory methods.
//
public static WindowsIdentity GetCurrent()
{
return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, false);
}
public static WindowsIdentity GetCurrent(bool ifImpersonating)
{
return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, ifImpersonating);
}
public static WindowsIdentity GetCurrent(TokenAccessLevels desiredAccess)
{
return GetCurrentInternal(desiredAccess, false);
}
// GetAnonymous() is used heavily in ASP.NET requests as a dummy identity to indicate
// the request is anonymous. It does not represent a real process or thread token so
// it cannot impersonate or do anything useful. Note this identity does not represent the
// usual concept of an anonymous token, and the name is simply misleading but we cannot change it now.
public static WindowsIdentity GetAnonymous()
{
return new WindowsIdentity();
}
//
// Properties.
//
// this is defined 'override sealed' for back compat. Il generated is 'virtual final' and this needs to be the same.
public override sealed string AuthenticationType
{
get
{
// If this is an anonymous identity, return an empty string
if (_safeTokenHandle.IsInvalid)
return string.Empty;
if (_authType == null)
{
Interop.LUID authId = GetLogonAuthId(_safeTokenHandle);
if (authId.LowPart == Interop.LuidOptions.ANONYMOUS_LOGON_LUID)
return string.Empty; // no authentication, just return an empty string
SafeLsaReturnBufferHandle pLogonSessionData = SafeLsaReturnBufferHandle.InvalidHandle;
try
{
int status = Interop.SspiCli.LsaGetLogonSessionData(ref authId, ref pLogonSessionData);
if (status < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(status);
pLogonSessionData.Initialize((uint)Marshal.SizeOf<Interop.SECURITY_LOGON_SESSION_DATA>());
Interop.SECURITY_LOGON_SESSION_DATA logonSessionData = pLogonSessionData.Read<Interop.SECURITY_LOGON_SESSION_DATA>(0);
return Marshal.PtrToStringUni(logonSessionData.AuthenticationPackage.Buffer);
}
finally
{
if (!pLogonSessionData.IsInvalid)
pLogonSessionData.Dispose();
}
}
return _authType;
}
}
public TokenImpersonationLevel ImpersonationLevel
{
get
{
// In case of a race condition here here, both threads will set m_impersonationLevel to the same value,
// which is ok.
if (!_impersonationLevelInitialized)
{
TokenImpersonationLevel impersonationLevel = TokenImpersonationLevel.None;
// If this is an anonymous identity
if (_safeTokenHandle.IsInvalid)
{
impersonationLevel = TokenImpersonationLevel.Anonymous;
}
else
{
TokenType tokenType = (TokenType)GetTokenInformation<int>(TokenInformationClass.TokenType);
if (tokenType == TokenType.TokenPrimary)
{
impersonationLevel = TokenImpersonationLevel.None; // primary token;
}
else
{
/// This is an impersonation token, get the impersonation level
int level = GetTokenInformation<int>(TokenInformationClass.TokenImpersonationLevel);
impersonationLevel = (TokenImpersonationLevel)level + 1;
}
}
_impersonationLevel = impersonationLevel;
_impersonationLevelInitialized = true;
}
return _impersonationLevel;
}
}
public override bool IsAuthenticated
{
get
{
if (_isAuthenticated == -1)
{
// This approach will not work correctly for domain guests (will return false
// instead of true). This is a corner-case that is not very interesting.
_isAuthenticated = CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[] { Interop.SecurityIdentifier.SECURITY_AUTHENTICATED_USER_RID })) ? 1 : 0;
}
return _isAuthenticated == 1;
}
}
private bool CheckNtTokenForSid(SecurityIdentifier sid)
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return false;
// CheckTokenMembership expects an impersonation token
SafeAccessTokenHandle token = SafeAccessTokenHandle.InvalidHandle;
TokenImpersonationLevel til = ImpersonationLevel;
bool isMember = false;
try
{
if (til == TokenImpersonationLevel.None)
{
if (!Interop.Advapi32.DuplicateTokenEx(_safeTokenHandle,
(uint)TokenAccessLevels.Query,
IntPtr.Zero,
(uint)TokenImpersonationLevel.Identification,
(uint)TokenType.TokenImpersonation,
ref token))
throw new SecurityException(new Win32Exception().Message);
}
// CheckTokenMembership will check if the SID is both present and enabled in the access token.
#if uap
if (!Interop.Kernel32.CheckTokenMembershipEx((til != TokenImpersonationLevel.None ? _safeTokenHandle : token),
sid.BinaryForm,
Interop.Kernel32.CTMF_INCLUDE_APPCONTAINER,
ref isMember))
throw new SecurityException(new Win32Exception().Message);
#else
if (!Interop.Advapi32.CheckTokenMembership((til != TokenImpersonationLevel.None ? _safeTokenHandle : token),
sid.BinaryForm,
ref isMember))
throw new SecurityException(new Win32Exception().Message);
#endif
}
finally
{
if (token != SafeAccessTokenHandle.InvalidHandle)
{
token.Dispose();
}
}
return isMember;
}
//
// IsGuest, IsSystem and IsAnonymous are maintained for compatibility reasons. It is always
// possible to extract this same information from the User SID property and the new
// (and more general) methods defined in the SID class (IsWellKnown, etc...).
//
public virtual bool IsGuest
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return false;
return CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[] { Interop.SecurityIdentifier.SECURITY_BUILTIN_DOMAIN_RID, (int)WindowsBuiltInRole.Guest }));
}
}
public virtual bool IsSystem
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return false;
SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[] { Interop.SecurityIdentifier.SECURITY_LOCAL_SYSTEM_RID });
return (this.User == sid);
}
}
public virtual bool IsAnonymous
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return true;
SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[] { Interop.SecurityIdentifier.SECURITY_ANONYMOUS_LOGON_RID });
return (this.User == sid);
}
}
public override string Name
{
get
{
return GetName();
}
}
internal string GetName()
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return string.Empty;
if (_name == null)
{
// revert thread impersonation for the duration of the call to get the name.
RunImpersonated(SafeAccessTokenHandle.InvalidHandle, delegate
{
NTAccount ntAccount = this.User.Translate(typeof(NTAccount)) as NTAccount;
_name = ntAccount.ToString();
});
}
return _name;
}
public SecurityIdentifier Owner
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return null;
if (_owner == null)
{
using (SafeLocalAllocHandle tokenOwner = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenOwner))
{
_owner = new SecurityIdentifier(tokenOwner.Read<IntPtr>(0), true);
}
}
return _owner;
}
}
public SecurityIdentifier User
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return null;
if (_user == null)
{
using (SafeLocalAllocHandle tokenUser = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser))
{
_user = new SecurityIdentifier(tokenUser.Read<IntPtr>(0), true);
}
}
return _user;
}
}
public IdentityReferenceCollection Groups
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return null;
if (_groups == null)
{
IdentityReferenceCollection groups = new IdentityReferenceCollection();
using (SafeLocalAllocHandle pGroups = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups))
{
uint groupCount = pGroups.Read<uint>(0);
Interop.TOKEN_GROUPS tokenGroups = pGroups.Read<Interop.TOKEN_GROUPS>(0);
Interop.SID_AND_ATTRIBUTES[] groupDetails = new Interop.SID_AND_ATTRIBUTES[tokenGroups.GroupCount];
pGroups.ReadArray((uint)Marshal.OffsetOf<Interop.TOKEN_GROUPS>("Groups").ToInt32(),
groupDetails,
0,
groupDetails.Length);
foreach (Interop.SID_AND_ATTRIBUTES group in groupDetails)
{
// Ignore disabled, logon ID, and deny-only groups.
uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY;
if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED)
{
groups.Add(new SecurityIdentifier(group.Sid, true));
}
}
}
Interlocked.CompareExchange(ref _groups, groups, null);
}
return _groups;
}
}
public SafeAccessTokenHandle AccessToken
{
get
{
return _safeTokenHandle;
}
}
public virtual IntPtr Token
{
get
{
return _safeTokenHandle.DangerousGetHandle();
}
}
//
// Public methods.
//
public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
RunImpersonatedInternal(safeAccessTokenHandle, action);
}
public static T RunImpersonated<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<T> func)
{
if (func == null)
throw new ArgumentNullException(nameof(func));
T result = default(T);
RunImpersonatedInternal(safeAccessTokenHandle, () => result = func());
return result;
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_safeTokenHandle != null && !_safeTokenHandle.IsClosed)
_safeTokenHandle.Dispose();
}
_name = null;
_owner = null;
_user = null;
}
public void Dispose()
{
Dispose(true);
}
//
// internal.
//
private static AsyncLocal<SafeAccessTokenHandle> s_currentImpersonatedToken = new AsyncLocal<SafeAccessTokenHandle>(CurrentImpersonatedTokenChanged);
private static void RunImpersonatedInternal(SafeAccessTokenHandle token, Action action)
{
token = DuplicateAccessToken(token);
bool isImpersonating;
int hr;
SafeAccessTokenHandle previousToken = GetCurrentToken(TokenAccessLevels.MaximumAllowed, false, out isImpersonating, out hr);
if (previousToken == null || previousToken.IsInvalid)
throw new SecurityException(new Win32Exception(hr).Message);
s_currentImpersonatedToken.Value = isImpersonating ? previousToken : null;
ExecutionContext currentContext = ExecutionContext.Capture();
// Run everything else inside of ExecutionContext.Run, so that any EC changes will be undone
// on the way out.
ExecutionContext.Run(
currentContext,
delegate
{
if (!Interop.Advapi32.RevertToSelf())
Environment.FailFast(new Win32Exception().Message);
s_currentImpersonatedToken.Value = null;
if (!token.IsInvalid && !Interop.Advapi32.ImpersonateLoggedOnUser(token))
throw new SecurityException(SR.Argument_ImpersonateUser);
s_currentImpersonatedToken.Value = token;
action();
},
null);
}
private static void CurrentImpersonatedTokenChanged(AsyncLocalValueChangedArgs<SafeAccessTokenHandle> args)
{
if (!args.ThreadContextChanged)
return; // we handle explicit Value property changes elsewhere.
if (!Interop.Advapi32.RevertToSelf())
Environment.FailFast(new Win32Exception().Message);
if (args.CurrentValue != null && !args.CurrentValue.IsInvalid)
{
if (!Interop.Advapi32.ImpersonateLoggedOnUser(args.CurrentValue))
Environment.FailFast(new Win32Exception().Message);
}
}
internal static WindowsIdentity GetCurrentInternal(TokenAccessLevels desiredAccess, bool threadOnly)
{
int hr = 0;
bool isImpersonating;
SafeAccessTokenHandle safeTokenHandle = GetCurrentToken(desiredAccess, threadOnly, out isImpersonating, out hr);
if (safeTokenHandle == null || safeTokenHandle.IsInvalid)
{
// either we wanted only ThreadToken - return null
if (threadOnly && !isImpersonating)
return null;
// or there was an error
throw new SecurityException(new Win32Exception(hr).Message);
}
WindowsIdentity wi = new WindowsIdentity();
wi._safeTokenHandle.Dispose();
wi._safeTokenHandle = safeTokenHandle;
return wi;
}
//
// private.
//
private static int GetHRForWin32Error(int dwLastError)
{
if ((dwLastError & 0x80000000) == 0x80000000)
return dwLastError;
else
return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000);
}
private static Exception GetExceptionFromNtStatus(int status)
{
if ((uint)status == Interop.StatusOptions.STATUS_ACCESS_DENIED)
return new UnauthorizedAccessException();
if ((uint)status == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES || (uint)status == Interop.StatusOptions.STATUS_NO_MEMORY)
return new OutOfMemoryException();
uint win32ErrorCode = Interop.Advapi32.LsaNtStatusToWinError((uint)status);
return new SecurityException(new Win32Exception(unchecked((int)win32ErrorCode)).Message);
}
private static SafeAccessTokenHandle GetCurrentToken(TokenAccessLevels desiredAccess, bool threadOnly, out bool isImpersonating, out int hr)
{
isImpersonating = true;
SafeAccessTokenHandle safeTokenHandle;
hr = 0;
bool success = Interop.Advapi32.OpenThreadToken(desiredAccess, WinSecurityContext.Both, out safeTokenHandle);
if (!success)
hr = Marshal.GetHRForLastWin32Error();
if (!success && hr == GetHRForWin32Error(Interop.Errors.ERROR_NO_TOKEN))
{
// No impersonation
isImpersonating = false;
if (!threadOnly)
safeTokenHandle = GetCurrentProcessToken(desiredAccess, out hr);
}
return safeTokenHandle;
}
private static SafeAccessTokenHandle GetCurrentProcessToken(TokenAccessLevels desiredAccess, out int hr)
{
hr = 0;
SafeAccessTokenHandle safeTokenHandle;
if (!Interop.Advapi32.OpenProcessToken(Interop.Kernel32.GetCurrentProcess(), desiredAccess, out safeTokenHandle))
hr = GetHRForWin32Error(Marshal.GetLastWin32Error());
return safeTokenHandle;
}
/// <summary>
/// Get a property from the current token
/// </summary>
private T GetTokenInformation<T>(TokenInformationClass tokenInformationClass) where T : struct
{
Debug.Assert(!_safeTokenHandle.IsInvalid && !_safeTokenHandle.IsClosed, "!m_safeTokenHandle.IsInvalid && !m_safeTokenHandle.IsClosed");
using (SafeLocalAllocHandle information = GetTokenInformation(_safeTokenHandle, tokenInformationClass))
{
Debug.Assert(information.ByteLength >= (ulong)Marshal.SizeOf<T>(),
"information.ByteLength >= (ulong)Marshal.SizeOf(typeof(T))");
return information.Read<T>(0);
}
}
private static Interop.LUID GetLogonAuthId(SafeAccessTokenHandle safeTokenHandle)
{
using (SafeLocalAllocHandle pStatistics = GetTokenInformation(safeTokenHandle, TokenInformationClass.TokenStatistics))
{
Interop.TOKEN_STATISTICS statistics = pStatistics.Read<Interop.TOKEN_STATISTICS>(0);
return statistics.AuthenticationId;
}
}
private static SafeLocalAllocHandle GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass, bool nullOnInvalidParam = false)
{
SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle;
uint dwLength = (uint)sizeof(uint);
bool result = Interop.Advapi32.GetTokenInformation(tokenHandle,
(uint)tokenInformationClass,
safeLocalAllocHandle,
0,
out dwLength);
int dwErrorCode = Marshal.GetLastWin32Error();
switch (dwErrorCode)
{
case Interop.Errors.ERROR_BAD_LENGTH:
// special case for TokenSessionId. Falling through
case Interop.Errors.ERROR_INSUFFICIENT_BUFFER:
// ptrLength is an [In] param to LocalAlloc
UIntPtr ptrLength = new UIntPtr(dwLength);
safeLocalAllocHandle.Dispose();
safeLocalAllocHandle = Interop.Kernel32.LocalAlloc(0, ptrLength);
if (safeLocalAllocHandle == null || safeLocalAllocHandle.IsInvalid)
throw new OutOfMemoryException();
safeLocalAllocHandle.Initialize(dwLength);
result = Interop.Advapi32.GetTokenInformation(tokenHandle,
(uint)tokenInformationClass,
safeLocalAllocHandle,
dwLength,
out dwLength);
if (!result)
throw new SecurityException(new Win32Exception().Message);
break;
case Interop.Errors.ERROR_INVALID_HANDLE:
throw new ArgumentException(SR.Argument_InvalidImpersonationToken);
case Interop.Errors.ERROR_INVALID_PARAMETER:
if (nullOnInvalidParam)
{
safeLocalAllocHandle.Dispose();
return null;
}
// Throw the exception.
goto default;
default:
throw new SecurityException(new Win32Exception(dwErrorCode).Message);
}
return safeLocalAllocHandle;
}
private static string GetAuthType(WindowsIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
return identity._authType;
}
/// <summary>
/// Returns a new instance of <see cref="WindowsIdentity"/> with values copied from this object.
/// </summary>
public override ClaimsIdentity Clone()
{
return new WindowsIdentity(this);
}
/// <summary>
/// Gets the 'User Claims' from the NTToken that represents this identity
/// </summary>
public virtual IEnumerable<Claim> UserClaims
{
get
{
InitializeClaims();
return _userClaims.ToArray();
}
}
/// <summary>
/// Gets the 'Device Claims' from the NTToken that represents the device the identity is using
/// </summary>
public virtual IEnumerable<Claim> DeviceClaims
{
get
{
InitializeClaims();
return _deviceClaims.ToArray();
}
}
/// <summary>
/// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="WindowsIdentity"/>.
/// Includes UserClaims and DeviceClaims.
/// </summary>
public override IEnumerable<Claim> Claims
{
get
{
if (!_claimsInitialized)
{
InitializeClaims();
}
foreach (Claim claim in base.Claims)
yield return claim;
foreach (Claim claim in _userClaims)
yield return claim;
foreach (Claim claim in _deviceClaims)
yield return claim;
}
}
/// <summary>
/// Internal method to initialize the claim collection.
/// Lazy init is used so claims are not initialized until needed
/// </summary>
private void InitializeClaims()
{
if (!_claimsInitialized)
{
lock (_claimsIntiailizedLock)
{
if (!_claimsInitialized)
{
_userClaims = new List<Claim>();
_deviceClaims = new List<Claim>();
if (!string.IsNullOrEmpty(Name))
{
//
// Add the name claim only if the WindowsIdentity.Name is populated
// WindowsIdentity.Name will be null when it is the fake anonymous user
// with a token value of IntPtr.Zero
//
_userClaims.Add(new Claim(NameClaimType, Name, ClaimValueTypes.String, _issuerName, _issuerName, this));
}
// primary sid
AddPrimarySidClaim(_userClaims);
// group sids
AddGroupSidClaims(_userClaims);
if (!s_ignoreWindows8Properties)
{
// Device group sids (may cause s_ignoreWindows8Properties to be set to true, so must be first in this block)
AddDeviceGroupSidClaims(_deviceClaims, TokenInformationClass.TokenDeviceGroups);
if (!s_ignoreWindows8Properties)
{
// User token claims
AddTokenClaims(_userClaims, TokenInformationClass.TokenUserClaimAttributes, ClaimTypes.WindowsUserClaim);
// Device token claims
AddTokenClaims(_deviceClaims, TokenInformationClass.TokenDeviceClaimAttributes, ClaimTypes.WindowsDeviceClaim);
}
}
_claimsInitialized = true;
}
}
}
}
/// <summary>
/// Creates a collection of SID claims that represent the users groups.
/// </summary>
private void AddGroupSidClaims(List<Claim> instanceClaims)
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return;
SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle;
SafeLocalAllocHandle safeAllocHandlePrimaryGroup = SafeLocalAllocHandle.InvalidHandle;
try
{
// Retrieve the primary group sid
safeAllocHandlePrimaryGroup = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenPrimaryGroup);
Interop.TOKEN_PRIMARY_GROUP primaryGroup = (Interop.TOKEN_PRIMARY_GROUP)Marshal.PtrToStructure<Interop.TOKEN_PRIMARY_GROUP>(safeAllocHandlePrimaryGroup.DangerousGetHandle());
SecurityIdentifier primaryGroupSid = new SecurityIdentifier(primaryGroup.PrimaryGroup, true);
// only add one primary group sid
bool foundPrimaryGroupSid = false;
// Retrieve all group sids, primary group sid is one of them
safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups);
int count = Marshal.ReadInt32(safeAllocHandle.DangerousGetHandle());
IntPtr pSidAndAttributes = new IntPtr((long)safeAllocHandle.DangerousGetHandle() + (long)Marshal.OffsetOf<Interop.TOKEN_GROUPS>("Groups"));
Claim claim;
for (int i = 0; i < count; ++i)
{
Interop.SID_AND_ATTRIBUTES group = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure<Interop.SID_AND_ATTRIBUTES>(pSidAndAttributes);
uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY;
SecurityIdentifier groupSid = new SecurityIdentifier(group.Sid, true);
if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED)
{
if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value))
{
claim = new Claim(ClaimTypes.PrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
foundPrimaryGroupSid = true;
}
//Primary group sid generates both regular groupsid claim and primary groupsid claim
claim = new Claim(ClaimTypes.GroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
}
else if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY)
{
if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value))
{
claim = new Claim(ClaimTypes.DenyOnlyPrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
foundPrimaryGroupSid = true;
}
//Primary group sid generates both regular groupsid claim and primary groupsid claim
claim = new Claim(ClaimTypes.DenyOnlySid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
}
pSidAndAttributes = new IntPtr((long)pSidAndAttributes + Marshal.SizeOf<Interop.SID_AND_ATTRIBUTES>());
}
}
finally
{
safeAllocHandle.Dispose();
safeAllocHandlePrimaryGroup.Dispose();
}
}
/// <summary>
/// Creates a Windows SID Claim and adds to collection of claims.
/// </summary>
private void AddPrimarySidClaim(List<Claim> instanceClaims)
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return;
SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle;
try
{
safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser);
Interop.SID_AND_ATTRIBUTES user = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure<Interop.SID_AND_ATTRIBUTES>(safeAllocHandle.DangerousGetHandle());
uint mask = Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY;
SecurityIdentifier sid = new SecurityIdentifier(user.Sid, true);
Claim claim;
if (user.Attributes == 0)
{
claim = new Claim(ClaimTypes.PrimarySid, sid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, sid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
}
else if ((user.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY)
{
claim = new Claim(ClaimTypes.DenyOnlyPrimarySid, sid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, sid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
}
}
finally
{
safeAllocHandle.Dispose();
}
}
private void AddDeviceGroupSidClaims(List<Claim> instanceClaims, TokenInformationClass tokenInformationClass)
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return;
SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle;
try
{
// Retrieve all group sids
safeAllocHandle = GetTokenInformation(_safeTokenHandle, tokenInformationClass, nullOnInvalidParam: true);
if (safeAllocHandle == null)
{
s_ignoreWindows8Properties = true;
return;
}
int count = Marshal.ReadInt32(safeAllocHandle.DangerousGetHandle());
IntPtr pSidAndAttributes = new IntPtr((long)safeAllocHandle.DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(Interop.TOKEN_GROUPS), "Groups"));
string claimType = null;
for (int i = 0; i < count; ++i)
{
Interop.SID_AND_ATTRIBUTES group = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure(pSidAndAttributes, typeof(Interop.SID_AND_ATTRIBUTES));
uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY;
SecurityIdentifier groupSid = new SecurityIdentifier(group.Sid, true);
if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED)
{
claimType = ClaimTypes.WindowsDeviceGroup;
Claim claim = new Claim(claimType, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, Convert.ToString(groupSid.IdentifierAuthority, CultureInfo.InvariantCulture));
claim.Properties.Add(claimType, "");
instanceClaims.Add(claim);
}
else if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY)
{
claimType = ClaimTypes.DenyOnlyWindowsDeviceGroup;
Claim claim = new Claim(claimType, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, Convert.ToString(groupSid.IdentifierAuthority, CultureInfo.InvariantCulture));
claim.Properties.Add(claimType, "");
instanceClaims.Add(claim);
}
pSidAndAttributes = new IntPtr((long)pSidAndAttributes + Marshal.SizeOf<Interop.SID_AND_ATTRIBUTES>());
}
}
finally
{
safeAllocHandle?.Close();
}
}
private void AddTokenClaims(List<Claim> instanceClaims, TokenInformationClass tokenInformationClass, string propertyValue)
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return;
SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle;
try
{
safeAllocHandle = GetTokenInformation(_safeTokenHandle, tokenInformationClass);
Interop.CLAIM_SECURITY_ATTRIBUTES_INFORMATION claimAttributes = (Interop.CLAIM_SECURITY_ATTRIBUTES_INFORMATION)Marshal.PtrToStructure(safeAllocHandle.DangerousGetHandle(), typeof(Interop.CLAIM_SECURITY_ATTRIBUTES_INFORMATION));
// An attribute represents a collection of claims. Inside each attribute a claim can be multivalued, we create a claim for each value.
// It is a ragged multi-dimentional array, where each cell can be of different lenghts.
// index into array of claims.
long offset = 0;
for (int attribute = 0; attribute < claimAttributes.AttributeCount; attribute++)
{
IntPtr pAttribute = new IntPtr(claimAttributes.Attribute.pAttributeV1.ToInt64() + offset);
Interop.CLAIM_SECURITY_ATTRIBUTE_V1 windowsClaim = (Interop.CLAIM_SECURITY_ATTRIBUTE_V1)Marshal.PtrToStructure(pAttribute, typeof(Interop.CLAIM_SECURITY_ATTRIBUTE_V1));
// the switch was written this way, which appears to have multiple for loops, because each item in the ValueCount is of the same ValueType. This saves the type check each item.
switch (windowsClaim.ValueType)
{
case Interop.ClaimSecurityAttributeType.CLAIM_SECURITY_ATTRIBUTE_TYPE_STRING:
IntPtr[] stringPointers = new IntPtr[windowsClaim.ValueCount];
Marshal.Copy(windowsClaim.Values.ppString, stringPointers, 0, (int)windowsClaim.ValueCount);
for (int item = 0; item < windowsClaim.ValueCount; item++)
{
Claim c = new Claim(windowsClaim.Name, Marshal.PtrToStringAuto(stringPointers[item]), ClaimValueTypes.String, _issuerName, _issuerName, this);
c.Properties.Add(propertyValue, string.Empty);
instanceClaims.Add(c);
}
break;
case Interop.ClaimSecurityAttributeType.CLAIM_SECURITY_ATTRIBUTE_TYPE_INT64:
long[] intValues = new long[windowsClaim.ValueCount];
Marshal.Copy(windowsClaim.Values.pInt64, intValues, 0, (int)windowsClaim.ValueCount);
for (int item = 0; item < windowsClaim.ValueCount; item++)
{
Claim c = new Claim(windowsClaim.Name, Convert.ToString(intValues[item], CultureInfo.InvariantCulture), ClaimValueTypes.Integer64, _issuerName, _issuerName, this);
c.Properties.Add(propertyValue, string.Empty);
instanceClaims.Add(c);
}
break;
case Interop.ClaimSecurityAttributeType.CLAIM_SECURITY_ATTRIBUTE_TYPE_UINT64:
long[] uintValues = new long[windowsClaim.ValueCount];
Marshal.Copy(windowsClaim.Values.pUint64, uintValues, 0, (int)windowsClaim.ValueCount);
for (int item = 0; item < windowsClaim.ValueCount; item++)
{
Claim c = new Claim(windowsClaim.Name, Convert.ToString((ulong)uintValues[item], CultureInfo.InvariantCulture), ClaimValueTypes.UInteger64, _issuerName, _issuerName, this);
c.Properties.Add(propertyValue, string.Empty);
instanceClaims.Add(c);
}
break;
case Interop.ClaimSecurityAttributeType.CLAIM_SECURITY_ATTRIBUTE_TYPE_BOOLEAN:
long[] boolValues = new long[windowsClaim.ValueCount];
Marshal.Copy(windowsClaim.Values.pUint64, boolValues, 0, (int)windowsClaim.ValueCount);
for (int item = 0; item < windowsClaim.ValueCount; item++)
{
Claim c = new Claim(
windowsClaim.Name,
((ulong)boolValues[item] != 0).ToString(),
ClaimValueTypes.Boolean,
_issuerName,
_issuerName,
this);
c.Properties.Add(propertyValue, string.Empty);
instanceClaims.Add(c);
}
break;
}
offset += Marshal.SizeOf(windowsClaim);
}
}
finally
{
safeAllocHandle.Close();
}
}
}
internal enum WinSecurityContext
{
Thread = 1, // OpenAsSelf = false
Process = 2, // OpenAsSelf = true
Both = 3 // OpenAsSelf = true, then OpenAsSelf = false
}
internal enum TokenType : int
{
TokenPrimary = 1,
TokenImpersonation
}
internal enum TokenInformationClass : int
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUIAccess,
TokenMandatoryPolicy,
TokenLogonSid,
TokenIsAppContainer,
TokenCapabilities,
TokenAppContainerSid,
TokenAppContainerNumber,
TokenUserClaimAttributes,
TokenDeviceClaimAttributes,
TokenRestrictedUserClaimAttributes,
TokenRestrictedDeviceClaimAttributes,
TokenDeviceGroups,
TokenRestrictedDeviceGroups,
MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
#if !MONO
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace TheArtOfDev.HtmlRenderer.WinForms.Utilities
{
/// <summary>
/// Utility for Win32 API.
/// </summary>
internal static class Win32Utils
{
public const int WsBorder = 0x00800000;
public const int WsExClientEdge = 0x200;
/// <summary>
/// Const for BitBlt copy raster-operation code.
/// </summary>
public const int BitBltCopy = 0x00CC0020;
/// <summary>
/// Const for BitBlt paint raster-operation code.
/// </summary>
public const int BitBltPaint = 0x00EE0086;
public const int WmSetCursor = 0x20;
public const int IdcHand = 32649;
public const int TextAlignDefault = 0;
public const int TextAlignRtl = 256;
public const int TextAlignBaseline = 24;
public const int TextAlignBaselineRtl = 256 + 24;
[DllImport("user32.dll")]
public static extern int SetCursor(int hCursor);
[DllImport("user32.dll")]
public static extern int LoadCursor(int hInstance, int lpCursorName);
/// <summary>
/// Create a compatible memory HDC from the given HDC.<br/>
/// The memory HDC can be rendered into without effecting the original HDC.<br/>
/// The returned memory HDC and <paramref name="dib"/> must be released using <see cref="ReleaseMemoryHdc"/>.
/// </summary>
/// <param name="hdc">the HDC to create memory HDC from</param>
/// <param name="width">the width of the memory HDC to create</param>
/// <param name="height">the height of the memory HDC to create</param>
/// <param name="dib">returns used bitmap memory section that must be released when done with memory HDC</param>
/// <returns>memory HDC</returns>
public static IntPtr CreateMemoryHdc(IntPtr hdc, int width, int height, out IntPtr dib)
{
// Create a memory DC so we can work off-screen
IntPtr memoryHdc = CreateCompatibleDC(hdc);
SetBkMode(memoryHdc, 1);
// Create a device-independent bitmap and select it into our DC
var info = new BitMapInfo();
info.biSize = Marshal.SizeOf(info);
info.biWidth = width;
info.biHeight = -height;
info.biPlanes = 1;
info.biBitCount = 32;
info.biCompression = 0; // BI_RGB
IntPtr ppvBits;
dib = CreateDIBSection(hdc, ref info, 0, out ppvBits, IntPtr.Zero, 0);
SelectObject(memoryHdc, dib);
return memoryHdc;
}
/// <summary>
/// Release the given memory HDC and dib section created from <see cref="CreateMemoryHdc"/>.
/// </summary>
/// <param name="memoryHdc">Memory HDC to release</param>
/// <param name="dib">bitmap section to release</param>
public static void ReleaseMemoryHdc(IntPtr memoryHdc, IntPtr dib)
{
DeleteObject(dib);
DeleteDC(memoryHdc);
}
[DllImport("user32.dll")]
public static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr WindowFromDC(IntPtr hdc);
/// <summary>
/// Retrieves the dimensions of the bounding rectangle of the specified window. The dimensions are given in screen coordinates that are relative to the upper-left corner of the screen.
/// </summary>
/// <remarks>
/// In conformance with conventions for the RECT structure, the bottom-right coordinates of the returned rectangle are exclusive. In other words,
/// the pixel at (right, bottom) lies immediately outside the rectangle.
/// </remarks>
/// <param name="hWnd">A handle to the window.</param>
/// <param name="lpRect">A pointer to a RECT structure that receives the screen coordinates of the upper-left and lower-right corners of the window.</param>
/// <returns>If the function succeeds, the return value is nonzero.</returns>
[DllImport("User32", SetLastError = true)]
public static extern int GetWindowRect(IntPtr hWnd, out Rectangle lpRect);
/// <summary>
/// Retrieves the dimensions of the bounding rectangle of the specified window. The dimensions are given in screen coordinates that are relative to the upper-left corner of the screen.
/// </summary>
/// <remarks>
/// In conformance with conventions for the RECT structure, the bottom-right coordinates of the returned rectangle are exclusive. In other words,
/// the pixel at (right, bottom) lies immediately outside the rectangle.
/// </remarks>
/// <param name="handle">A handle to the window.</param>
/// <returns>RECT structure that receives the screen coordinates of the upper-left and lower-right corners of the window.</returns>
public static Rectangle GetWindowRectangle(IntPtr handle)
{
Rectangle rect;
GetWindowRect(handle, out rect);
return new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
}
[DllImport("User32.dll")]
public static extern bool MoveWindow(IntPtr handle, int x, int y, int width, int height, bool redraw);
[DllImport("gdi32.dll")]
public static extern int SetTextAlign(IntPtr hdc, uint fMode);
[DllImport("gdi32.dll")]
public static extern int SetBkMode(IntPtr hdc, int mode);
[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiObj);
[DllImport("gdi32.dll")]
public static extern uint SetTextColor(IntPtr hdc, int color);
[DllImport("gdi32.dll", CharSet = CharSet.Unicode)]
public static extern bool GetTextMetrics(IntPtr hdc, out TextMetric lptm);
[DllImport("gdi32.dll", EntryPoint = "GetTextExtentPoint32W", CharSet = CharSet.Unicode)]
public static extern int GetTextExtentPoint32(IntPtr hdc, [MarshalAs(UnmanagedType.LPWStr)] string str, int len, ref Size size);
[DllImport("gdi32.dll", EntryPoint = "GetTextExtentExPointW", CharSet = CharSet.Unicode)]
public static extern bool GetTextExtentExPoint(IntPtr hDc, [MarshalAs(UnmanagedType.LPWStr)] string str, int nLength, int nMaxExtent, int[] lpnFit, int[] alpDx, ref Size size);
[DllImport("gdi32.dll", EntryPoint = "TextOutW", CharSet = CharSet.Unicode)]
public static extern bool TextOut(IntPtr hdc, int x, int y, [MarshalAs(UnmanagedType.LPWStr)] string str, int len);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);
[DllImport("gdi32.dll")]
public static extern int GetClipBox(IntPtr hdc, out Rectangle lprc);
[DllImport("gdi32.dll")]
public static extern int SelectClipRgn(IntPtr hdc, IntPtr hrgn);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop);
[DllImport("gdi32.dll", EntryPoint = "GdiAlphaBlend")]
public static extern bool AlphaBlend(IntPtr hdcDest, int nXOriginDest, int nYOriginDest, int nWidthDest, int nHeightDest, IntPtr hdcSrc, int nXOriginSrc, int nYOriginSrc, int nWidthSrc, int nHeightSrc, BlendFunction blendFunction);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern bool DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateDIBSection(IntPtr hdc, [In] ref BitMapInfo pbmi, uint iUsage, out IntPtr ppvBits, IntPtr hSection, uint dwOffset);
}
[StructLayout(LayoutKind.Sequential)]
internal struct BlendFunction
{
public byte BlendOp;
public byte BlendFlags;
public byte SourceConstantAlpha;
public byte AlphaFormat;
public BlendFunction(byte alpha)
{
BlendOp = 0;
BlendFlags = 0;
AlphaFormat = 0;
SourceConstantAlpha = alpha;
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct BitMapInfo
{
public int biSize;
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;
public byte bmiColors_rgbBlue;
public byte bmiColors_rgbGreen;
public byte bmiColors_rgbRed;
public byte bmiColors_rgbReserved;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct TextMetric
{
public int tmHeight;
public int tmAscent;
public int tmDescent;
public int tmInternalLeading;
public int tmExternalLeading;
public int tmAveCharWidth;
public int tmMaxCharWidth;
public int tmWeight;
public int tmOverhang;
public int tmDigitizedAspectX;
public int tmDigitizedAspectY;
public char tmFirstChar;
public char tmLastChar;
public char tmDefaultChar;
public char tmBreakChar;
public byte tmItalic;
public byte tmUnderlined;
public byte tmStruckOut;
public byte tmPitchAndFamily;
public byte tmCharSet;
}
}
#endif
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions;
using osu.Framework.Extensions.ExceptionExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.Multiplayer;
using osu.Game.Online.Rooms;
using osu.Game.Overlays;
using osu.Game.Rulesets;
using osu.Game.Screens.OnlinePlay.Match.Components;
using osuTK;
namespace osu.Game.Screens.OnlinePlay.Multiplayer.Match
{
public class MultiplayerMatchSettingsOverlay : RoomSettingsOverlay
{
private MatchSettings settings;
protected override OsuButton SubmitButton => settings.ApplyButton;
[Resolved]
private OngoingOperationTracker ongoingOperationTracker { get; set; }
protected override bool IsLoading => ongoingOperationTracker.InProgress.Value;
public MultiplayerMatchSettingsOverlay(Room room)
: base(room)
{
}
protected override void SelectBeatmap() => settings.SelectBeatmap();
protected override OnlinePlayComposite CreateSettings(Room room) => settings = new MatchSettings(room)
{
RelativeSizeAxes = Axes.Both,
RelativePositionAxes = Axes.Y,
SettingsApplied = Hide
};
protected class MatchSettings : OnlinePlayComposite
{
private const float disabled_alpha = 0.2f;
public Action SettingsApplied;
public OsuTextBox NameField, MaxParticipantsField;
public RoomAvailabilityPicker AvailabilityPicker;
public MatchTypePicker TypePicker;
public OsuEnumDropdown<QueueMode> QueueModeDropdown;
public OsuTextBox PasswordTextBox;
public TriangleButton ApplyButton;
public OsuSpriteText ErrorText;
private OsuSpriteText typeLabel;
private LoadingLayer loadingLayer;
public void SelectBeatmap()
{
if (matchSubScreen.IsCurrentScreen())
matchSubScreen.Push(new MultiplayerMatchSongSelect(matchSubScreen.Room));
}
[Resolved]
private MultiplayerMatchSubScreen matchSubScreen { get; set; }
[Resolved]
private IRoomManager manager { get; set; }
[Resolved]
private MultiplayerClient client { get; set; }
[Resolved]
private Bindable<WorkingBeatmap> beatmap { get; set; }
[Resolved]
private Bindable<RulesetInfo> ruleset { get; set; }
[Resolved]
private OngoingOperationTracker ongoingOperationTracker { get; set; }
private readonly IBindable<bool> operationInProgress = new BindableBool();
[CanBeNull]
private IDisposable applyingSettingsOperation;
private readonly Room room;
private Drawable playlistContainer;
private DrawableRoomPlaylist drawablePlaylist;
public MatchSettings(Room room)
{
this.room = room;
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider, OsuColour colours)
{
InternalChildren = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colourProvider.Background4
},
new GridContainer
{
RelativeSizeAxes = Axes.Both,
RowDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
},
Content = new[]
{
new Drawable[]
{
new OsuScrollContainer
{
Padding = new MarginPadding
{
Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING,
Vertical = 10
},
RelativeSizeAxes = Axes.Both,
Children = new[]
{
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 10),
Children = new[]
{
new Container
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Padding = new MarginPadding { Horizontal = WaveOverlayContainer.WIDTH_PADDING },
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new SectionContainer
{
Padding = new MarginPadding { Right = FIELD_PADDING / 2 },
Children = new[]
{
new Section("Room name")
{
Child = NameField = new OsuTextBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
LengthLimit = 100,
},
},
new Section("Room visibility")
{
Alpha = disabled_alpha,
Child = AvailabilityPicker = new RoomAvailabilityPicker
{
Enabled = { Value = false }
},
},
new Section("Game type")
{
Child = new FillFlowContainer
{
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
Direction = FillDirection.Vertical,
Spacing = new Vector2(7),
Children = new Drawable[]
{
TypePicker = new MatchTypePicker
{
RelativeSizeAxes = Axes.X,
},
typeLabel = new OsuSpriteText
{
Font = OsuFont.GetFont(size: 14),
Colour = colours.Yellow
},
},
},
},
new Section("Queue mode")
{
Child = new Container
{
RelativeSizeAxes = Axes.X,
Height = 40,
Child = QueueModeDropdown = new OsuEnumDropdown<QueueMode>
{
RelativeSizeAxes = Axes.X
}
}
}
},
},
new SectionContainer
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Padding = new MarginPadding { Left = FIELD_PADDING / 2 },
Children = new[]
{
new Section("Max participants")
{
Alpha = disabled_alpha,
Child = MaxParticipantsField = new OsuNumberBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
ReadOnly = true,
},
},
new Section("Password (optional)")
{
Child = PasswordTextBox = new OsuPasswordTextBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
LengthLimit = 255,
},
},
}
}
},
},
playlistContainer = new FillFlowContainer
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Width = 0.5f,
Depth = float.MaxValue,
Spacing = new Vector2(5),
Children = new Drawable[]
{
drawablePlaylist = new DrawableRoomPlaylist(false, false)
{
RelativeSizeAxes = Axes.X,
Height = DrawableRoomPlaylistItem.HEIGHT
},
new PurpleTriangleButton
{
RelativeSizeAxes = Axes.X,
Height = 40,
Text = "Select beatmap",
Action = SelectBeatmap
}
}
}
}
}
},
},
},
new Drawable[]
{
new Container
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Y = 2,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colourProvider.Background5
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 20),
Margin = new MarginPadding { Vertical = 20 },
Padding = new MarginPadding { Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING },
Children = new Drawable[]
{
ApplyButton = new CreateOrUpdateButton
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
Size = new Vector2(230, 55),
Enabled = { Value = false },
Action = apply,
},
ErrorText = new OsuSpriteText
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
Alpha = 0,
Depth = 1,
Colour = colours.RedDark
}
}
}
}
}
}
}
},
loadingLayer = new LoadingLayer(true)
};
TypePicker.Current.BindValueChanged(type => typeLabel.Text = type.NewValue.GetLocalisableDescription(), true);
RoomName.BindValueChanged(name => NameField.Text = name.NewValue, true);
Availability.BindValueChanged(availability => AvailabilityPicker.Current.Value = availability.NewValue, true);
Type.BindValueChanged(type => TypePicker.Current.Value = type.NewValue, true);
MaxParticipants.BindValueChanged(count => MaxParticipantsField.Text = count.NewValue?.ToString(), true);
RoomID.BindValueChanged(roomId => playlistContainer.Alpha = roomId.NewValue == null ? 1 : 0, true);
Password.BindValueChanged(password => PasswordTextBox.Text = password.NewValue ?? string.Empty, true);
QueueMode.BindValueChanged(mode => QueueModeDropdown.Current.Value = mode.NewValue, true);
operationInProgress.BindTo(ongoingOperationTracker.InProgress);
operationInProgress.BindValueChanged(v =>
{
if (v.NewValue)
loadingLayer.Show();
else
loadingLayer.Hide();
});
}
protected override void LoadComplete()
{
base.LoadComplete();
drawablePlaylist.Items.BindTo(Playlist);
drawablePlaylist.SelectedItem.BindTo(SelectedItem);
}
protected override void Update()
{
base.Update();
ApplyButton.Enabled.Value = Playlist.Count > 0 && NameField.Text.Length > 0 && !operationInProgress.Value;
}
private void apply()
{
if (!ApplyButton.Enabled.Value)
return;
hideError();
Debug.Assert(applyingSettingsOperation == null);
applyingSettingsOperation = ongoingOperationTracker.BeginOperation();
// If the client is already in a room, update via the client.
// Otherwise, update the room directly in preparation for it to be submitted to the API on match creation.
if (client.Room != null)
{
client.ChangeSettings(
name: NameField.Text,
password: PasswordTextBox.Text,
matchType: TypePicker.Current.Value,
queueMode: QueueModeDropdown.Current.Value)
.ContinueWith(t => Schedule(() =>
{
if (t.IsCompletedSuccessfully)
onSuccess(room);
else
onError(t.Exception?.AsSingular().Message ?? "Error changing settings.");
}));
}
else
{
room.Name.Value = NameField.Text;
room.Availability.Value = AvailabilityPicker.Current.Value;
room.Type.Value = TypePicker.Current.Value;
room.Password.Value = PasswordTextBox.Current.Value;
room.QueueMode.Value = QueueModeDropdown.Current.Value;
if (int.TryParse(MaxParticipantsField.Text, out int max))
room.MaxParticipants.Value = max;
else
room.MaxParticipants.Value = null;
manager?.CreateRoom(room, onSuccess, onError);
}
}
private void hideError() => ErrorText.FadeOut(50);
private void onSuccess(Room room)
{
Debug.Assert(applyingSettingsOperation != null);
SettingsApplied?.Invoke();
applyingSettingsOperation.Dispose();
applyingSettingsOperation = null;
}
private void onError(string text)
{
Debug.Assert(applyingSettingsOperation != null);
// see https://github.com/ppy/osu-web/blob/2c97aaeb64fb4ed97c747d8383a35b30f57428c7/app/Models/Multiplayer/PlaylistItem.php#L48.
const string not_found_prefix = "beatmaps not found:";
if (text.StartsWith(not_found_prefix, StringComparison.Ordinal))
{
ErrorText.Text = "The selected beatmap is not available online.";
SelectedItem.Value.MarkInvalid();
}
else
{
ErrorText.Text = text;
}
ErrorText.FadeIn(50);
applyingSettingsOperation.Dispose();
applyingSettingsOperation = null;
}
}
public class CreateOrUpdateButton : TriangleButton
{
[Resolved(typeof(Room), nameof(Room.RoomID))]
private Bindable<long?> roomId { get; set; }
protected override void LoadComplete()
{
base.LoadComplete();
roomId.BindValueChanged(id => Text = id.NewValue == null ? "Create" : "Update", true);
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
BackgroundColour = colours.Yellow;
Triangles.ColourLight = colours.YellowLight;
Triangles.ColourDark = colours.YellowDark;
}
}
}
}
| |
/*
* 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.Xml.Serialization;
using OpenMetaverse;
namespace OpenSim.Framework
{
/// <summary>
/// Asset class. All Assets are reference by this class or a class derived from this class
/// </summary>
[Serializable]
public class AssetBase
{
/// <summary>
/// Data of the Asset
/// </summary>
private byte[] m_data;
/// <summary>
/// Meta Data of the Asset
/// </summary>
private AssetMetadata m_metadata;
public AssetBase()
{
m_metadata = new AssetMetadata();
}
public AssetBase(UUID assetId, string name)
{
m_metadata = new AssetMetadata();
m_metadata.FullID = assetId;
m_metadata.Name = name;
}
public bool ContainsReferences
{
get
{
return
IsTextualAsset && (
Type != (sbyte)AssetType.Notecard
&& Type != (sbyte)AssetType.CallingCard
&& Type != (sbyte)AssetType.LSLText
&& Type != (sbyte)AssetType.Landmark);
}
}
public bool IsTextualAsset
{
get
{
return !IsBinaryAsset;
}
}
/// <summary>
/// Checks if this asset is a binary or text asset
/// </summary>
public bool IsBinaryAsset
{
get
{
return
(Type == (sbyte) AssetType.Animation ||
Type == (sbyte)AssetType.Gesture ||
Type == (sbyte)AssetType.Simstate ||
Type == (sbyte)AssetType.Unknown ||
Type == (sbyte)AssetType.Object ||
Type == (sbyte)AssetType.Sound ||
Type == (sbyte)AssetType.SoundWAV ||
Type == (sbyte)AssetType.Texture ||
Type == (sbyte)AssetType.TextureTGA ||
Type == (sbyte)AssetType.Folder ||
Type == (sbyte)AssetType.RootFolder ||
Type == (sbyte)AssetType.LostAndFoundFolder ||
Type == (sbyte)AssetType.SnapshotFolder ||
Type == (sbyte)AssetType.TrashFolder ||
Type == (sbyte)AssetType.ImageJPEG ||
Type == (sbyte) AssetType.ImageTGA ||
Type == (sbyte) AssetType.LSLBytecode);
}
}
public virtual byte[] Data
{
get { return m_data; }
set { m_data = value; }
}
/// <summary>
/// Asset UUID
/// </summary>
public UUID FullID
{
get { return m_metadata.FullID; }
set { m_metadata.FullID = value; }
}
/// <summary>
/// Asset MetaData ID (transferring from UUID to string ID)
/// </summary>
public string ID
{
get { return m_metadata.ID; }
set { m_metadata.ID = value; }
}
public string Name
{
get { return m_metadata.Name; }
set { m_metadata.Name = value; }
}
public string Description
{
get { return m_metadata.Description; }
set { m_metadata.Description = value; }
}
/// <summary>
/// (sbyte) AssetType enum
/// </summary>
public sbyte Type
{
get { return m_metadata.Type; }
set { m_metadata.Type = value; }
}
/// <summary>
/// Is this a region only asset, or does this exist on the asset server also
/// </summary>
public bool Local
{
get { return m_metadata.Local; }
set { m_metadata.Local = value; }
}
/// <summary>
/// Is this asset going to be saved to the asset database?
/// </summary>
public bool Temporary
{
get { return m_metadata.Temporary; }
set { m_metadata.Temporary = value; }
}
[XmlIgnore]
public AssetMetadata Metadata
{
get { return m_metadata; }
set { m_metadata = value; }
}
public override string ToString()
{
return FullID.ToString();
}
}
[Serializable]
public class AssetMetadata
{
private UUID m_fullid;
// m_id added as a dirty hack to transition from FullID to ID
private string m_id;
private string m_name = String.Empty;
private string m_description = String.Empty;
private DateTime m_creation_date;
private sbyte m_type;
private string m_content_type;
private byte[] m_sha1;
private bool m_local = false;
private bool m_temporary = false;
//private Dictionary<string, Uri> m_methods = new Dictionary<string, Uri>();
//private OSDMap m_extra_data;
public UUID FullID
{
get { return m_fullid; }
set { m_fullid = value; m_id = m_fullid.ToString(); }
}
public string ID
{
//get { return m_fullid.ToString(); }
//set { m_fullid = new UUID(value); }
get { return m_id; }
set
{
UUID uuid = UUID.Zero;
if (UUID.TryParse(value, out uuid))
{
m_fullid = uuid;
m_id = m_fullid.ToString();
}
else
m_id = value;
}
}
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public string Description
{
get { return m_description; }
set { m_description = value; }
}
public DateTime CreationDate
{
get { return m_creation_date; }
set { m_creation_date = value; }
}
public sbyte Type
{
get { return m_type; }
set { m_type = value; }
}
public string ContentType
{
get { return m_content_type; }
set { m_content_type = value; }
}
public byte[] SHA1
{
get { return m_sha1; }
set { m_sha1 = value; }
}
public bool Local
{
get { return m_local; }
set { m_local = value; }
}
public bool Temporary
{
get { return m_temporary; }
set { m_temporary = value; }
}
//public Dictionary<string, Uri> Methods
//{
// get { return m_methods; }
// set { m_methods = value; }
//}
//public OSDMap ExtraData
//{
// get { return m_extra_data; }
// set { m_extra_data = value; }
//}
}
}
| |
using System.Windows.Forms;
using DigitallyImported.Components;
namespace DigitallyImported.Client
{
partial class FavoritesForm<TChannel, TTrack>
where TChannel : UserControl, IChannel, new()
where TTrack: UserControl, ITrack, new()
{
/// <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(FavoritesForm<,>));
this.ChannelsGroupBox = new System.Windows.Forms.GroupBox();
this.PlaylistLabel3 = new System.Windows.Forms.Label();
this.RemoveExternalButton = new System.Windows.Forms.Button();
this.AddExternalButton = new System.Windows.Forms.Button();
this.ExternalPlaylistCheckBox = new System.Windows.Forms.CheckedListBox();
this.PlaylistLabel2 = new System.Windows.Forms.Label();
this.PlaylistLabel1 = new System.Windows.Forms.Label();
this.DIPlaylistCheckedList = new System.Windows.Forms.CheckedListBox();
this.SkyPlaylistCheckedList = new System.Windows.Forms.CheckedListBox();
this.ClearButton = new System.Windows.Forms.Button();
this.CancelButton = new System.Windows.Forms.Button();
this.SaveButton = new System.Windows.Forms.Button();
this.FavoritesPanel = new System.Windows.Forms.FlowLayoutPanel();
this.FavoritesStatusStrip = new System.Windows.Forms.StatusStrip();
this.ChannelCountLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.ChannelsGroupBox.SuspendLayout();
this.FavoritesPanel.SuspendLayout();
this.FavoritesStatusStrip.SuspendLayout();
this.toolStripContainer1.BottomToolStripPanel.SuspendLayout();
this.toolStripContainer1.ContentPanel.SuspendLayout();
this.toolStripContainer1.SuspendLayout();
this.SuspendLayout();
//
// ChannelsGroupBox
//
this.ChannelsGroupBox.Controls.Add(this.PlaylistLabel3);
this.ChannelsGroupBox.Controls.Add(this.RemoveExternalButton);
this.ChannelsGroupBox.Controls.Add(this.AddExternalButton);
this.ChannelsGroupBox.Controls.Add(this.ExternalPlaylistCheckBox);
this.ChannelsGroupBox.Controls.Add(this.PlaylistLabel2);
this.ChannelsGroupBox.Controls.Add(this.PlaylistLabel1);
this.ChannelsGroupBox.Controls.Add(this.DIPlaylistCheckedList);
this.ChannelsGroupBox.Controls.Add(this.SkyPlaylistCheckedList);
this.ChannelsGroupBox.Location = new System.Drawing.Point(3, 3);
this.ChannelsGroupBox.Name = "ChannelsGroupBox";
this.ChannelsGroupBox.Size = new System.Drawing.Size(390, 293);
this.ChannelsGroupBox.TabIndex = 5;
this.ChannelsGroupBox.TabStop = false;
this.ChannelsGroupBox.Text = "Available Channels";
//
// PlaylistLabel3
//
this.PlaylistLabel3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.PlaylistLabel3.Location = new System.Drawing.Point(258, 16);
this.PlaylistLabel3.Name = "PlaylistLabel3";
this.PlaylistLabel3.Size = new System.Drawing.Size(84, 23);
this.PlaylistLabel3.TabIndex = 10;
this.PlaylistLabel3.Text = "0";
this.PlaylistLabel3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// RemoveExternalButton
//
this.RemoveExternalButton.Location = new System.Drawing.Point(361, 262);
this.RemoveExternalButton.Name = "RemoveExternalButton";
this.RemoveExternalButton.Size = new System.Drawing.Size(20, 20);
this.RemoveExternalButton.TabIndex = 9;
this.RemoveExternalButton.Text = "-";
this.RemoveExternalButton.UseVisualStyleBackColor = true;
this.RemoveExternalButton.Click += new System.EventHandler(this.RemoveExternalButton_Click);
//
// AddExternalButton
//
this.AddExternalButton.Location = new System.Drawing.Point(335, 262);
this.AddExternalButton.Name = "AddExternalButton";
this.AddExternalButton.Size = new System.Drawing.Size(20, 20);
this.AddExternalButton.TabIndex = 8;
this.AddExternalButton.Text = "+";
this.AddExternalButton.UseVisualStyleBackColor = true;
this.AddExternalButton.Click += new System.EventHandler(this.AddExternalButton_Click);
//
// ExternalPlaylistCheckBox
//
this.ExternalPlaylistCheckBox.CheckOnClick = true;
this.ExternalPlaylistCheckBox.FormattingEnabled = true;
this.ExternalPlaylistCheckBox.Location = new System.Drawing.Point(261, 42);
this.ExternalPlaylistCheckBox.Name = "ExternalPlaylistCheckBox";
this.ExternalPlaylistCheckBox.Size = new System.Drawing.Size(120, 214);
this.ExternalPlaylistCheckBox.TabIndex = 7;
this.ExternalPlaylistCheckBox.ThreeDCheckBoxes = true;
//
// PlaylistLabel2
//
this.PlaylistLabel2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.PlaylistLabel2.Location = new System.Drawing.Point(132, 16);
this.PlaylistLabel2.Name = "PlaylistLabel2";
this.PlaylistLabel2.Size = new System.Drawing.Size(84, 23);
this.PlaylistLabel2.TabIndex = 6;
this.PlaylistLabel2.Text = "0";
this.PlaylistLabel2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// PlaylistLabel1
//
this.PlaylistLabel1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.PlaylistLabel1.Location = new System.Drawing.Point(9, 16);
this.PlaylistLabel1.Name = "PlaylistLabel1";
this.PlaylistLabel1.Size = new System.Drawing.Size(84, 23);
this.PlaylistLabel1.TabIndex = 5;
this.PlaylistLabel1.Text = "0";
this.PlaylistLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// DIPlaylistCheckedList
//
this.DIPlaylistCheckedList.CheckOnClick = true;
this.DIPlaylistCheckedList.FormattingEnabled = true;
this.DIPlaylistCheckedList.Location = new System.Drawing.Point(9, 42);
this.DIPlaylistCheckedList.Name = "DIPlaylistCheckedList";
this.DIPlaylistCheckedList.Size = new System.Drawing.Size(120, 214);
this.DIPlaylistCheckedList.TabIndex = 0;
this.DIPlaylistCheckedList.ThreeDCheckBoxes = true;
//
// SkyPlaylistCheckedList
//
this.SkyPlaylistCheckedList.CheckOnClick = true;
this.SkyPlaylistCheckedList.FormattingEnabled = true;
this.SkyPlaylistCheckedList.Location = new System.Drawing.Point(135, 42);
this.SkyPlaylistCheckedList.Name = "SkyPlaylistCheckedList";
this.SkyPlaylistCheckedList.Size = new System.Drawing.Size(120, 214);
this.SkyPlaylistCheckedList.TabIndex = 1;
this.SkyPlaylistCheckedList.ThreeDCheckBoxes = true;
//
// ClearButton
//
this.ClearButton.Location = new System.Drawing.Point(165, 302);
this.ClearButton.Name = "ClearButton";
this.ClearButton.Size = new System.Drawing.Size(75, 23);
this.ClearButton.TabIndex = 4;
this.ClearButton.Text = "Clear";
this.ClearButton.UseVisualStyleBackColor = true;
this.ClearButton.Click += new System.EventHandler(this.ResetButton_Click);
//
// CancelButton
//
this.CancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CancelButton.Location = new System.Drawing.Point(84, 302);
this.CancelButton.Name = "CancelButton";
this.CancelButton.Size = new System.Drawing.Size(75, 23);
this.CancelButton.TabIndex = 3;
this.CancelButton.Text = "&Cancel";
this.CancelButton.UseVisualStyleBackColor = true;
//
// SaveButton
//
this.SaveButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.SaveButton.Location = new System.Drawing.Point(3, 302);
this.SaveButton.Name = "SaveButton";
this.SaveButton.Size = new System.Drawing.Size(75, 23);
this.SaveButton.TabIndex = 2;
this.SaveButton.Text = "&Save";
this.SaveButton.UseVisualStyleBackColor = true;
this.SaveButton.Click += new System.EventHandler(this.SaveButton_Click);
//
// FavoritesPanel
//
this.FavoritesPanel.AutoScroll = true;
this.FavoritesPanel.Controls.Add(this.ChannelsGroupBox);
this.FavoritesPanel.Controls.Add(this.SaveButton);
this.FavoritesPanel.Controls.Add(this.CancelButton);
this.FavoritesPanel.Controls.Add(this.ClearButton);
this.FavoritesPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.FavoritesPanel.Location = new System.Drawing.Point(0, 0);
this.FavoritesPanel.Name = "FavoritesPanel";
this.FavoritesPanel.Size = new System.Drawing.Size(397, 330);
this.FavoritesPanel.TabIndex = 5;
//
// FavoritesStatusStrip
//
this.FavoritesStatusStrip.Dock = System.Windows.Forms.DockStyle.None;
this.FavoritesStatusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ChannelCountLabel});
this.FavoritesStatusStrip.Location = new System.Drawing.Point(0, 0);
this.FavoritesStatusStrip.Name = "FavoritesStatusStrip";
this.FavoritesStatusStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional;
this.FavoritesStatusStrip.Size = new System.Drawing.Size(397, 22);
this.FavoritesStatusStrip.TabIndex = 6;
this.FavoritesStatusStrip.Text = "statusStrip1";
//
// ChannelCountLabel
//
this.ChannelCountLabel.Name = "ChannelCountLabel";
this.ChannelCountLabel.Size = new System.Drawing.Size(13, 17);
this.ChannelCountLabel.Text = "0";
//
// toolStripContainer1
//
//
// toolStripContainer1.BottomToolStripPanel
//
this.toolStripContainer1.BottomToolStripPanel.Controls.Add(this.FavoritesStatusStrip);
//
// toolStripContainer1.ContentPanel
//
this.toolStripContainer1.ContentPanel.AutoScroll = true;
this.toolStripContainer1.ContentPanel.Controls.Add(this.FavoritesPanel);
this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(397, 330);
this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolStripContainer1.LeftToolStripPanelVisible = false;
this.toolStripContainer1.Location = new System.Drawing.Point(0, 0);
this.toolStripContainer1.Name = "toolStripContainer1";
this.toolStripContainer1.RightToolStripPanelVisible = false;
this.toolStripContainer1.Size = new System.Drawing.Size(397, 352);
this.toolStripContainer1.TabIndex = 6;
this.toolStripContainer1.Text = "toolStripContainer1";
this.toolStripContainer1.TopToolStripPanelVisible = false;
//
// FavoritesForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(397, 352);
this.Controls.Add(this.toolStripContainer1);
this.DoubleBuffered = true;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
//this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "FavoritesForm";
this.ShowInTaskbar = false;
this.Text = "Favorites List";
this.Load += new System.EventHandler(this.FavoritesForm_Load);
this.ChannelsGroupBox.ResumeLayout(false);
this.FavoritesPanel.ResumeLayout(false);
this.FavoritesStatusStrip.ResumeLayout(false);
this.FavoritesStatusStrip.PerformLayout();
this.toolStripContainer1.BottomToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.BottomToolStripPanel.PerformLayout();
this.toolStripContainer1.ContentPanel.ResumeLayout(false);
this.toolStripContainer1.ResumeLayout(false);
this.toolStripContainer1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox ChannelsGroupBox;
private System.Windows.Forms.CheckedListBox DIPlaylistCheckedList;
private System.Windows.Forms.CheckedListBox SkyPlaylistCheckedList;
private System.Windows.Forms.Button ClearButton;
private System.Windows.Forms.Button CancelButton;
private System.Windows.Forms.Button SaveButton;
private System.Windows.Forms.FlowLayoutPanel FavoritesPanel;
private System.Windows.Forms.StatusStrip FavoritesStatusStrip;
private System.Windows.Forms.ToolStripContainer toolStripContainer1;
private System.Windows.Forms.ToolStripStatusLabel ChannelCountLabel;
private System.Windows.Forms.Label PlaylistLabel2;
private System.Windows.Forms.Label PlaylistLabel1;
private Label PlaylistLabel3;
private Button RemoveExternalButton;
private Button AddExternalButton;
private CheckedListBox ExternalPlaylistCheckBox;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using ModestTree.Util;
namespace ModestTree
{
public static class LinqExtensions
{
// Inclusive because it includes the item that meets the predicate
public static IEnumerable<TSource> TakeUntilInclusive<TSource>(
this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
foreach (var item in source)
{
yield return item;
if (predicate(item))
{
yield break;
}
}
}
// Return the first item when the list is of length one and otherwise returns default
public static TSource OnlyOrDefault<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (source.Count() > 1)
{
return default(TSource);
}
return source.FirstOrDefault();
}
// Another name for IEnumerable.Reverse()
// This is useful to distinguish betweeh List.Reverse() when dealing with a list
public static IEnumerable<T> Reversed<T>(this IEnumerable<T> list)
{
return list.Reverse();
}
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
foreach (T t in second)
{
yield return t;
}
foreach (T t in first)
{
yield return t;
}
}
// These are more efficient than Count() in cases where the size of the collection is not known
public static bool HasAtLeast<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount).Count() == amount;
}
public static bool HasMoreThan<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.HasAtLeast(amount+1);
}
public static bool HasLessThan<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.HasAtMost(amount-1);
}
public static bool HasAtMost<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount + 1).Count() <= amount;
}
public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
{
return !enumerable.Any();
}
public static IEnumerable<T> GetDuplicates<T>(this IEnumerable<T> list)
{
return list.GroupBy(x => x).Where(x => x.Skip(1).Any()).Select(x => x.Key);
}
public static IEnumerable<T> ReplaceOrAppend<T>(
this IEnumerable<T> enumerable, Predicate<T> match, T replacement)
{
bool replaced = false;
foreach (T t in enumerable)
{
if (match(t))
{
replaced = true;
yield return replacement;
}
else
{
yield return t;
}
}
if (!replaced)
{
yield return replacement;
}
}
public static IEnumerable<T> ToEnumerable<T>(this IEnumerator enumerator)
{
while (enumerator.MoveNext())
{
yield return (T)enumerator.Current;
}
}
public static IEnumerable<T> ToEnumerable<T>(this IEnumerator<T> enumerator)
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> enumerable)
{
return new HashSet<T>(enumerable);
}
// This is more efficient than just Count() < x because it will end early
// rather than iterating over the entire collection
public static bool IsLength<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount + 1).Count() == amount;
}
public static IEnumerable<T> Except<T>(this IEnumerable<T> list, T item)
{
return list.Except(item.Yield());
}
public static T GetSingle<T>(this object[] objectArray, bool required)
{
if (required)
{
return objectArray.Where(x => x is T).Cast<T>().Single();
}
else
{
return objectArray.Where(x => x is T).Cast<T>().SingleOrDefault();
}
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
return source.DistinctBy(keySelector, null);
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
if (source == null)
throw new ArgumentNullException("source");
if (keySelector == null)
throw new ArgumentNullException("keySelector");
return DistinctByImpl(source, keySelector, comparer);
}
static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
var knownKeys = new HashSet<TKey>(comparer);
foreach (var element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
public static T Second<T>(this IEnumerable<T> list)
{
return list.Skip(1).First();
}
public static T SecondOrDefault<T>(this IEnumerable<T> list)
{
return list.Skip(1).FirstOrDefault();
}
public static int RemoveAll<T>(this LinkedList<T> list, Func<T, bool> predicate)
{
int numRemoved = 0;
var currentNode = list.First;
while (currentNode != null)
{
if (predicate(currentNode.Value))
{
var toRemove = currentNode;
currentNode = currentNode.Next;
list.Remove(toRemove);
numRemoved++;
}
else
{
currentNode = currentNode.Next;
}
}
return numRemoved;
}
// LINQ already has a method called "Contains" that does the same thing as this
// BUT it fails to work with Mono 3.5 in some cases.
// For example the following prints False, True in Mono 3.5 instead of True, True like it should:
//
// IEnumerable<string> args = new string[]
// {
// "",
// null,
// };
// Log.Info(args.ContainsItem(null));
// Log.Info(args.Where(x => x == null).Any());
public static bool ContainsItem<T>(this IEnumerable<T> list, T value)
{
// Use object.Equals to support null values
return list.Where(x => object.Equals(x, value)).Any();
}
// We call it Zipper instead of Zip to avoid naming conflicts with .NET 4
public static IEnumerable<T> Zipper<A, B, T>(
this IEnumerable<A> seqA, IEnumerable<B> seqB, Func<A, B, T> func)
{
using (var iteratorA = seqA.GetEnumerator())
using (var iteratorB = seqB.GetEnumerator())
{
while (true)
{
bool isDoneA = !iteratorA.MoveNext();
bool isDoneB = !iteratorB.MoveNext();
Assert.That(isDoneA == isDoneB,
"Given collections have different length in Zip operator");
if (isDoneA || isDoneB)
{
break;
}
yield return func(iteratorA.Current, iteratorB.Current);
}
}
}
public static IEnumerable<ValuePair<A, B>> Zipper<A, B>(
this IEnumerable<A> seqA, IEnumerable<B> seqB)
{
return seqA.Zipper<A, B, ValuePair<A, B>>(seqB, ValuePair.New);
}
}
}
| |
// 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.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
namespace System.Threading.Tasks.Sources
{
/// <summary>Provides the core logic for implementing a manual-reset <see cref="IValueTaskSource"/> or <see cref="IValueTaskSource{TResult}"/>.</summary>
/// <typeparam name="TResult"></typeparam>
[StructLayout(LayoutKind.Auto)]
public struct ManualResetValueTaskSourceCore<TResult>
{
/// <summary>
/// The callback to invoke when the operation completes if <see cref="OnCompleted"/> was called before the operation completed,
/// or <see cref="ManualResetValueTaskSourceCoreShared.s_sentinel"/> if the operation completed before a callback was supplied,
/// or null if a callback hasn't yet been provided and the operation hasn't yet completed.
/// </summary>
private Action<object> _continuation;
/// <summary>State to pass to <see cref="_continuation"/>.</summary>
private object _continuationState;
/// <summary><see cref="ExecutionContext"/> to flow to the callback, or null if no flowing is required.</summary>
private ExecutionContext _executionContext;
/// <summary>
/// A "captured" <see cref="SynchronizationContext"/> or <see cref="TaskScheduler"/> with which to invoke the callback,
/// or null if no special context is required.
/// </summary>
private object _capturedContext;
/// <summary>Whether the current operation has completed.</summary>
private bool _completed;
/// <summary>The result with which the operation succeeded, or the default value if it hasn't yet completed or failed.</summary>
private TResult _result;
/// <summary>The exception with which the operation failed, or null if it hasn't yet completed or completed successfully.</summary>
private ExceptionDispatchInfo _error;
/// <summary>The current version of this value, used to help prevent misuse.</summary>
private short _version;
/// <summary>Gets or sets whether to force continuations to run asynchronously.</summary>
/// <remarks>Continuations may run asynchronously if this is false, but they'll never run synchronously if this is true.</remarks>
public bool RunContinuationsAsynchronously { get; set; }
/// <summary>Resets to prepare for the next operation.</summary>
public void Reset()
{
// Reset/update state for the next use/await of this instance.
_version++;
_completed = false;
_result = default;
_error = null;
_executionContext = null;
_capturedContext = null;
_continuation = null;
_continuationState = null;
}
/// <summary>Completes with a successful result.</summary>
/// <param name="result">The result.</param>
public void SetResult(TResult result)
{
_result = result;
SignalCompletion();
}
/// <summary>Complets with an error.</summary>
/// <param name="error"></param>
public void SetException(Exception error)
{
_error = ExceptionDispatchInfo.Capture(error);
SignalCompletion();
}
/// <summary>Gets the operation version.</summary>
public short Version => _version;
/// <summary>Gets the status of the operation.</summary>
/// <param name="token">Opaque value that was provided to the <see cref="ValueTask"/>'s constructor.</param>
public ValueTaskSourceStatus GetStatus(short token)
{
ValidateToken(token);
return
_continuation == null || !_completed ? ValueTaskSourceStatus.Pending :
_error == null ? ValueTaskSourceStatus.Succeeded :
_error.SourceException is OperationCanceledException ? ValueTaskSourceStatus.Canceled :
ValueTaskSourceStatus.Faulted;
}
/// <summary>Gets the result of the operation.</summary>
/// <param name="token">Opaque value that was provided to the <see cref="ValueTask"/>'s constructor.</param>
[StackTraceHidden]
public TResult GetResult(short token)
{
ValidateToken(token);
if (!_completed)
{
ThrowHelper.ThrowInvalidOperationException();
}
_error?.Throw();
return _result;
}
/// <summary>Schedules the continuation action for this operation.</summary>
/// <param name="continuation">The continuation to invoke when the operation has completed.</param>
/// <param name="state">The state object to pass to <paramref name="continuation"/> when it's invoked.</param>
/// <param name="token">Opaque value that was provided to the <see cref="ValueTask"/>'s constructor.</param>
/// <param name="flags">The flags describing the behavior of the continuation.</param>
public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
{
if (continuation == null)
{
throw new ArgumentNullException(nameof(continuation));
}
ValidateToken(token);
if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0)
{
_executionContext = ExecutionContext.Capture();
}
if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0)
{
SynchronizationContext sc = SynchronizationContext.Current;
if (sc != null && sc.GetType() != typeof(SynchronizationContext))
{
_capturedContext = sc;
}
else
{
TaskScheduler ts = TaskScheduler.Current;
if (ts != TaskScheduler.Default)
{
_capturedContext = ts;
}
}
}
// We need to set the continuation state before we swap in the delegate, so that
// if there's a race between this and SetResult/Exception and SetResult/Exception
// sees the _continuation as non-null, it'll be able to invoke it with the state
// stored here. However, this also means that if this is used incorrectly (e.g.
// awaited twice concurrently), _continuationState might get erroneously overwritten.
// To minimize the chances of that, we check preemptively whether _continuation
// is already set to something other than the completion sentinel.
object oldContinuation = _continuation;
if (oldContinuation == null)
{
_continuationState = state;
oldContinuation = Interlocked.CompareExchange(ref _continuation, continuation, null);
}
if (oldContinuation != null)
{
// Operation already completed, so we need to queue the supplied callback.
if (!ReferenceEquals(oldContinuation, ManualResetValueTaskSourceCoreShared.s_sentinel))
{
ThrowHelper.ThrowInvalidOperationException();
}
switch (_capturedContext)
{
case null:
if (_executionContext != null)
{
ThreadPool.QueueUserWorkItem(continuation, state, preferLocal: true);
}
else
{
ThreadPool.UnsafeQueueUserWorkItem(continuation, state, preferLocal: true);
}
break;
case SynchronizationContext sc:
sc.Post(s =>
{
var tuple = (Tuple<Action<object>, object>)s;
tuple.Item1(tuple.Item2);
}, Tuple.Create(continuation, state));
break;
case TaskScheduler ts:
Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, ts);
break;
}
}
}
/// <summary>Ensures that the specified token matches the current version.</summary>
/// <param name="token">The token supplied by <see cref="ValueTask"/>.</param>
private void ValidateToken(short token)
{
if (token != _version)
{
ThrowHelper.ThrowInvalidOperationException();
}
}
/// <summary>Signals that that the operation has completed. Invoked after the result or error has been set.</summary>
private void SignalCompletion()
{
if (_completed)
{
ThrowHelper.ThrowInvalidOperationException();
}
_completed = true;
if (_continuation != null || Interlocked.CompareExchange(ref _continuation, ManualResetValueTaskSourceCoreShared.s_sentinel, null) != null)
{
if (_executionContext != null)
{
ExecutionContext.RunInternal(
_executionContext,
(ref ManualResetValueTaskSourceCore<TResult> s) => s.InvokeContinuation(),
ref this);
}
else
{
InvokeContinuation();
}
}
}
/// <summary>
/// Invokes the continuation with the appropriate captured context / scheduler.
/// This assumes that if <see cref="_executionContext"/> is not null we're already
/// running within that <see cref="ExecutionContext"/>.
/// </summary>
private void InvokeContinuation()
{
switch (_capturedContext)
{
case null:
if (RunContinuationsAsynchronously)
{
if (_executionContext != null)
{
ThreadPool.QueueUserWorkItem(_continuation, _continuationState, preferLocal: true);
}
else
{
ThreadPool.UnsafeQueueUserWorkItem(_continuation, _continuationState, preferLocal: true);
}
}
else
{
_continuation(_continuationState);
}
break;
case SynchronizationContext sc:
sc.Post(s =>
{
var state = (Tuple<Action<object>, object>)s;
state.Item1(state.Item2);
}, Tuple.Create(_continuation, _continuationState));
break;
case TaskScheduler ts:
Task.Factory.StartNew(_continuation, _continuationState, CancellationToken.None, TaskCreationOptions.DenyChildAttach, ts);
break;
}
}
}
internal static class ManualResetValueTaskSourceCoreShared // separated out of generic to avoid unnecessary duplication
{
internal static readonly Action<object> s_sentinel = CompletionSentinel;
private static void CompletionSentinel(object _) // named method to aid debugging
{
Debug.Fail("The sentinel delegate should never be invoked.");
ThrowHelper.ThrowInvalidOperationException();
}
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using Scriban.Helpers;
using Scriban.Runtime;
namespace Scriban.Syntax
{
[ScriptSyntax("function call expression", "<target_expression> <arguemnt[0]> ... <arguement[n]>")]
public partial class ScriptFunctionCall : ScriptExpression
{
private ScriptExpression _target;
private ScriptToken _openParent;
private ScriptList<ScriptExpression> _arguments;
private ScriptToken _closeParen;
// Maximum number of parameters is 64
// it equals the argMask we are using for matching arguments passed
// as it is a long, it can only store 64 bits, so we are limiting
// the number of parameter to simplify the implementation.
public const int MaximumParameterCount = 64;
public ScriptFunctionCall()
{
Arguments = new ScriptList<ScriptExpression>();
}
public ScriptExpression Target
{
get => _target;
set => ParentToThis(ref _target, value);
}
public ScriptToken OpenParent
{
get => _openParent;
set => ParentToThis(ref _openParent, value);
}
public ScriptList<ScriptExpression> Arguments
{
get => _arguments;
set => ParentToThis(ref _arguments, value);
}
public ScriptToken CloseParen
{
get => _closeParen;
set => ParentToThis(ref _closeParen, value);
}
public bool ExplicitCall { get; set; }
public bool TryGetFunctionDeclaration(out ScriptFunction function)
{
function = null;
if (!ExplicitCall) return false;
if (!(Target is ScriptVariableGlobal name)) return false;
if (OpenParent == null || CloseParen == null) return false;
foreach(var arg in Arguments)
{
if (!(arg is ScriptVariableGlobal)) return false;
}
var parameters = new ScriptList<ScriptParameter>();
function = new ScriptFunction
{
NameOrDoToken = (ScriptVariable)name.Clone(),
OpenParen = (ScriptToken)OpenParent.Clone(),
CloseParen = (ScriptToken)CloseParen.Clone(),
Span = Span
};
foreach (var arg in Arguments)
{
var variableName = (ScriptVariableGlobal) arg.Clone();
parameters.Add(new ScriptParameter() {Name = variableName});
}
function.Parameters = parameters;
return true;
}
public void AddArgument(ScriptExpression argument)
{
if (argument == null) throw new ArgumentNullException(nameof(argument));
Arguments.Add(argument);
if (CloseParen == null && !argument.Span.IsEmpty)
{
Span.End = argument.Span.End;
}
}
public ScriptExpression GetScientificExpression(TemplateContext context)
{
// If we are in scientific mode and we have a function which takes arguments, and is not an explicit call (e.g sin(x) rather then sin x)
// Then we need to rewrite the call to a proper expression.
if (context.UseScientific && !ExplicitCall && Arguments.Count > 0)
{
var rewrite = new ScientificFunctionCallRewriter(1 + Arguments.Count);
rewrite.Add(Target);
rewrite.AddRange(Arguments);
return rewrite.Rewrite(context, this);
}
return this;
}
public override object Evaluate(TemplateContext context)
{
// Double check if the expression can be rewritten
var newExpression = GetScientificExpression(context);
if (newExpression != this)
{
return context.Evaluate(newExpression);
}
// Invoke evaluate on the target, but don't automatically call the function as if it was a parameterless call.
var targetFunction = context.Evaluate(Target, true);
// Throw an exception if the target function is null
if (targetFunction == null)
{
if (context.EnableRelaxedFunctionAccess)
{
return null;
}
throw new ScriptRuntimeException(Target.Span, $"The function `{Target}` was not found");
}
return Call(context, this, targetFunction, context.AllowPipeArguments, Arguments);
}
public override void PrintTo(ScriptPrinter printer)
{
printer.Write(Target);
if (OpenParent != null)
{
printer.Write(OpenParent);
printer.WriteListWithCommas(Arguments);
}
else
{
for (var i = 0; i < Arguments.Count; i++)
{
var scriptExpression = Arguments[i];
printer.ExpectSpace();
printer.Write(scriptExpression);
}
}
if (CloseParen != null) printer.Write(CloseParen);
}
public override bool CanHaveLeadingTrivia()
{
return false;
}
public static bool IsFunction(object target)
{
return target is IScriptCustomFunction;
}
public static object Call(TemplateContext context, ScriptNode callerContext, object functionObject, bool processPipeArguments, IReadOnlyList<ScriptExpression> arguments)
{
if (context == null) throw new ArgumentNullException(nameof(context));
// Pop immediately the block
ScriptBlockStatement blockDelegate = null;
if (context.BlockDelegates.Count > 0)
{
blockDelegate = context.BlockDelegates.Pop();
}
if (callerContext == null) throw new ArgumentNullException(nameof(callerContext));
if (functionObject == null)
{
throw new ScriptRuntimeException(callerContext.Span, $"The target function `{callerContext}` is null");
}
var scriptFunction = functionObject as ScriptFunction;
var function = functionObject as IScriptCustomFunction;
if (function == null)
{
throw new ScriptRuntimeException(callerContext.Span, $"Invalid target function `{functionObject}` ({context.GetTypeName(functionObject)})");
}
if (function.ParameterCount >= MaximumParameterCount)
{
throw new ScriptRuntimeException(callerContext.Span, $"Out of range number of parameters {function.ParameterCount} for target function `{functionObject}`. The maximum number of parameters for a function is: {MaximumParameterCount}.");
}
// Generates an error only if the context is configured for it
if (context.ErrorForStatementFunctionAsExpression && function.ReturnType == typeof(void) && callerContext.Parent is ScriptExpression)
{
var firstToken = callerContext.FindFirstTerminal();
throw new ScriptRuntimeException(callerContext.Span, $"The function `{firstToken}` is a statement and cannot be used within an expression.");
}
// We can't cache this array because it might be collect by the function
// So we absolutely need to generate a new array everytime we call a function
ScriptArray argumentValues;
List<ScriptExpression> allArgumentsWithPipe = null;
// Handle pipe arguments here
if (processPipeArguments && context.CurrentPipeArguments != null && context.CurrentPipeArguments.Count > 0)
{
var argCount = Math.Max(function.RequiredParameterCount, 1 + (arguments?.Count ?? 0));
allArgumentsWithPipe = context.GetOrCreateListOfScriptExpressions(argCount);
var pipeFrom = context.CurrentPipeArguments.Pop();
argumentValues = new ScriptArray(argCount);
allArgumentsWithPipe.Add(pipeFrom);
if (arguments != null)
{
allArgumentsWithPipe.AddRange(arguments);
}
arguments = allArgumentsWithPipe;
}
else
{
argumentValues = new ScriptArray(arguments?.Count ?? 0);
}
var needLocal = !(function is ScriptFunction func && func.HasParameters);
object result = null;
try
{
// Process direct arguments
ulong argMask = 0;
if (arguments != null)
{
argMask = ProcessArguments(context, callerContext, arguments, function, scriptFunction, argumentValues);
}
// Fill remaining argument default values
var hasVariableParams = function.VarParamKind != ScriptVarParamKind.None;
var requiredParameterCount = function.RequiredParameterCount;
var parameterCount = function.ParameterCount;
if (function.VarParamKind != ScriptVarParamKind.Direct)
{
FillRemainingOptionalArguments(ref argMask, argumentValues.Count, parameterCount - 1 , function, argumentValues);
}
// Check the required number of arguments
var requiredMask = (1U << requiredParameterCount) - 1;
argMask = argMask & requiredMask;
// Create a span after the caller for missing arguments
var afterCallerSpan = callerContext.Span;
afterCallerSpan.Start = afterCallerSpan.End.NextColumn();
afterCallerSpan.End = afterCallerSpan.End.NextColumn();
if (argMask != requiredMask)
{
int argCount = 0;
while (argMask != 0)
{
if ((argMask & 1) != 0) argCount++;
argMask = argMask >> 1;
}
throw new ScriptRuntimeException(afterCallerSpan, $"Invalid number of arguments `{argCount}` passed to `{callerContext}` while expecting `{requiredParameterCount}` arguments");
}
if (!hasVariableParams && argumentValues.Count > parameterCount)
{
if (argumentValues.Count > 0 && arguments != null && argumentValues.Count <= arguments.Count)
{
throw new ScriptRuntimeException(arguments[argumentValues.Count - 1].Span, $"Invalid number of arguments `{argumentValues.Count}` passed to `{callerContext}` while expecting `{parameterCount}` arguments");
}
throw new ScriptRuntimeException(afterCallerSpan, $"Invalid number of arguments `{argumentValues.Count}` passed to `{callerContext}` while expecting `{parameterCount}` arguments");
}
context.EnterFunction(callerContext);
try
{
result = function.Invoke(context, callerContext, argumentValues, blockDelegate);
}
catch (ArgumentException ex)
{
// Slow path to detect the argument index from the name if we can
var index = GetParameterIndexByName(function, ex.ParamName);
if (index >= 0 && arguments != null && index < arguments.Count)
{
throw new ScriptRuntimeException(arguments[index].Span, ex.Message);
}
throw;
}
catch (ScriptArgumentException ex)
{
var index = ex.ArgumentIndex;
if (index >= 0 && arguments != null && index < arguments.Count)
{
throw new ScriptRuntimeException(arguments[index].Span, ex.Message);
}
throw;
}
finally
{
context.ExitFunction(callerContext);
}
}
finally
{
if (allArgumentsWithPipe != null)
{
context.ReleaseListOfScriptExpressions(allArgumentsWithPipe);
}
}
// Restore the flow state to none
context.FlowState = ScriptFlowState.None;
return result;
}
private static ulong ProcessArguments(TemplateContext context, ScriptNode callerContext, IReadOnlyList<ScriptExpression> arguments, IScriptCustomFunction function, ScriptFunction scriptFunction, ScriptArray argumentValues)
{
ulong argMask = 0;
var parameterCount = function.ParameterCount;
for (var argIndex = 0; argIndex < arguments.Count; argIndex++)
{
var argument = arguments[argIndex];
int index = argumentValues.Count;
object value;
// Handle named arguments
var namedArg = argument as ScriptNamedArgument;
if (namedArg != null)
{
var argName = namedArg.Name?.Name;
if (argName == null)
{
throw new ScriptRuntimeException(argument.Span, "Invalid null argument name");
}
index = GetParameterIndexByName(function, argName);
// In case of a ScriptFunction, we write the named argument into the ScriptArray directly
if (scriptFunction != null)
{
if (function.VarParamKind != ScriptVarParamKind.None)
{
if (index >= 0)
{
}
// We can't add an argument that is "size" for array
else if (argumentValues.CanWrite(argName))
{
argumentValues.TrySetValue(context, callerContext.Span, argName, context.Evaluate(namedArg), false);
continue;
}
else
{
throw new ScriptRuntimeException(argument.Span, $"Cannot pass argument {argName} to function. This name is not supported by this function.");
}
}
}
if (index < 0)
{
index = argumentValues.Count;
}
}
if (function.IsParameterType<ScriptExpression>(index))
{
value = namedArg != null ? namedArg.Value : argument;
}
else
{
value = context.Evaluate(argument);
}
// Handle parameters expansion for a function call when the operator ^ is used
if (argument is ScriptUnaryExpression unaryExpression && unaryExpression.Operator == ScriptUnaryOperator.FunctionParametersExpand && !(value is ScriptExpression))
{
var valueEnumerator = value as IEnumerable;
if (valueEnumerator != null)
{
foreach (var subValue in valueEnumerator)
{
var paramType = function.GetParameterInfo(argumentValues.Count).ParameterType;
var newValue = context.ToObject(callerContext.Span, subValue, paramType);
SetArgumentValue(index, newValue, function, ref argMask, argumentValues, parameterCount);
index++;
}
continue;
}
}
{
var paramType = function.GetParameterInfo(index).ParameterType;
value = context.ToObject(argument.Span, value, paramType);
}
SetArgumentValue(index, value, function, ref argMask, argumentValues, parameterCount);
}
return argMask;
}
private static void SetArgumentValue(int index, object value, IScriptCustomFunction function, ref ulong argMask, ScriptArray argumentValues, int parameterCount)
{
// NamedArguments can index further, so we need to fill any intermediate argument values
// with their default values.
if (index > argumentValues.Count)
{
FillRemainingOptionalArguments(ref argMask, argumentValues.Count, index, function, argumentValues);
}
if (index < parameterCount) argMask |= 1U << index;
if (function.VarParamKind == ScriptVarParamKind.LastParameter && index >= parameterCount - 1)
{
var varArgs = (ScriptArray) argumentValues[parameterCount - 1];
if (varArgs == null)
{
argumentValues[index] = varArgs = new ScriptArray();
}
varArgs.Add(value);
}
else
{
argumentValues[index] = value;
}
}
private static void FillRemainingOptionalArguments(ref ulong argMask, int startIndex, int endIndex, IScriptCustomFunction function, ScriptArray argumentValues)
{
var maxIndex = function.ParameterCount - 1;
if (endIndex > maxIndex) endIndex = maxIndex;
int paramsVarIndex = function.VarParamKind == ScriptVarParamKind.LastParameter ? maxIndex : -1;
for (int i = startIndex; i <= endIndex; i++)
{
var parameterInfo = function.GetParameterInfo(i);
if (parameterInfo.HasDefaultValue)
{
argumentValues[i] = parameterInfo.DefaultValue;
argMask |= 1U << i;
}
else
{
argumentValues[i] = i == paramsVarIndex ? new ScriptArray() : null;
}
}
}
private static int GetParameterIndexByName(IScriptFunctionInfo functionInfo, string name)
{
var paramCount = functionInfo.ParameterCount;
for (var i = 0; i < paramCount; i++)
{
var p = functionInfo.GetParameterInfo(i);
if (p.Name == name) return i;
}
return -1;
}
}
}
| |
// 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.Collections.Generic;
using System.IO;
using System.Diagnostics.Contracts;
namespace Microsoft.Research.CodeAnalysis
{
public partial interface IFrameworkLogOptions
{
/// <summary>
/// Print tracing information during DFA steps
/// </summary>
bool TraceDFA { get; }
/// <summary>
/// Trace the heap analysis phase of the framework
/// </summary>
bool TraceHeapAnalysis { get; }
/// <summary>
/// Trace the expression analysis phase of the framework
/// </summary>
bool TraceExpressionAnalysis { get; }
/// <summary>
/// Trace the egraph operations of the framework
/// </summary>
bool TraceEGraph { get; }
/// <summary>
/// Trace assumptions of the framework
/// </summary>
bool TraceAssumptions { get; }
/// <summary>
/// Trace weakest precondition paths
/// </summary>
bool TraceWP { get; }
/// <summary>
/// Emit the WP formula we cannot prove in the SMT-LIB format
/// </summary>
bool EmitSMT2Formula { get; }
bool TraceNumericalAnalysis { get; }
/// <summary>
/// Trace the execution of the partition analysis
/// </summary>
bool TracePartitionAnalysis { get; }
bool TraceInference { get; }
bool TraceChecks { get; }
/// <summary>
/// Trace, for each transfer function, its cost
/// </summary>
bool TraceTimings { get; }
/// <summary>
/// Trace, for each transfer function, its memory usage
/// </summary>
bool TraceMemoryConsumption { get; }
bool TraceMoveNext { get; }
/// <summary>
/// True if analysis framework should print IL of CFGs
/// </summary>
bool PrintIL { get; }
/// <summary>
/// If true, try to prioritize the warning messages
/// </summary>
bool PrioritizeWarnings { get; }
/// <summary>
/// Controls whether or not to print suggestions for requires
/// </summary>
bool SuggestRequires { get; }
/// <summary>
/// Suggest turning assertions into contracts
/// </summary>
bool SuggestAssertToContracts { get; }
/// <summary>
/// Controls whether or not to print suggestions on arrays
/// - Eventually this will be merged with SuggestRequires, now we keep it separate for debugging/development
/// </summary>
bool SuggestRequiresForArrays { get; }
/// <summary>
/// Controls whether or not should output the suggestion for [Pure] for arrays
/// </summary>
bool SuggestRequiresPurityForArrays { get; }
/// <summary>
/// Controls whether or not to print ensures suggestions
/// </summary>
bool SuggestEnsures(bool isProperty);
/// <summary>
/// Control whether or not to print return != null suggestions
/// </summary>
bool SuggestNonNullReturn { get; }
bool InferPreconditionsFromPostconditions { get; }
bool PropagateObjectInvariants { get; }
bool InferAssumesForBaseLining { get; }
/// <summary>
/// True if we should try to propagate inferred pre-conditions for the method <code>m</code>
/// </summary>
/// <param name="isGetterOrSetter">Is the current method a getter or a setter</param>
bool PropagateInferredRequires(bool isCurrentMethodGetterOrSetter);
/// <summary>
/// True iff we should try to propagate the inferred postconditions for the method <code>m</code>
/// </summary>
/// <param name="isGetterOrSetter">Is the current method a getter or a setter</param>
bool PropagateInferredEnsures(bool isCurrentMethodGetterOrSetter);
/// <summary>
/// True iff we want to propagate the ensures != null inferred for a method
/// </summary>
bool PropagateInferredNonNullReturn { get; }
bool PropagateInferredSymbolicReturn { get; }
bool PropagateRequiresPurityForArrays { get; }
bool PropagatedRequiresAreSufficient { get; }
bool CheckFalsePostconditions { get; }
/// <summary>
/// When printing CS files with contracts, limit output to visible items.
/// </summary>
bool OutputOnlyExternallyVisibleMembers { get; }
/// <summary>
/// The timeout, expressed in minutes, to stop the analysis
/// </summary>
int Timeout { get; }
/// <summary>
/// How many joins before widening ?
/// </summary>
int IterationsBeforeWidening { get; }
/// <summary>
/// How many variables before giving up the inference of Octagons?
/// </summary>
int MaxVarsForOctagonInference { get; }
int MaxVarsInSingleRenaming { get; }
bool IsAdaptiveAnalysis { get; }
/// <summary>
/// Enforce the fair join
/// </summary>
bool EnforceFairJoin { get; }
bool TurnArgumentExceptionThrowsIntoAssertFalse { get; }
bool IgnoreExplicitAssumptions { get; }
/// <summary>
/// True iff we want to show the analysis phases
/// </summary>
bool ShowPhases { get; }
bool SufficientConditions { get; }
}
#region IFrameworkLogOptions contract binding
[ContractClass(typeof(IFrameworkLogOptionsContract))]
public partial interface IFrameworkLogOptions
{
}
[ContractClassFor(typeof(IFrameworkLogOptions))]
internal abstract class IFrameworkLogOptionsContract : IFrameworkLogOptions
{
#region IFrameworkLogOptions Members
public bool TraceDFA
{
get { throw new NotImplementedException(); }
}
public bool TraceHeapAnalysis
{
get { throw new NotImplementedException(); }
}
public bool TraceExpressionAnalysis
{
get { throw new NotImplementedException(); }
}
public bool TraceEGraph
{
get { throw new NotImplementedException(); }
}
public bool TraceAssumptions
{
get { throw new NotImplementedException(); }
}
public bool TraceWP
{
get { throw new NotImplementedException(); }
}
public bool TraceNumericalAnalysis
{
get { throw new NotImplementedException(); }
}
public bool TracePartitionAnalysis
{
get { throw new NotImplementedException(); }
}
public bool TraceTimings
{
get { throw new NotImplementedException(); }
}
public bool PrintIL
{
get { throw new NotImplementedException(); }
}
public bool PrioritizeWarnings
{
get { throw new NotImplementedException(); }
}
public bool SuggestRequires
{
get { throw new NotImplementedException(); }
}
public bool SuggestAssertToContracts
{
get { throw new NotImplementedException(); }
}
public bool SuggestRequiresForArrays
{
get
{
throw new NotImplementedException();
}
}
public bool SuggestRequiresPurityForArrays { get { throw new NotImplementedException(); } }
public bool SuggestEnsures(bool isProperty)
{
throw new NotImplementedException();
}
public bool SuggestNonNullReturn
{
get { throw new NotImplementedException(); }
}
public bool OutputOnlyExternallyVisibleMembers
{
get { throw new NotImplementedException(); }
}
public bool InferPreconditionsFromPostconditions
{
get { throw new NotImplementedException(); }
}
public int Timeout
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
throw new NotImplementedException();
}
}
public int IterationsBeforeWidening
{
get { throw new NotImplementedException(); }
}
public int MaxVarsForOctagonInference
{
get { throw new NotImplementedException(); }
}
public bool EnforceFairJoin
{
get { throw new NotImplementedException(); }
}
#endregion
#region IFrameworkLogOptions Members
public bool TraceChecks
{
get { throw new NotImplementedException(); }
}
public bool InferRequiresPurityForArrays
{
get { throw new NotImplementedException(); }
}
public bool TraceInference
{
get { throw new NotImplementedException(); }
}
#endregion
#region No interesting contract
public bool PropagateInferredRequires(bool isCurrentMethodGetterOrSetter)
{
throw new NotImplementedException();
}
public bool PropagateSimpleRequires
{
get { throw new NotImplementedException(); }
}
public bool PropagateInferredEnsures(bool isCurrentMethodGetterOrSetter)
{
throw new NotImplementedException();
}
public bool PropagateInferredNonNullReturn
{
get { throw new NotImplementedException(); }
}
public bool PropagateRequiresPurityForArrays
{
get { throw new NotImplementedException(); }
}
public bool PropagatedRequiresAreSufficient
{
get { throw new NotImplementedException(); }
}
public bool EmitSMT2Formula
{
get { throw new NotImplementedException(); }
}
public bool IgnoreExplicitAssumptions
{
get { throw new NotImplementedException(); }
}
public bool ShowPhases
{
get { throw new NotImplementedException(); }
}
public bool TraceMemoryConsumption
{
get { throw new NotImplementedException(); }
}
public bool CheckFalsePostconditions
{
get { throw new NotImplementedException(); }
}
public bool PropagateObjectInvariants
{
get { throw new NotImplementedException(); }
}
public bool InferAssumesForBaseLining
{
get
{
throw new NotImplementedException();
}
}
#endregion
#region IFrameworkLogOptions Members
public bool TurnArgumentExceptionThrowsIntoAssertFalse
{
get { throw new NotImplementedException(); }
}
#endregion
public bool PropagateInferredSymbolicReturn
{
get { throw new NotImplementedException(); }
}
public bool SufficientConditions
{
get { throw new NotImplementedException(); }
}
public bool TraceMoveNext { get { return default(bool); } }
public int MaxVarsInSingleRenaming
{
get { Contract.Ensures(Contract.Result<int>() >= 0); return 0; }
}
public bool IsAdaptiveAnalysis
{
get { throw new NotImplementedException(); }
}
}
#endregion
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: ResourceWriter
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: Default way to write strings to a CLR resource
** file.
**
**
===========================================================*/
namespace System.Resources {
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
#if FEATURE_SERIALIZATION
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
#endif // FEATURE_SERIALIZATION
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Security;
using System.Security.Permissions;
// Generates a binary .resources file in the system default format
// from name and value pairs. Create one with a unique file name,
// call AddResource() at least once, then call Generate() to write
// the .resources file to disk, then call Close() to close the file.
//
// The resources generally aren't written out in the same order
// they were added.
//
// See the RuntimeResourceSet overview for details on the system
// default file format.
//
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ResourceWriter : IResourceWriter
{
private Func<Type, String> typeConverter;
// Set this delegate to allow multi-targeting for .resources files.
public Func<Type, String> TypeNameConverter
{
get
{
return typeConverter;
}
set
{
typeConverter = value;
}
}
// For cases where users can't create an instance of the deserialized
// type in memory, and need to pass us serialized blobs instead.
// LocStudio's managed code parser will do this in some cases.
private class PrecannedResource
{
internal String TypeName;
internal byte[] Data;
internal PrecannedResource(String typeName, byte[] data)
{
TypeName = typeName;
Data = data;
}
}
private class StreamWrapper
{
internal Stream m_stream;
internal bool m_closeAfterWrite;
internal StreamWrapper(Stream s, bool closeAfterWrite)
{
m_stream = s;
m_closeAfterWrite = closeAfterWrite;
}
}
// An initial size for our internal sorted list, to avoid extra resizes.
private const int _ExpectedNumberOfResources = 1000;
private const int AverageNameSize = 20 * 2; // chars in little endian Unicode
private const int AverageValueSize = 40;
private Dictionary<String, Object> _resourceList;
internal Stream _output;
private Dictionary<String, Object> _caseInsensitiveDups;
private Dictionary<String, PrecannedResource> _preserializedData;
private const int _DefaultBufferSize = 4096;
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public ResourceWriter(String fileName)
{
if (fileName==null)
throw new ArgumentNullException("fileName");
Contract.EndContractBlock();
_output = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
_resourceList = new Dictionary<String, Object>(_ExpectedNumberOfResources, FastResourceComparer.Default);
_caseInsensitiveDups = new Dictionary<String, Object>(StringComparer.OrdinalIgnoreCase);
}
public ResourceWriter(Stream stream)
{
if (stream==null)
throw new ArgumentNullException("stream");
if (!stream.CanWrite)
throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"));
Contract.EndContractBlock();
_output = stream;
_resourceList = new Dictionary<String, Object>(_ExpectedNumberOfResources, FastResourceComparer.Default);
_caseInsensitiveDups = new Dictionary<String, Object>(StringComparer.OrdinalIgnoreCase);
}
// Adds a string resource to the list of resources to be written to a file.
// They aren't written until Generate() is called.
//
public void AddResource(String name, String value)
{
if (name==null)
throw new ArgumentNullException("name");
Contract.EndContractBlock();
if (_resourceList == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceWriterSaved"));
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, value);
}
// Adds a resource of type Object to the list of resources to be
// written to a file. They aren't written until Generate() is called.
//
public void AddResource(String name, Object value)
{
if (name==null)
throw new ArgumentNullException("name");
Contract.EndContractBlock();
if (_resourceList == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceWriterSaved"));
// needed for binary compat
if (value != null && value is Stream)
{
AddResourceInternal(name, (Stream)value, false);
}
else
{
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, value);
}
}
// Adds a resource of type Stream to the list of resources to be
// written to a file. They aren't written until Generate() is called.
// Doesn't close the Stream when done.
//
public void AddResource(String name, Stream value)
{
if (name == null)
throw new ArgumentNullException("name");
Contract.EndContractBlock();
if (_resourceList == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceWriterSaved"));
AddResourceInternal(name, value, false);
}
// Adds a resource of type Stream to the list of resources to be
// written to a file. They aren't written until Generate() is called.
// closeAfterWrite parameter indicates whether to close the stream when done.
//
public void AddResource(String name, Stream value, bool closeAfterWrite)
{
if (name == null)
throw new ArgumentNullException("name");
Contract.EndContractBlock();
if (_resourceList == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceWriterSaved"));
AddResourceInternal(name, value, closeAfterWrite);
}
private void AddResourceInternal(String name, Stream value, bool closeAfterWrite)
{
if (value == null)
{
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, value);
}
else
{
// make sure the Stream is seekable
if (!value.CanSeek)
throw new ArgumentException(Environment.GetResourceString("NotSupported_UnseekableStream"));
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, new StreamWrapper(value, closeAfterWrite));
}
}
// Adds a named byte array as a resource to the list of resources to
// be written to a file. They aren't written until Generate() is called.
//
public void AddResource(String name, byte[] value)
{
if (name==null)
throw new ArgumentNullException("name");
Contract.EndContractBlock();
if (_resourceList == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceWriterSaved"));
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
_resourceList.Add(name, value);
}
public void AddResourceData(String name, String typeName, byte[] serializedData)
{
if (name == null)
throw new ArgumentNullException("name");
if (typeName == null)
throw new ArgumentNullException("typeName");
if (serializedData == null)
throw new ArgumentNullException("serializedData");
Contract.EndContractBlock();
if (_resourceList == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceWriterSaved"));
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
if (_preserializedData == null)
_preserializedData = new Dictionary<String, PrecannedResource>(FastResourceComparer.Default);
_preserializedData.Add(name, new PrecannedResource(typeName, serializedData));
}
// Closes the output stream.
public void Close()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (disposing) {
if (_resourceList != null) {
Generate();
}
if (_output != null) {
_output.Close();
}
}
_output = null;
_caseInsensitiveDups = null;
// _resourceList is set to null by Generate.
}
public void Dispose()
{
Dispose(true);
}
// After calling AddResource, Generate() writes out all resources to the
// output stream in the system default format.
// If an exception occurs during object serialization or during IO,
// the .resources file is closed and deleted, since it is most likely
// invalid.
[SecuritySafeCritical] // Asserts permission to create & delete a temp file.
public void Generate()
{
if (_resourceList == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceWriterSaved"));
BinaryWriter bw = new BinaryWriter(_output, Encoding.UTF8);
List<String> typeNames = new List<String>();
// Write out the ResourceManager header
// Write out magic number
bw.Write(ResourceManager.MagicNumber);
// Write out ResourceManager header version number
bw.Write(ResourceManager.HeaderVersionNumber);
MemoryStream resMgrHeaderBlob = new MemoryStream(240);
BinaryWriter resMgrHeaderPart = new BinaryWriter(resMgrHeaderBlob);
// Write out class name of IResourceReader capable of handling
// this file.
resMgrHeaderPart.Write(MultitargetingHelpers.GetAssemblyQualifiedName(typeof(ResourceReader),typeConverter));
// Write out class name of the ResourceSet class best suited to
// handling this file.
// This needs to be the same even with multi-targeting. It's the
// full name -- not the ----sembly qualified name.
resMgrHeaderPart.Write(ResourceManager.ResSetTypeName);
resMgrHeaderPart.Flush();
// Write number of bytes to skip over to get past ResMgr header
bw.Write((int)resMgrHeaderBlob.Length);
// Write the rest of the ResMgr header
bw.Write(resMgrHeaderBlob.GetBuffer(), 0, (int)resMgrHeaderBlob.Length);
// End ResourceManager header
// Write out the RuntimeResourceSet header
// Version number
bw.Write(RuntimeResourceSet.Version);
#if RESOURCE_FILE_FORMAT_DEBUG
// Write out a tag so we know whether to enable or disable
// debugging support when reading the file.
bw.Write("***DEBUG***");
#endif
// number of resources
int numResources = _resourceList.Count;
if (_preserializedData != null)
numResources += _preserializedData.Count;
bw.Write(numResources);
// Store values in temporary streams to write at end of file.
int[] nameHashes = new int[numResources];
int[] namePositions = new int[numResources];
int curNameNumber = 0;
MemoryStream nameSection = new MemoryStream(numResources * AverageNameSize);
BinaryWriter names = new BinaryWriter(nameSection, Encoding.Unicode);
// The data section can be very large, and worse yet, we can grow the byte[] used
// for the data section repeatedly. When using large resources like ~100 images,
// this can lead to both a fragmented large object heap as well as allocating about
// 2-3x of our storage needs in extra overhead. Using a temp file can avoid this.
// Assert permission to get a temp file name, which requires two permissions.
// Additionally, we may be running under an account that doesn't have permission to
// write to the temp directory (enforced via a Windows ACL). Fall back to a MemoryStream.
Stream dataSection = null; // Either a FileStream or a MemoryStream
String tempFile = null;
#if !DISABLE_CAS_USE
PermissionSet permSet = new PermissionSet(PermissionState.None);
permSet.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
permSet.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
#endif
try {
#if !DISABLE_CAS_USE
permSet.Assert();
#endif
tempFile = Path.GetTempFileName();
File.SetAttributes(tempFile, FileAttributes.Temporary | FileAttributes.NotContentIndexed);
// Explicitly opening with FileOptions.DeleteOnClose to avoid complicated File.Delete
// (safe from ----s w/ antivirus software, etc)
dataSection = new FileStream(tempFile, FileMode.Open, FileAccess.ReadWrite, FileShare.Read,
4096, FileOptions.DeleteOnClose | FileOptions.SequentialScan);
}
catch (UnauthorizedAccessException) {
// In case we're running under an account that can't access a temp directory.
dataSection = new MemoryStream();
}
catch (IOException) {
// In case Path.GetTempFileName fails because no unique file names are available
dataSection = new MemoryStream();
}
finally {
#if !DISABLE_CAS_USE
PermissionSet.RevertAssert();
#endif
}
using(dataSection) {
BinaryWriter data = new BinaryWriter(dataSection, Encoding.UTF8);
#if FEATURE_SERIALIZATION
IFormatter objFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File | StreamingContextStates.Persistence));
#endif // FEATURE_SERIALIZATION
#if RESOURCE_FILE_FORMAT_DEBUG
// Write NAMES right before the names section.
names.Write(new byte[] { (byte) 'N', (byte) 'A', (byte) 'M', (byte) 'E', (byte) 'S', (byte) '-', (byte) '-', (byte) '>'});
// Write DATA at the end of the name table section.
data.Write(new byte[] { (byte) 'D', (byte) 'A', (byte) 'T', (byte) 'A', (byte) '-', (byte) '-', (byte)'-', (byte)'>'});
#endif
// We've stored our resources internally in a Hashtable, which
// makes no guarantees about the ordering while enumerating.
// While we do our own sorting of the resource names based on their
// hash values, that's only sorting the nameHashes and namePositions
// arrays. That's all that is strictly required for correctness,
// but for ease of generating a patch in the future that
// modifies just .resources files, we should re-sort them.
SortedList sortedResources = new SortedList(_resourceList, FastResourceComparer.Default);
if (_preserializedData != null) {
foreach (KeyValuePair<String, PrecannedResource> entry in _preserializedData)
sortedResources.Add(entry.Key, entry.Value);
}
IDictionaryEnumerator items = sortedResources.GetEnumerator();
// Write resource name and position to the file, and the value
// to our temporary buffer. Save Type as well.
while (items.MoveNext()) {
nameHashes[curNameNumber] = FastResourceComparer.HashFunction((String)items.Key);
namePositions[curNameNumber++] = (int)names.Seek(0, SeekOrigin.Current);
names.Write((String)items.Key); // key
names.Write((int)data.Seek(0, SeekOrigin.Current)); // virtual offset of value.
#if RESOURCE_FILE_FORMAT_DEBUG
names.Write((byte) '*');
#endif
Object value = items.Value;
ResourceTypeCode typeCode = FindTypeCode(value, typeNames);
// Write out type code
Write7BitEncodedInt(data, (int)typeCode);
// Write out value
PrecannedResource userProvidedResource = value as PrecannedResource;
if (userProvidedResource != null) {
data.Write(userProvidedResource.Data);
}
else {
#if FEATURE_SERIALIZATION
WriteValue(typeCode, value, data, objFormatter);
#else
WriteValue(typeCode, value, data);
#endif
}
#if RESOURCE_FILE_FORMAT_DEBUG
data.Write(new byte[] { (byte) 'S', (byte) 'T', (byte) 'O', (byte) 'P'});
#endif
}
// At this point, the ResourceManager header has been written.
// Finish RuntimeResourceSet header
// Write size & contents of class table
bw.Write(typeNames.Count);
for (int i = 0; i < typeNames.Count; i++)
bw.Write(typeNames[i]);
// Write out the name-related items for lookup.
// Note that the hash array and the namePositions array must
// be sorted in parallel.
Array.Sort(nameHashes, namePositions);
// Prepare to write sorted name hashes (alignment fixup)
// Note: For 64-bit machines, these MUST be aligned on 8 byte
// boundaries! Pointers on IA64 must be aligned! And we'll
// run faster on X86 machines too.
bw.Flush();
int alignBytes = ((int)bw.BaseStream.Position) & 7;
if (alignBytes > 0) {
for (int i = 0; i < 8 - alignBytes; i++)
bw.Write("PAD"[i % 3]);
}
// Write out sorted name hashes.
// Align to 8 bytes.
Contract.Assert((bw.BaseStream.Position & 7) == 0, "ResourceWriter: Name hashes array won't be 8 byte aligned! Ack!");
#if RESOURCE_FILE_FORMAT_DEBUG
bw.Write(new byte[] { (byte) 'H', (byte) 'A', (byte) 'S', (byte) 'H', (byte) 'E', (byte) 'S', (byte) '-', (byte) '>'} );
#endif
foreach (int hash in nameHashes)
bw.Write(hash);
#if RESOURCE_FILE_FORMAT_DEBUG
Console.Write("Name hashes: ");
foreach(int hash in nameHashes)
Console.Write(hash.ToString("x")+" ");
Console.WriteLine();
#endif
// Write relative positions of all the names in the file.
// Note: this data is 4 byte aligned, occuring immediately
// after the 8 byte aligned name hashes (whose length may
// potentially be odd).
Contract.Assert((bw.BaseStream.Position & 3) == 0, "ResourceWriter: Name positions array won't be 4 byte aligned! Ack!");
#if RESOURCE_FILE_FORMAT_DEBUG
bw.Write(new byte[] { (byte) 'P', (byte) 'O', (byte) 'S', (byte) '-', (byte) '-', (byte) '-', (byte) '-', (byte) '>' } );
#endif
foreach (int pos in namePositions)
bw.Write(pos);
#if RESOURCE_FILE_FORMAT_DEBUG
Console.Write("Name positions: ");
foreach(int pos in namePositions)
Console.Write(pos.ToString("x")+" ");
Console.WriteLine();
#endif
// Flush all BinaryWriters to their underlying streams.
bw.Flush();
names.Flush();
data.Flush();
// Write offset to data section
int startOfDataSection = (int)(bw.Seek(0, SeekOrigin.Current) + nameSection.Length);
startOfDataSection += 4; // We're writing an int to store this data, adding more bytes to the header
BCLDebug.Log("RESMGRFILEFORMAT", "Generate: start of DataSection: 0x" + startOfDataSection.ToString("x", CultureInfo.InvariantCulture) + " nameSection length: " + nameSection.Length);
bw.Write(startOfDataSection);
// Write name section.
bw.Write(nameSection.GetBuffer(), 0, (int)nameSection.Length);
names.Close();
// Write data section.
Contract.Assert(startOfDataSection == bw.Seek(0, SeekOrigin.Current), "ResourceWriter::Generate - start of data section is wrong!");
dataSection.Position = 0;
dataSection.CopyTo(bw.BaseStream);
data.Close();
} // using(dataSection) <--- Closes dataSection, which was opened w/ FileOptions.DeleteOnClose
bw.Flush();
// Indicate we've called Generate
_resourceList = null;
}
// Finds the ResourceTypeCode for a type, or adds this type to the
// types list.
private ResourceTypeCode FindTypeCode(Object value, List<String> types)
{
if (value == null)
return ResourceTypeCode.Null;
Type type = value.GetType();
if (type == typeof(String))
return ResourceTypeCode.String;
else if (type == typeof(Int32))
return ResourceTypeCode.Int32;
else if (type == typeof(Boolean))
return ResourceTypeCode.Boolean;
else if (type == typeof(Char))
return ResourceTypeCode.Char;
else if (type == typeof(Byte))
return ResourceTypeCode.Byte;
else if (type == typeof(SByte))
return ResourceTypeCode.SByte;
else if (type == typeof(Int16))
return ResourceTypeCode.Int16;
else if (type == typeof(Int64))
return ResourceTypeCode.Int64;
else if (type == typeof(UInt16))
return ResourceTypeCode.UInt16;
else if (type == typeof(UInt32))
return ResourceTypeCode.UInt32;
else if (type == typeof(UInt64))
return ResourceTypeCode.UInt64;
else if (type == typeof(Single))
return ResourceTypeCode.Single;
else if (type == typeof(Double))
return ResourceTypeCode.Double;
else if (type == typeof (Decimal))
return ResourceTypeCode.Decimal;
else if (type == typeof(DateTime))
return ResourceTypeCode.DateTime;
else if (type == typeof(TimeSpan))
return ResourceTypeCode.TimeSpan;
else if (type == typeof(byte[]))
return ResourceTypeCode.ByteArray;
else if (type == typeof(StreamWrapper))
return ResourceTypeCode.Stream;
// This is a user type, or a precanned resource. Find type
// table index. If not there, add new element.
String typeName;
if (type == typeof(PrecannedResource)) {
typeName = ((PrecannedResource)value).TypeName;
if (typeName.StartsWith("ResourceTypeCode.", StringComparison.Ordinal)) {
typeName = typeName.Substring(17); // Remove through '.'
ResourceTypeCode typeCode = (ResourceTypeCode)Enum.Parse(typeof(ResourceTypeCode), typeName);
return typeCode;
}
}
else
{
typeName = MultitargetingHelpers.GetAssemblyQualifiedName(type, typeConverter);
}
int typeIndex = types.IndexOf(typeName);
if (typeIndex == -1) {
typeIndex = types.Count;
types.Add(typeName);
}
return (ResourceTypeCode)(typeIndex + ResourceTypeCode.StartOfUserTypes);
}
#if FEATURE_SERIALIZATION
private void WriteValue(ResourceTypeCode typeCode, Object value, BinaryWriter writer, IFormatter objFormatter)
#else
private void WriteValue(ResourceTypeCode typeCode, Object value, BinaryWriter writer)
#endif // FEATURE_SERIALIZATION
{
Contract.Requires(writer != null);
switch(typeCode) {
case ResourceTypeCode.Null:
break;
case ResourceTypeCode.String:
writer.Write((String) value);
break;
case ResourceTypeCode.Boolean:
writer.Write((bool) value);
break;
case ResourceTypeCode.Char:
writer.Write((UInt16) (char) value);
break;
case ResourceTypeCode.Byte:
writer.Write((byte) value);
break;
case ResourceTypeCode.SByte:
writer.Write((sbyte) value);
break;
case ResourceTypeCode.Int16:
writer.Write((Int16) value);
break;
case ResourceTypeCode.UInt16:
writer.Write((UInt16) value);
break;
case ResourceTypeCode.Int32:
writer.Write((Int32) value);
break;
case ResourceTypeCode.UInt32:
writer.Write((UInt32) value);
break;
case ResourceTypeCode.Int64:
writer.Write((Int64) value);
break;
case ResourceTypeCode.UInt64:
writer.Write((UInt64) value);
break;
case ResourceTypeCode.Single:
writer.Write((Single) value);
break;
case ResourceTypeCode.Double:
writer.Write((Double) value);
break;
case ResourceTypeCode.Decimal:
writer.Write((Decimal) value);
break;
case ResourceTypeCode.DateTime:
// Use DateTime's ToBinary & FromBinary.
Int64 data = ((DateTime) value).ToBinary();
writer.Write(data);
break;
case ResourceTypeCode.TimeSpan:
writer.Write(((TimeSpan) value).Ticks);
break;
// Special Types
case ResourceTypeCode.ByteArray:
{
byte[] bytes = (byte[]) value;
writer.Write(bytes.Length);
writer.Write(bytes, 0, bytes.Length);
break;
}
case ResourceTypeCode.Stream:
{
StreamWrapper sw = (StreamWrapper)value;
if (sw.m_stream.GetType() == typeof(MemoryStream))
{
MemoryStream ms = (MemoryStream)sw.m_stream;
if (ms.Length > Int32.MaxValue)
throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
int offset, len;
ms.InternalGetOriginAndLength(out offset, out len);
byte[] bytes = ms.InternalGetBuffer();
writer.Write(len);
writer.Write(bytes, offset, len);
}
else
{
Stream s = sw.m_stream;
// we've already verified that the Stream is seekable
if (s.Length > Int32.MaxValue)
throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
s.Position = 0;
writer.Write((int)s.Length);
byte[] buffer = new byte[_DefaultBufferSize];
int read = 0;
while ((read = s.Read(buffer, 0, buffer.Length)) != 0)
{
writer.Write(buffer, 0, read);
}
if (sw.m_closeAfterWrite)
{
s.Close();
}
}
break;
}
default:
Contract.Assert(typeCode >= ResourceTypeCode.StartOfUserTypes, String.Format(CultureInfo.InvariantCulture, "ResourceReader: Unsupported ResourceTypeCode in .resources file! {0}", typeCode));
#if FEATURE_SERIALIZATION
objFormatter.Serialize(writer.BaseStream, value);
break;
#else
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization"));
#endif // FEATURE_SERIALIZATION
}
}
private static void Write7BitEncodedInt(BinaryWriter store, int value) {
Contract.Requires(store != null);
// Write out an int 7 bits at a time. The high bit of the byte,
// when on, tells reader to continue reading more bytes.
uint v = (uint) value; // support negative numbers
while (v >= 0x80) {
store.Write((byte) (v | 0x80));
v >>= 7;
}
store.Write((byte)v);
}
}
}
| |
// 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.PortsTests;
using System.Threading;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class Parity_Property : PortsTest
{
//The default number of bytes to read/write to verify the speed of the port
//and that the bytes were transfered successfully
private const int DEFAULT_BYTE_SIZE = 512;
//If the percentage difference between the expected time to transfer with the specified parity
//and the actual time found through Stopwatch is greater then 10% then the Parity value was not correctly
//set and the testcase fails.
private const double MAX_ACCEPTABEL_PERCENTAGE_DIFFERENCE = .10;
//The default number of databits to use when testing Parity
private const int DEFUALT_DATABITS = 8;
private const int NUM_TRYS = 3;
private enum ThrowAt { Set, Open };
#region Test Cases
[ConditionalFact(nameof(HasNullModem))]
public void Parity_Default()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default Parity");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyParity(com1, DEFAULT_BYTE_SIZE);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Parity_None_BeforeOpen()
{
Debug.WriteLine("Verifying None Parity before open");
VerifyParityBeforeOpen((int)Parity.None, DEFAULT_BYTE_SIZE);
}
[ConditionalFact(nameof(HasNullModem))]
public void Parity_Even_BeforeOpen()
{
Debug.WriteLine("Verifying Even Parity before open");
VerifyParityBeforeOpen((int)Parity.Even, DEFAULT_BYTE_SIZE);
}
[ConditionalFact(nameof(HasNullModem))]
public void Parity_Odd_BeforeOpen()
{
Debug.WriteLine("Verifying Odd Parity before open");
VerifyParityBeforeOpen((int)Parity.Odd, DEFAULT_BYTE_SIZE);
}
[ConditionalFact(nameof(HasNullModem))]
public void Parity_Mark_BeforeOpen()
{
Debug.WriteLine("Verifying Mark Parity before open");
VerifyParityBeforeOpen((int)Parity.Mark, DEFAULT_BYTE_SIZE);
}
[ConditionalFact(nameof(HasNullModem))]
public void Parity_Space_BeforeOpen()
{
Debug.WriteLine("Verifying Space before open");
VerifyParityBeforeOpen((int)Parity.Space, DEFAULT_BYTE_SIZE);
}
[ConditionalFact(nameof(HasNullModem))]
public void Parity_None_AfterOpen()
{
Debug.WriteLine("Verifying None Parity after open");
VerifyParityAfterOpen((int)Parity.None, DEFAULT_BYTE_SIZE);
}
[ConditionalFact(nameof(HasNullModem))]
public void Parity_Even_AfterOpen()
{
Debug.WriteLine("Verifying Even Parity after open");
VerifyParityAfterOpen((int)Parity.Even, DEFAULT_BYTE_SIZE);
}
[ConditionalFact(nameof(HasNullModem))]
public void Parity_Odd_AfterOpen()
{
Debug.WriteLine("Verifying Odd Parity after open");
VerifyParityAfterOpen((int)Parity.Odd, DEFAULT_BYTE_SIZE);
}
[ConditionalFact(nameof(HasNullModem))]
public void Parity_Mark_AfterOpen()
{
Debug.WriteLine("Verifying Mark Parity after open");
VerifyParityAfterOpen((int)Parity.Mark, DEFAULT_BYTE_SIZE);
}
[ConditionalFact(nameof(HasNullModem))]
public void Parity_Space_AfterOpen()
{
Debug.WriteLine("Verifying Space Parity after open");
VerifyParityAfterOpen((int)Parity.Space, DEFAULT_BYTE_SIZE);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Parity_Int32MinValue()
{
Debug.WriteLine("Verifying Int32.MinValue Parity");
VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Parity_Neg1()
{
Debug.WriteLine("Verifying -1 Parity");
VerifyException(-1, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Parity_Int32MaxValue()
{
Debug.WriteLine("Verifying Int32.MaxValue Parity");
VerifyException(int.MaxValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasNullModem))]
public void Parity_Even_Odd()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying Parity Even and then Odd");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
com1.Parity = Parity.Even;
com1.Parity = Parity.Odd;
serPortProp.SetProperty("Parity", Parity.Odd);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyParity(com1, DEFAULT_BYTE_SIZE);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Parity_Odd_Even()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying Parity Odd and then Even");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
com1.Parity = Parity.Odd;
com1.Parity = Parity.Even;
serPortProp.SetProperty("Parity", Parity.Even);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyParity(com1, DEFAULT_BYTE_SIZE);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Parity_Odd_Mark()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying Parity Odd and then Mark");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
com1.Parity = Parity.Odd;
com1.Parity = Parity.Mark;
serPortProp.SetProperty("Parity", Parity.Mark);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyParity(com1, DEFAULT_BYTE_SIZE);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
#endregion
#region Verification for Test Cases
private void VerifyException(int parity, ThrowAt throwAt, Type expectedException)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
VerifyExceptionAtOpen(com, parity, throwAt, expectedException);
if (com.IsOpen)
com.Close();
VerifyExceptionAfterOpen(com, parity, expectedException);
}
}
private void VerifyExceptionAtOpen(SerialPort com, int parity, ThrowAt throwAt, Type expectedException)
{
int origParity = (int)com.Parity;
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
if (ThrowAt.Open == throwAt)
serPortProp.SetProperty("Parity", (Parity)parity);
try
{
com.Parity = (Parity)parity;
if (ThrowAt.Open == throwAt)
com.Open();
if (null != expectedException)
{
Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException);
}
}
catch (Exception e)
{
if (null == expectedException)
{
Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType());
}
else if (e.GetType() != expectedException)
{
Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType());
}
}
serPortProp.VerifyPropertiesAndPrint(com);
com.Parity = (Parity)origParity;
}
private void VerifyExceptionAfterOpen(SerialPort com, int parity, Type expectedException)
{
SerialPortProperties serPortProp = new SerialPortProperties();
com.Open();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
try
{
com.Parity = (Parity)parity;
if (null != expectedException)
{
Fail("ERROR!!! Expected setting the Parity after Open() to throw {0} and nothing was thrown", expectedException);
}
}
catch (Exception e)
{
if (null == expectedException)
{
Fail("ERROR!!! Expected setting the Parity after Open() NOT to throw an exception and {0} was thrown", e.GetType());
}
else if (e.GetType() != expectedException)
{
Fail("ERROR!!! Expected setting the Parity after Open() throw {0} and {1} was thrown", expectedException, e.GetType());
}
}
serPortProp.VerifyPropertiesAndPrint(com);
}
private void VerifyParityBeforeOpen(int parity, int numBytesToSend)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Parity = (Parity)parity;
com1.Open();
serPortProp.SetProperty("Parity", (Parity)parity);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyParity(com1, numBytesToSend);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
private void VerifyParityAfterOpen(int parity, int numBytesToSend)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
com1.Parity = (Parity)parity;
serPortProp.SetProperty("Parity", (Parity)parity);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyParity(com1, numBytesToSend);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
private void VerifyParity(SerialPort com1, int numBytesToSend)
{
VerifyParity(com1, numBytesToSend, DEFUALT_DATABITS);
}
private void VerifyParity(SerialPort com1, int numBytesToSend, int dataBits)
{
byte[] xmitBytes = new byte[numBytesToSend];
byte[] expectedBytes = new byte[numBytesToSend];
Random rndGen = new Random();
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
byte shiftMask = 0xFF;
//Create a mask that when logicaly and'd with the transmitted byte will
//will result in the byte recievied due to the leading bits being chopped
//off due to Parity less then 8
if (8 > dataBits)
shiftMask >>= 8 - com1.DataBits;
//Generate some random bytes to read/write for this Parity setting
for (int i = 0; i < xmitBytes.Length; i++)
{
xmitBytes[i] = (byte)rndGen.Next(0, 256);
expectedBytes[i] = (byte)(xmitBytes[i] & shiftMask);
}
com2.DataBits = dataBits;
com2.Parity = com1.Parity;
com1.DataBits = dataBits;
com2.Open();
PerformWriteRead(com1, com2, xmitBytes, expectedBytes);
}
}
private void VerifyReadParity(int parity, int dataBits, int numBytesToSend)
{
byte[] xmitBytes = new byte[numBytesToSend];
byte[] expectedBytes = new byte[numBytesToSend];
Random rndGen = new Random();
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
byte shiftMask = 0xFF;
bool parityErrorOnLastByte = false, isParityError = false;
int parityIndex;
byte parityErrorByte;
if (8 > dataBits)
com1.DataBits = dataBits + 1;
else
com1.Parity = (Parity)parity;
com2.Parity = (Parity)parity;
com2.DataBits = dataBits;
com1.StopBits = StopBits.One;
com2.StopBits = StopBits.One;
//Create a mask that when logicaly and'd with the transmitted byte will
//will result in the byte recievied due to the leading bits being chopped
//off due to Parity less then 8
shiftMask >>= 8 - dataBits;
//Generate some random bytes to read/write for this Parity setting
for (int i = 0; i < xmitBytes.Length; i++)
{
do
{
xmitBytes[i] = (byte)rndGen.Next(0, 256);
isParityError = !VerifyParityByte(xmitBytes[i], com1.DataBits, (Parity)parity);
} while (isParityError); //Prevent adacent parity errors see VSWhidbey 103979
expectedBytes[i] = (byte)(xmitBytes[i] & shiftMask);
parityErrorOnLastByte = isParityError;
}
do
{
parityErrorByte = (byte)rndGen.Next(0, 256);
isParityError = !VerifyParityByte(parityErrorByte, com1.DataBits, (Parity)parity);
} while (!isParityError);
parityIndex = rndGen.Next(xmitBytes.Length / 4, xmitBytes.Length / 2);
xmitBytes[parityIndex] = parityErrorByte;
expectedBytes[parityIndex] = com2.ParityReplace;
Debug.WriteLine("parityIndex={0}", parityIndex);
parityIndex = rndGen.Next((3 * xmitBytes.Length) / 4, xmitBytes.Length - 1);
xmitBytes[parityIndex] = parityErrorByte;
expectedBytes[parityIndex] = com2.ParityReplace;
Debug.WriteLine("parityIndex={0}", parityIndex);
/*
for(int i=0; i<xmitBytes.Length; i++) {
do {
xmitBytes[i] = (byte)rndGen.Next(0, 256);
isParityError = !VerifyParityByte(xmitBytes[i], com1.DataBits, (Parity)parity);
}while(parityErrorOnLastByte && isParityError); //Prevent adacent parity errors see VSWhidbey 103979
expectedBytes[i] = isParityError ? com2.ParityReplace :(byte)(xmitBytes[i] & shiftMask);
parityErrorOnLastByte = isParityError;
}
*/
com1.Open();
com2.Open();
PerformWriteRead(com1, com2, xmitBytes, expectedBytes);
}
}
private void VerifyWriteParity(int parity, int dataBits, int numBytesToSend)
{
byte[] xmitBytes = new byte[numBytesToSend];
byte[] expectedBytes = new byte[numBytesToSend];
Random rndGen = new Random();
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
//Generate some random bytes to read/write for this Parity setting
for (int i = 0; i < xmitBytes.Length; i++)
{
xmitBytes[i] = (byte)rndGen.Next(0, 256);
expectedBytes[i] = SetParityBit((byte)(xmitBytes[i]), dataBits, (Parity)parity);
}
if (8 > dataBits)
com2.DataBits = dataBits + 1;
else
com2.Parity = (Parity)parity;
com1.Parity = (Parity)parity;
com1.DataBits = dataBits;
com1.Open();
com2.Open();
PerformWriteRead(com1, com2, xmitBytes, expectedBytes);
}
}
private void PerformWriteRead(SerialPort com1, SerialPort com2, byte[] xmitBytes, byte[] expectedBytes)
{
byte[] rcvBytes = new byte[expectedBytes.Length * 4];
Stopwatch sw = new Stopwatch();
double expectedTime, actualTime, percentageDifference;
int numParityBits = (Parity)com1.Parity == Parity.None ? 0 : 1;
double numStopBits = GetNumberOfStopBits(com1);
int length = xmitBytes.Length;
int rcvLength;
// TODO: Consider removing all of the code to check the time it takes to transfer the bytes.
// This was likely just a copy and paste from another test case
actualTime = 0;
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
com2.DiscardInBuffer();
IAsyncResult beginWriteResult = com1.BaseStream.BeginWrite(xmitBytes, 0, length, null, null);
while (0 == com2.BytesToRead) ;
sw.Start();
// Wait for all of the bytes to reach the input buffer of com2
TCSupport.WaitForReadBufferToLoad(com2, length);
sw.Stop();
actualTime += sw.ElapsedMilliseconds;
beginWriteResult.AsyncWaitHandle.WaitOne();
sw.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
expectedTime = ((xmitBytes.Length * (1 + numStopBits + com1.DataBits + numParityBits)) / com1.BaudRate) * 1000;
percentageDifference = Math.Abs((expectedTime - actualTime) / expectedTime);
//If the percentageDifference between the expected time and the actual time is to high
//then the expected baud rate must not have been used and we should report an error
if (MAX_ACCEPTABEL_PERCENTAGE_DIFFERENCE < percentageDifference)
{
Fail("ERROR!!! Parity not used Expected time:{0}, actual time:{1} percentageDifference:{2}", expectedTime, actualTime, percentageDifference);
}
rcvLength = com2.Read(rcvBytes, 0, rcvBytes.Length);
if (0 != com2.BytesToRead)
{
Fail("ERROR!!! BytesToRead={0} expected 0", com2.BytesToRead);
}
//Verify that the bytes we sent were the same ones we received
int expectedIndex = 0, actualIndex = 0;
for (; expectedIndex < expectedBytes.Length && actualIndex < rcvBytes.Length; ++expectedIndex, ++actualIndex)
{
if (expectedBytes[expectedIndex] != rcvBytes[actualIndex])
{
if (actualIndex != rcvBytes.Length - 1 && expectedBytes[expectedIndex] == rcvBytes[actualIndex + 1])
{
//Sometimes if there is a parity error an extra byte gets added to the input stream so
//look ahead at the next byte
actualIndex++;
}
else
{
Debug.WriteLine("Bytes Sent:");
TCSupport.PrintBytes(xmitBytes);
Debug.WriteLine("Bytes Recieved:");
TCSupport.PrintBytes(rcvBytes);
Debug.WriteLine("Expected Bytes:");
TCSupport.PrintBytes(expectedBytes);
Fail(
"ERROR: Expected to read {0,2:X} at {1,3} actually read {2,2:X} sent {3,2:X}",
expectedBytes[expectedIndex],
expectedIndex,
rcvBytes[actualIndex],
xmitBytes[expectedIndex]);
}
}
}
if (expectedIndex < expectedBytes.Length)
{
Fail("ERRROR: Did not enumerate all of the expected bytes index={0} length={1}", expectedIndex, expectedBytes.Length);
}
}
private double GetNumberOfStopBits(SerialPort com)
{
double stopBits = -1;
switch (com.StopBits)
{
case StopBits.One:
stopBits = 1.0;
break;
case StopBits.OnePointFive:
stopBits = 1.5;
break;
case StopBits.Two:
stopBits = 2.0;
break;
default:
throw new ArgumentOutOfRangeException();
}
return stopBits;
}
private byte SetParityBit(byte parityByte, int dataBitSize, Parity parity)
{
byte result;
if (8 == dataBitSize)
{
return parityByte;
}
switch (parity)
{
case Parity.Even:
if (VerifyEvenParity(parityByte, dataBitSize))
result = (byte)(parityByte & (0xFF >> 8 - dataBitSize));
else
result = (byte)(parityByte | (0x80 >> 8 - (dataBitSize + 1)));
break;
case Parity.Odd:
if (VerifyOddParity(parityByte, dataBitSize))
result = (byte)(parityByte & (0xFF >> 8 - dataBitSize));
else
result = (byte)(parityByte | (0x80 >> 8 - (dataBitSize + 1)));
break;
case Parity.Mark:
result = (byte)(parityByte | (0x80 >> 8 - (dataBitSize + 1)));
break;
case Parity.Space:
result = (byte)(parityByte & (0xFF >> 8 - dataBitSize));
break;
default:
result = 0;
break;
}
if (7 > dataBitSize)
result &= (byte)(0xFF >> 8 - (dataBitSize + 1));
return result;
}
private bool VerifyParityByte(byte parityByte, int parityWordSize, Parity parity)
{
switch (parity)
{
case Parity.Even:
return VerifyEvenParity(parityByte, parityWordSize);
case Parity.Odd:
return VerifyOddParity(parityByte, parityWordSize);
case Parity.Mark:
return VerifyMarkParity(parityByte, parityWordSize);
case Parity.Space:
return VerifySpaceParity(parityByte, parityWordSize);
default:
return false;
}
}
private bool VerifyEvenParity(byte parityByte, int parityWordSize)
{
return (0 == CalcNumberOfTrueBits(parityByte, parityWordSize) % 2);
}
private bool VerifyOddParity(byte parityByte, int parityWordSize)
{
return (1 == CalcNumberOfTrueBits(parityByte, parityWordSize) % 2);
}
private bool VerifyMarkParity(byte parityByte, int parityWordSize)
{
byte parityMask = 0x80;
parityByte <<= 8 - parityWordSize;
return (0 != (parityByte & parityMask));
}
private bool VerifySpaceParity(byte parityByte, int parityWordSize)
{
byte parityMask = 0x80;
parityByte <<= 8 - parityWordSize;
return (0 == (parityByte & parityMask));
}
private int CalcNumberOfTrueBits(byte parityByte, int parityWordSize)
{
byte parityMask = 0x80;
int numTrueBits = 0;
//Debug.WriteLine("parityByte={0}", System.Convert.ToString(parityByte, 16));
parityByte <<= 8 - parityWordSize;
for (int i = 0; i < parityWordSize; i++)
{
if (0 != (parityByte & parityMask))
numTrueBits++;
parityByte <<= 1;
}
//Debug.WriteLine("Number of true bits: {0}", numTrueBits);
return numTrueBits;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Localization;
using OrchardCore.Admin;
using OrchardCore.Deployment.Remote.Services;
using OrchardCore.Deployment.Remote.ViewModels;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Navigation;
using OrchardCore.Routing;
using OrchardCore.Settings;
namespace OrchardCore.Deployment.Remote.Controllers
{
[Admin]
public class RemoteClientController : Controller
{
private readonly IDataProtector _dataProtector;
private readonly IAuthorizationService _authorizationService;
private readonly ISiteService _siteService;
private readonly RemoteClientService _remoteClientService;
private readonly INotifier _notifier;
private readonly dynamic New;
private readonly IStringLocalizer S;
private readonly IHtmlLocalizer H;
public RemoteClientController(
IDataProtectionProvider dataProtectionProvider,
RemoteClientService remoteClientService,
IAuthorizationService authorizationService,
ISiteService siteService,
IShapeFactory shapeFactory,
IStringLocalizer<RemoteClientController> stringLocalizer,
IHtmlLocalizer<RemoteClientController> htmlLocalizer,
INotifier notifier
)
{
_authorizationService = authorizationService;
_siteService = siteService;
New = shapeFactory;
S = stringLocalizer;
H = htmlLocalizer;
_notifier = notifier;
_remoteClientService = remoteClientService;
_dataProtector = dataProtectionProvider.CreateProtector("OrchardCore.Deployment").ToTimeLimitedDataProtector();
}
public async Task<IActionResult> Index(ContentOptions options, PagerParameters pagerParameters)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageRemoteClients))
{
return Forbid();
}
var siteSettings = await _siteService.GetSiteSettingsAsync();
var pager = new Pager(pagerParameters, siteSettings.PageSize);
var remoteClients = (await _remoteClientService.GetRemoteClientListAsync()).RemoteClients;
if (!string.IsNullOrWhiteSpace(options.Search))
{
remoteClients = remoteClients.Where(x => x.ClientName.Contains(options.Search, StringComparison.OrdinalIgnoreCase)).ToList();
}
var count = remoteClients.Count();
var startIndex = pager.GetStartIndex();
var pageSize = pager.PageSize;
// Maintain previous route data when generating page links
var routeData = new RouteData();
routeData.Values.Add("Options.Search", options.Search);
var pagerShape = (await New.Pager(pager)).TotalItemCount(count).RouteData(routeData);
var model = new RemoteClientIndexViewModel
{
RemoteClients = remoteClients,
Pager = pagerShape,
Options = options
};
model.Options.ContentsBulkAction = new List<SelectListItem>() {
new SelectListItem() { Text = S["Delete"], Value = nameof(ContentsBulkAction.Remove) }
};
return View(model);
}
[HttpPost, ActionName("Index")]
[FormValueRequired("submit.Filter")]
public ActionResult IndexFilterPOST(RemoteClientIndexViewModel model)
{
return RedirectToAction("Index", new RouteValueDictionary {
{ "Options.Search", model.Options.Search }
});
}
public async Task<IActionResult> Create()
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageRemoteClients))
{
return Forbid();
}
var model = new EditRemoteClientViewModel();
return View(model);
}
[HttpPost]
public async Task<IActionResult> Create(EditRemoteClientViewModel model)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageRemoteClients))
{
return Forbid();
}
if (ModelState.IsValid)
{
ValidateViewModel(model);
}
if (ModelState.IsValid)
{
await _remoteClientService.CreateRemoteClientAsync(model.ClientName, model.ApiKey);
await _notifier.SuccessAsync(H["Remote client created successfully."]);
return RedirectToAction(nameof(Index));
}
// If we got this far, something failed, redisplay form
return View(model);
}
public async Task<IActionResult> Edit(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageRemoteClients))
{
return Forbid();
}
var remoteClient = await _remoteClientService.GetRemoteClientAsync(id);
if (remoteClient == null)
{
return NotFound();
}
var model = new EditRemoteClientViewModel
{
Id = remoteClient.Id,
ClientName = remoteClient.ClientName,
ApiKey = Encoding.UTF8.GetString(_dataProtector.Unprotect(remoteClient.ProtectedApiKey)),
};
return View(model);
}
[HttpPost]
public async Task<IActionResult> Edit(EditRemoteClientViewModel model)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageRemoteClients))
{
return Forbid();
}
var remoteClient = await _remoteClientService.GetRemoteClientAsync(model.Id);
if (remoteClient == null)
{
return NotFound();
}
if (ModelState.IsValid)
{
ValidateViewModel(model);
}
if (ModelState.IsValid)
{
await _remoteClientService.TryUpdateRemoteClient(model.Id, model.ClientName, model.ApiKey);
await _notifier.SuccessAsync(H["Remote client updated successfully."]);
return RedirectToAction(nameof(Index));
}
// If we got this far, something failed, redisplay form
return View(model);
}
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageRemoteClients))
{
return Forbid();
}
var remoteClient = await _remoteClientService.GetRemoteClientAsync(id);
if (remoteClient == null)
{
return NotFound();
}
await _remoteClientService.DeleteRemoteClientAsync(id);
await _notifier.SuccessAsync(H["Remote client deleted successfully."]);
return RedirectToAction(nameof(Index));
}
[HttpPost, ActionName("Index")]
[FormValueRequired("submit.BulkAction")]
public async Task<ActionResult> IndexPost(ViewModels.ContentOptions options, IEnumerable<string> itemIds)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageRemoteInstances))
{
return Forbid();
}
if (itemIds?.Count() > 0)
{
var remoteClients = (await _remoteClientService.GetRemoteClientListAsync()).RemoteClients;
var checkedContentItems = remoteClients.Where(x => itemIds.Contains(x.Id)).ToList();
switch (options.BulkAction)
{
case ContentsBulkAction.None:
break;
case ContentsBulkAction.Remove:
foreach (var item in checkedContentItems)
{
await _remoteClientService.DeleteRemoteClientAsync(item.Id);
}
await _notifier.SuccessAsync(H["Remote clients successfully removed."]);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return RedirectToAction("Index");
}
private void ValidateViewModel(EditRemoteClientViewModel model)
{
if (String.IsNullOrWhiteSpace(model.ClientName))
{
ModelState.AddModelError(nameof(EditRemoteClientViewModel.ClientName), S["The client name is mandatory."]);
}
if (String.IsNullOrWhiteSpace(model.ApiKey))
{
ModelState.AddModelError(nameof(EditRemoteClientViewModel.ApiKey), S["The api key is mandatory."]);
}
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using ParticlePlayground;
using ParticlePlaygroundLanguage;
using PlaygroundSplines;
[CustomEditor (typeof(PlaygroundC))]
public class PlaygroundInspectorC : Editor {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Playground variables
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static PlaygroundC playgroundScriptReference;
public static SerializedObject playground;
public static SerializedProperty calculate;
public static SerializedProperty pixelFilterMode;
public static SerializedProperty globalTimeScale;
public static SerializedProperty autoGroup;
public static SerializedProperty buildZeroAlphaPixels;
public static SerializedProperty drawGizmos;
public static SerializedProperty drawSourcePositions;
public static SerializedProperty drawWireframe;
public static SerializedProperty drawSplinePreview;
public static SerializedProperty paintToolbox;
public static SerializedProperty showShuriken;
public static SerializedProperty showSnapshots;
public static SerializedProperty threadPool;
public static SerializedProperty threads;
public static SerializedProperty threadsTurbulence;
public static SerializedProperty threadsSkinned;
public static SerializedProperty maxThreads;
public static SerializedProperty particleSystems;
public static SerializedProperty manipulators;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Internal variables
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static Vector3 manipulatorHandlePosition;
public static GUIStyle boxStyle;
public static bool showSnapshotsSettings;
public static PlaygroundSettingsC playgroundSettings;
public static PlaygroundLanguageC playgroundLanguage;
public void OnEnable () {
Initialize(target as PlaygroundC);
}
public static void Initialize (PlaygroundC targetRef) {
playgroundScriptReference = targetRef;
PlaygroundC.reference = targetRef;
if (playgroundScriptReference==null) return;
playground = new SerializedObject(playgroundScriptReference);
particleSystems = playground.FindProperty("particleSystems");
manipulators = playground.FindProperty("manipulators");
calculate = playground.FindProperty("calculate");
pixelFilterMode = playground.FindProperty("pixelFilterMode");
globalTimeScale = playground.FindProperty("globalTimeScale");
autoGroup = playground.FindProperty("autoGroup");
buildZeroAlphaPixels = playground.FindProperty("buildZeroAlphaPixels");
drawGizmos = playground.FindProperty("drawGizmos");
drawSourcePositions = playground.FindProperty("drawSourcePositions");
drawWireframe = playground.FindProperty("drawWireframe");
drawSplinePreview = playground.FindProperty("drawSplinePreview");
paintToolbox = playground.FindProperty("paintToolbox");
showShuriken = playground.FindProperty("showShuriken");
showSnapshots = playground.FindProperty("showSnapshotsInHierarchy");
threadPool = playground.FindProperty("threadPoolMethod");
threads = playground.FindProperty("threadMethod");
threadsTurbulence = playground.FindProperty("turbulenceThreadMethod");
threadsSkinned = playground.FindProperty("skinnedMeshThreadMethod");
maxThreads = playground.FindProperty("maxThreads");
playgroundSettings = PlaygroundSettingsC.GetReference();
playgroundLanguage = PlaygroundSettingsC.GetLanguage();
}
public override void OnInspectorGUI () {
if (PlaygroundC.reference==null) return;
if (boxStyle==null)
boxStyle = GUI.skin.FindStyle("box");
EditorGUILayout.Separator();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(playgroundLanguage.playgroundName+" "+PlaygroundC.version+PlaygroundC.specialVersion, EditorStyles.largeLabel, GUILayout.Height(20));
EditorGUILayout.Separator();
if(GUILayout.Button(playgroundLanguage.openPlaygroundWizard, EditorStyles.toolbarButton, GUILayout.Width(130))) {
PlaygroundParticleWindowC.ShowWindow();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
RenderPlaygroundSettings();
if (Event.current.type == EventType.ValidateCommand &&
Event.current.commandName == "UndoRedoPerformed") {
foreach (PlaygroundParticlesC p in playgroundScriptReference.particleSystems) {
p.Boot();
}
}
}
void OnSceneGUI () {
if (playgroundScriptReference!=null && playgroundScriptReference.drawGizmos && playgroundSettings.globalManipulatorsFoldout)
for (int i = 0; i<playgroundScriptReference.manipulators.Count; i++)
RenderManipulatorInScene(playgroundScriptReference.manipulators[i], playgroundScriptReference.manipulators[i].shape == MANIPULATORSHAPEC.Infinite? new Color(1f,.1f,.1f,1f) : playgroundScriptReference.manipulators[i].inverseBounds? new Color(1f,.6f,.4f,1f) : new Color(.4f,.6f,1f,1f));
if (GUI.changed)
EditorUtility.SetDirty (target);
}
public static void RenderManipulatorInScene (ManipulatorObjectC thisManipulator, Color manipulatorColor) {
// Draw Manipulators in Scene View
if (thisManipulator.transform.available && thisManipulator.transform.transform!=null) {
Handles.color = new Color(manipulatorColor.r,manipulatorColor.g,manipulatorColor.b,Mathf.Clamp(Mathf.Abs(thisManipulator.strength),.25f,1f));
Handles.color = thisManipulator.enabled? Handles.color : new Color(manipulatorColor.r,manipulatorColor.g,manipulatorColor.b,.2f);
// Position
if (UnityEditor.Tools.current==UnityEditor.Tool.Move)
thisManipulator.transform.transform.position = Handles.PositionHandle(thisManipulator.transform.transform.position, UnityEditor.Tools.pivotRotation==PivotRotation.Global? Quaternion.identity : thisManipulator.transform.transform.rotation);
// Rotation
else if (UnityEditor.Tools.current==UnityEditor.Tool.Rotate)
thisManipulator.transform.transform.rotation = Handles.RotationHandle(thisManipulator.transform.transform.rotation, thisManipulator.transform.transform.position);
// Scale
else if (UnityEditor.Tools.current==UnityEditor.Tool.Scale)
thisManipulator.transform.transform.localScale = Handles.ScaleHandle(thisManipulator.transform.transform.localScale, thisManipulator.transform.transform.position, thisManipulator.transform.transform.rotation, HandleUtility.GetHandleSize(thisManipulator.transform.transform.position));
// Sphere Size
if (thisManipulator.shape==MANIPULATORSHAPEC.Sphere) {
thisManipulator.size = Handles.RadiusHandle (Quaternion.identity, thisManipulator.transform.position, thisManipulator.size);
if (thisManipulator.enabled && GUIUtility.hotControl>0)
Handles.Label(thisManipulator.transform.transform.position+new Vector3(thisManipulator.size+1f,1f,0f), playgroundLanguage.size+" "+thisManipulator.size.ToString("f2"));
// Box Bounds
} else if (thisManipulator.shape==MANIPULATORSHAPEC.Box) {
DrawManipulatorBox(thisManipulator);
}
// Strength
manipulatorHandlePosition = thisManipulator.transform.transform.position+new Vector3(0f,thisManipulator.strength,0f);
// Event particles
if (thisManipulator.trackParticles) {
Handles.Label(thisManipulator.transform.transform.position+new Vector3(0f,-(thisManipulator.size+1f),0f), thisManipulator.particles.Count+" "+playgroundLanguage.particles);
}
Handles.DrawLine(thisManipulator.transform.transform.position, manipulatorHandlePosition);
thisManipulator.strength = Handles.ScaleValueHandle(thisManipulator.strength, manipulatorHandlePosition, Quaternion.identity, HandleUtility.GetHandleSize(manipulatorHandlePosition), Handles.SphereCap, 1);
if (thisManipulator.enabled && GUIUtility.hotControl>0)
Handles.Label(manipulatorHandlePosition+new Vector3(1f,1f,0f), playgroundLanguage.strength+" "+thisManipulator.strength.ToString("f2"));
Handles.color = new Color(.4f,.6f,1f,.025f);
Handles.DrawSolidDisc(thisManipulator.transform.transform.position, Camera.current.transform.forward, thisManipulator.strength);
Handles.color = new Color(.4f,.6f,1f,.5f);
Handles.DrawSolidDisc(thisManipulator.transform.transform.position, Camera.current.transform.forward, HandleUtility.GetHandleSize(thisManipulator.transform.transform.position)*.05f);
}
}
// Draws a Manipulator bounding box with handles in scene view
public static void DrawManipulatorBox (ManipulatorObjectC manipulator) {
Vector3 boxFrontTopLeft;
Vector3 boxFrontTopRight;
Vector3 boxFrontBottomLeft;
Vector3 boxFrontBottomRight;
Vector3 boxBackTopLeft;
Vector3 boxBackTopRight;
Vector3 boxBackBottomLeft;
Vector3 boxBackBottomRight;
Vector3 boxFrontDot;
Vector3 boxLeftDot;
Vector3 boxUpDot;
// Always set positive values of bounds
manipulator.bounds.extents = new Vector3(Mathf.Abs(manipulator.bounds.extents.x), Mathf.Abs(manipulator.bounds.extents.y), Mathf.Abs(manipulator.bounds.extents.z));
// Set positions from bounds
boxFrontTopLeft = new Vector3(manipulator.bounds.center.x - manipulator.bounds.extents.x, manipulator.bounds.center.y + manipulator.bounds.extents.y, manipulator.bounds.center.z - manipulator.bounds.extents.z);
boxFrontTopRight = new Vector3(manipulator.bounds.center.x + manipulator.bounds.extents.x, manipulator.bounds.center.y + manipulator.bounds.extents.y, manipulator.bounds.center.z - manipulator.bounds.extents.z);
boxFrontBottomLeft = new Vector3(manipulator.bounds.center.x - manipulator.bounds.extents.x, manipulator.bounds.center.y - manipulator.bounds.extents.y, manipulator.bounds.center.z - manipulator.bounds.extents.z);
boxFrontBottomRight = new Vector3(manipulator.bounds.center.x + manipulator.bounds.extents.x, manipulator.bounds.center.y - manipulator.bounds.extents.y, manipulator.bounds.center.z - manipulator.bounds.extents.z);
boxBackTopLeft = new Vector3(manipulator.bounds.center.x - manipulator.bounds.extents.x, manipulator.bounds.center.y + manipulator.bounds.extents.y, manipulator.bounds.center.z + manipulator.bounds.extents.z);
boxBackTopRight = new Vector3(manipulator.bounds.center.x + manipulator.bounds.extents.x, manipulator.bounds.center.y + manipulator.bounds.extents.y, manipulator.bounds.center.z + manipulator.bounds.extents.z);
boxBackBottomLeft = new Vector3(manipulator.bounds.center.x - manipulator.bounds.extents.x, manipulator.bounds.center.y - manipulator.bounds.extents.y, manipulator.bounds.center.z + manipulator.bounds.extents.z);
boxBackBottomRight = new Vector3(manipulator.bounds.center.x + manipulator.bounds.extents.x, manipulator.bounds.center.y - manipulator.bounds.extents.y, manipulator.bounds.center.z + manipulator.bounds.extents.z);
boxFrontDot = new Vector3(manipulator.bounds.center.x + manipulator.bounds.extents.x, manipulator.bounds.center.y, manipulator.bounds.center.z);
boxUpDot = new Vector3(manipulator.bounds.center.x, manipulator.bounds.center.y + manipulator.bounds.extents.y, manipulator.bounds.center.z);
boxLeftDot = new Vector3(manipulator.bounds.center.x, manipulator.bounds.center.y, manipulator.bounds.center.z + manipulator.bounds.extents.z);
// Apply transform positioning
boxFrontTopLeft = manipulator.transform.transform.TransformPoint(boxFrontTopLeft);
boxFrontTopRight = manipulator.transform.transform.TransformPoint(boxFrontTopRight);
boxFrontBottomLeft = manipulator.transform.transform.TransformPoint(boxFrontBottomLeft);
boxFrontBottomRight = manipulator.transform.transform.TransformPoint(boxFrontBottomRight);
boxBackTopLeft = manipulator.transform.transform.TransformPoint(boxBackTopLeft);
boxBackTopRight = manipulator.transform.transform.TransformPoint(boxBackTopRight);
boxBackBottomLeft = manipulator.transform.transform.TransformPoint(boxBackBottomLeft);
boxBackBottomRight = manipulator.transform.transform.TransformPoint(boxBackBottomRight);
boxFrontDot = manipulator.transform.transform.TransformPoint(boxFrontDot);
boxLeftDot = manipulator.transform.transform.TransformPoint(boxLeftDot);
boxUpDot = manipulator.transform.transform.TransformPoint(boxUpDot);
// Draw front lines
Handles.DrawLine(boxFrontTopLeft, boxFrontTopRight);
Handles.DrawLine(boxFrontTopRight, boxFrontBottomRight);
Handles.DrawLine(boxFrontBottomLeft, boxFrontTopLeft);
Handles.DrawLine(boxFrontBottomRight, boxFrontBottomLeft);
// Draw back lines
Handles.DrawLine(boxBackTopLeft, boxBackTopRight);
Handles.DrawLine(boxBackTopRight, boxBackBottomRight);
Handles.DrawLine(boxBackBottomLeft, boxBackTopLeft);
Handles.DrawLine(boxBackBottomRight, boxBackBottomLeft);
// Draw front to back lines
Handles.DrawLine(boxFrontTopLeft, boxBackTopLeft);
Handles.DrawLine(boxFrontTopRight, boxBackTopRight);
Handles.DrawLine(boxFrontBottomLeft, boxBackBottomLeft);
Handles.DrawLine(boxFrontBottomRight, boxBackBottomRight);
// Draw extents handles
boxFrontDot = Handles.Slider(boxFrontDot, manipulator.transform.right, HandleUtility.GetHandleSize(boxFrontDot)*.03f, Handles.DotCap, 0f);
boxUpDot = Handles.Slider(boxUpDot, manipulator.transform.up, HandleUtility.GetHandleSize(boxUpDot)*.03f, Handles.DotCap, 0f);
boxLeftDot = Handles.Slider(boxLeftDot, manipulator.transform.forward, HandleUtility.GetHandleSize(boxLeftDot)*.03f, Handles.DotCap, 0f);
manipulator.bounds.extents = new Vector3(
manipulator.transform.transform.InverseTransformPoint(boxFrontDot).x-manipulator.bounds.center.x,
manipulator.transform.transform.InverseTransformPoint(boxUpDot).y-manipulator.bounds.center.y,
manipulator.transform.transform.InverseTransformPoint(boxLeftDot).z-manipulator.bounds.center.z
);
}
public static void RenderPlaygroundSettings () {
if (boxStyle==null)
boxStyle = GUI.skin.FindStyle("box");
EditorGUILayout.BeginVertical(boxStyle);
if (playgroundSettings==null) {
playgroundSettings = PlaygroundSettingsC.GetReference();
playgroundLanguage = PlaygroundSettingsC.GetLanguage();
}
playgroundSettings.playgroundManagerFoldout = GUILayout.Toggle(playgroundSettings.playgroundManagerFoldout, playgroundLanguage.playgroundManager, EditorStyles.foldout);
if (playgroundSettings.playgroundManagerFoldout) {
EditorGUILayout.BeginVertical(boxStyle);
if (playgroundScriptReference==null) {
playgroundScriptReference = GameObject.FindObjectOfType<PlaygroundC>();
if (playgroundScriptReference)
Initialize(playgroundScriptReference);
}
if (playgroundSettings.playgroundFoldout && playgroundScriptReference!=null) {
playground.Update();
// Particle System List
if (GUILayout.Button(playgroundLanguage.particleSystems+" ("+playgroundScriptReference.particleSystems.Count+")", EditorStyles.toolbarDropDown)) playgroundSettings.particleSystemsFoldout=!playgroundSettings.particleSystemsFoldout;
if (playgroundSettings.particleSystemsFoldout) {
EditorGUILayout.Separator();
if (playgroundScriptReference.particleSystems.Count>0) {
for (int ps = 0; ps<playgroundScriptReference.particleSystems.Count; ps++) {
EditorGUILayout.BeginVertical(boxStyle, GUILayout.MinHeight(26));
EditorGUILayout.BeginHorizontal();
if (playgroundScriptReference.particleSystems[ps].particleSystemGameObject == Selection.activeGameObject) GUILayout.BeginHorizontal(boxStyle);
GUILayout.Label(ps.ToString(), EditorStyles.miniLabel, new GUILayoutOption[]{GUILayout.Width(18)});
if (GUILayout.Button(playgroundScriptReference.particleSystems[ps].particleSystemGameObject.name+" ("+playgroundScriptReference.particleSystems[ps].particleCount+")", EditorStyles.label)) {
Selection.activeGameObject = playgroundScriptReference.particleSystems[ps].particleSystemGameObject;
}
EditorGUILayout.Separator();
if (playgroundScriptReference.particleSystems[ps].threadMethod!=ThreadMethodLocal.Inherit) {
GUILayout.Label(playgroundLanguage.thread+": "+playgroundScriptReference.particleSystems[ps].threadMethod.ToString(), EditorStyles.miniLabel);
}
GUI.enabled = (playgroundScriptReference.particleSystems.Count>1);
if(GUILayout.Button(playgroundLanguage.upSymbol, EditorStyles.toolbarButton, new GUILayoutOption[]{GUILayout.Width(18), GUILayout.Height(16)})){
particleSystems.MoveArrayElement(ps, ps==0?playgroundScriptReference.particleSystems.Count-1:ps-1);
}
if(GUILayout.Button(playgroundLanguage.downSymbol, EditorStyles.toolbarButton, new GUILayoutOption[]{GUILayout.Width(18), GUILayout.Height(16)})){
particleSystems.MoveArrayElement(ps, ps<playgroundScriptReference.particleSystems.Count-1?ps+1:0);
}
GUI.enabled = true;
// Clone
if(GUILayout.Button("+", EditorStyles.toolbarButton, new GUILayoutOption[]{GUILayout.Width(18), GUILayout.Height(16)})){
GameObject ppsDuplicateGo = Instantiate(playgroundScriptReference.particleSystems[ps].particleSystemGameObject, playgroundScriptReference.particleSystems[ps].particleSystemTransform.position, playgroundScriptReference.particleSystems[ps].particleSystemTransform.rotation) as GameObject;
PlaygroundParticlesC ppsDuplicate = ppsDuplicateGo.GetComponent<PlaygroundParticlesC>();
// Add this to Manager
if (PlaygroundC.reference!=null) {
PlaygroundC.particlesQuantity++;
ppsDuplicate.particleSystemId = PlaygroundC.particlesQuantity;
if (PlaygroundC.reference.autoGroup && ppsDuplicate.particleSystemTransform.parent==null)
ppsDuplicate.particleSystemTransform.parent = PlaygroundC.referenceTransform;
}
}
if(GUILayout.Button("-", EditorStyles.toolbarButton, new GUILayoutOption[]{GUILayout.Width(18), GUILayout.Height(16)})){
if (EditorUtility.DisplayDialog(
playgroundLanguage.remove+" "+playgroundScriptReference.particleSystems[ps].particleSystemGameObject.name+"?",
playgroundLanguage.removeParticlePlaygroundSystem,
playgroundLanguage.yes, playgroundLanguage.no)) {
if (Selection.activeGameObject==playgroundScriptReference.particleSystems[ps].particleSystemGameObject)
Selection.activeGameObject = PlaygroundC.referenceTransform.gameObject;
PlaygroundC.Destroy(playgroundScriptReference.particleSystems[ps]);
playground.ApplyModifiedProperties();
return;
}
}
if (playgroundScriptReference.particleSystems[ps].particleSystemGameObject == Selection.activeGameObject) GUILayout.EndHorizontal();
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
}
} else {
EditorGUILayout.HelpBox(playgroundLanguage.noParticleSystems, MessageType.Info);
}
if(GUILayout.Button(playgroundLanguage.create, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))){
PlaygroundParticlesC createdParticles = PlaygroundC.Particle();
Selection.activeGameObject = createdParticles.particleSystemGameObject;
}
EditorGUILayout.Separator();
}
// Manipulators
if (GUILayout.Button(playgroundLanguage.globalManipulators+" ("+playgroundScriptReference.manipulators.Count+")", EditorStyles.toolbarDropDown)) playgroundSettings.globalManipulatorsFoldout=!playgroundSettings.globalManipulatorsFoldout;
if (playgroundSettings.globalManipulatorsFoldout) {
EditorGUILayout.Separator();
if (manipulators.arraySize>0) {
float screenDPI = playgroundSettings.GetScreenDPI();
float guiDpiScale = screenDPI / 72f;
for (int i = 0; i<manipulators.arraySize; i++) {
if (!playgroundScriptReference.manipulators[i].enabled)
GUI.contentColor = Color.gray;
string mName;
if (playgroundScriptReference.manipulators[i].transform.available) {
mName = playgroundScriptReference.manipulators[i].transform.transform.name;
if (mName.Length>24)
mName = mName.Substring(0, 24)+"...";
} else {
GUI.color = Color.red;
mName = "("+playgroundLanguage.missingTransform+")";
}
EditorGUILayout.BeginVertical(boxStyle);
EditorGUILayout.BeginHorizontal();
GUILayout.Label(i.ToString(), EditorStyles.miniLabel, GUILayout.Width(18));
playgroundScriptReference.manipulators[i].unfolded = GUILayout.Toggle(playgroundScriptReference.manipulators[i].unfolded, ManipulatorTypeName(playgroundScriptReference.manipulators[i].type), EditorStyles.foldout, GUILayout.Width(Screen.width/guiDpiScale/5));
if (playgroundScriptReference.manipulators[i].transform.available) {
if (GUILayout.Button(" ("+mName+")", EditorStyles.label)) {
Selection.activeGameObject = playgroundScriptReference.manipulators[i].transform.transform.gameObject;
}
} else {
GUILayout.Button(ManipulatorTypeName(playgroundScriptReference.manipulators[i].type)+" ("+playgroundLanguage.missingTransform+")", EditorStyles.label);
}
GUI.contentColor = Color.white;
EditorGUILayout.Separator();
GUI.enabled = (playgroundScriptReference.manipulators.Count>1);
if(GUILayout.Button(playgroundLanguage.upSymbol, EditorStyles.toolbarButton, new GUILayoutOption[]{GUILayout.Width(18), GUILayout.Height(16)})){
manipulators.MoveArrayElement(i, i==0?playgroundScriptReference.manipulators.Count-1:i-1);
}
if(GUILayout.Button(playgroundLanguage.downSymbol, EditorStyles.toolbarButton, new GUILayoutOption[]{GUILayout.Width(18), GUILayout.Height(16)})){
manipulators.MoveArrayElement(i, i<playgroundScriptReference.manipulators.Count-1?i+1:0);
}
GUI.enabled = true;
if(GUILayout.Button("+", EditorStyles.toolbarButton, new GUILayoutOption[]{GUILayout.Width(18), GUILayout.Height(16)})){
PlaygroundC.reference.manipulators.Add(playgroundScriptReference.manipulators[i].Clone());
}
if(GUILayout.Button("-", EditorStyles.toolbarButton, new GUILayoutOption[]{GUILayout.Width(18), GUILayout.Height(16)})){
if (EditorUtility.DisplayDialog(
playgroundLanguage.remove+" "+ManipulatorTypeName(playgroundScriptReference.manipulators[i].type)+" "+playgroundLanguage.manipulator+" "+i+"?",
playgroundLanguage.removeManipulator+" "+mName+"? "+playgroundLanguage.gameObjectIntact,
playgroundLanguage.yes, playgroundLanguage.no)) {
manipulators.DeleteArrayElementAtIndex(i);
playground.ApplyModifiedProperties();
return;
}
}
GUI.color = Color.white;
EditorGUILayout.EndHorizontal();
if (playgroundScriptReference.manipulators[i].unfolded && i<manipulators.arraySize) {
RenderManipulatorSettings(playgroundScriptReference.manipulators[i], manipulators.GetArrayElementAtIndex(i), true);
}
GUI.enabled = true;
EditorGUILayout.Separator();
EditorGUILayout.EndVertical();
}
} else {
EditorGUILayout.HelpBox(playgroundLanguage.noManipulators, MessageType.Info);
}
if(GUILayout.Button(playgroundLanguage.create, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))){
if (Selection.gameObjects.Length>0 && Selection.activeGameObject.transform && Selection.activeTransform!=null) {
Transform mTrans = new GameObject().transform;
mTrans.parent = PlaygroundC.referenceTransform;
mTrans.position = Selection.activeGameObject.transform.position+Vector3.up;
if (manipulators.arraySize>0)
mTrans.name = "Global Manipulator "+(manipulators.arraySize+1);
else mTrans.name = "Global Manipulator";
PlaygroundC.ManipulatorObject(mTrans);
} else
manipulators.InsertArrayElementAtIndex(manipulators.arraySize);
SceneView.RepaintAll();
}
EditorGUILayout.Separator();
}
// Advanced Settings
if (GUILayout.Button(playgroundLanguage.advanced, EditorStyles.toolbarDropDown)) playgroundSettings.advancedSettingsFoldout=!playgroundSettings.advancedSettingsFoldout;
if (playgroundSettings.advancedSettingsFoldout) {
showSnapshotsSettings = PlaygroundC.reference.showSnapshotsInHierarchy;
EditorGUILayout.Separator();
EditorGUILayout.PropertyField(calculate, new GUIContent(playgroundLanguage.calculateParticles, playgroundLanguage.calculateParticlesDescription));
EditorGUILayout.PropertyField(autoGroup, new GUIContent(playgroundLanguage.groupAutomatically, playgroundLanguage.groupAutomaticallyDescription));
EditorGUILayout.PropertyField(buildZeroAlphaPixels, new GUIContent(playgroundLanguage.buildZeroAlphaPixels, playgroundLanguage.buildZeroAlphaPixelsDescription));
EditorGUILayout.PropertyField(drawGizmos, new GUIContent(playgroundLanguage.sceneGizmos, playgroundLanguage.sceneGizmosDescription));
GUI.enabled = drawGizmos.boolValue;
EditorGUILayout.PropertyField(drawSourcePositions, new GUIContent(playgroundLanguage.sourcePositions, playgroundLanguage.sourcePositionsDescription));
EditorGUILayout.PropertyField(drawSplinePreview, new GUIContent(playgroundLanguage.drawSplinePreview, playgroundLanguage.drawSplinePreviewDescription));
PlaygroundSpline.drawSplinePreviews = drawSplinePreview.boolValue;
GUI.enabled = true;
EditorGUILayout.PropertyField(drawWireframe, new GUIContent(playgroundLanguage.wireframes, playgroundLanguage.wireframesDescription));
EditorGUILayout.PropertyField(paintToolbox, new GUIContent(playgroundLanguage.paintToolbox, playgroundLanguage.paintToolboxDescription));
EditorGUILayout.PropertyField(showShuriken, new GUIContent(playgroundLanguage.showShuriken, playgroundLanguage.showShurikenDescription));
EditorGUILayout.PropertyField(showSnapshots, new GUIContent(playgroundLanguage.advancedSnapshots, playgroundLanguage.advancedSnapshotsDescription));
EditorGUILayout.PropertyField(pixelFilterMode, new GUIContent(playgroundLanguage.pixelFilterMode, playgroundLanguage.pixelFilterModeDescription));
EditorGUILayout.PropertyField(globalTimeScale, new GUIContent(playgroundLanguage.globalTimeScale, playgroundLanguage.globalTimeScaleDescription));
EditorGUILayout.Separator();
GUILayout.BeginVertical(boxStyle);
EditorGUILayout.LabelField(playgroundLanguage.multithreading+" ("+PlaygroundC.ActiveThreads().ToString()+" "+playgroundLanguage.activeThreads+", "+PlaygroundC.ProcessorCount()+" "+playgroundLanguage.processors+")", EditorStyles.miniLabel);
EditorGUILayout.PropertyField(threadPool, new GUIContent(playgroundLanguage.threadPoolMethod, playgroundLanguage.threadPoolMethodDescription));
EditorGUILayout.PropertyField(threads, new GUIContent(playgroundLanguage.particleThreadMethod, playgroundLanguage.threadMethodDescription));
EditorGUILayout.PropertyField(threadsTurbulence, new GUIContent(playgroundLanguage.turbulenceThreadMethod, playgroundLanguage.threadMethodDescription));
EditorGUILayout.PropertyField(threadsSkinned, new GUIContent(playgroundLanguage.skinnedMeshThreadMethod, playgroundLanguage.threadMethodDescription));
GUI.enabled = playgroundScriptReference.threadMethod==ThreadMethod.Automatic;
EditorGUILayout.PropertyField(maxThreads, new GUIContent(playgroundLanguage.maxThreads, playgroundLanguage.maxThreadsDescription));
GUI.enabled = true;
switch (playgroundScriptReference.threadMethod) {
case ThreadMethod.NoThreads:EditorGUILayout.HelpBox(playgroundLanguage.threadInfo01, MessageType.Info);break;
case ThreadMethod.OnePerSystem:EditorGUILayout.HelpBox(playgroundLanguage.threadInfo02, MessageType.Info);break;
case ThreadMethod.OneForAll:EditorGUILayout.HelpBox(playgroundLanguage.threadInfo03, MessageType.Info);break;
case ThreadMethod.Automatic:EditorGUILayout.HelpBox(playgroundLanguage.threadInfo04, MessageType.Info);break;
}
GUILayout.EndHorizontal();
EditorGUILayout.Separator();
// Update snapshot visibility
if (showSnapshots.boolValue != showSnapshotsSettings) {
UpdateSnapshots();
}
// Time reset
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(playgroundLanguage.timeSimulation);
if(GUILayout.Button(playgroundLanguage.reset, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))){
PlaygroundC.TimeReset();
for (int p = 0; p<playgroundScriptReference.particleSystems.Count; p++)
playgroundScriptReference.particleSystems[p].Boot();
}
GUILayout.EndHorizontal();
}
playground.ApplyModifiedProperties();
EditorGUILayout.EndVertical();
} else {
EditorGUILayout.HelpBox(playgroundLanguage.noPlaygroundManager, MessageType.Info);
if(GUILayout.Button(playgroundLanguage.create, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))){
PlaygroundC.ResourceInstantiate("Playground Manager");
}
EditorGUILayout.EndVertical();
}
}
EditorGUILayout.EndVertical();
}
public static void UpdateSnapshots () {
foreach (PlaygroundParticlesC p in PlaygroundC.reference.particleSystems) {
foreach (PlaygroundSave snapshot in p.snapshots) {
snapshot.settings.gameObject.hideFlags = PlaygroundC.reference.showSnapshotsInHierarchy?HideFlags.None:HideFlags.HideInHierarchy;
if (Selection.activeGameObject==snapshot.settings.gameObject)
Selection.activeGameObject = null;
}
}
EditorApplication.RepaintHierarchyWindow();
}
public static void RenderManipulatorSettings (ManipulatorObjectC thisManipulator, SerializedProperty serializedManipulator, bool isPlayground) {
SerializedProperty serializedManipulatorAffects = serializedManipulator.FindPropertyRelative("affects");
SerializedProperty serializedManipulatorSize;
SerializedProperty serializedManipulatorStrength;
SerializedProperty serializedManipulatorStrengthSmoothing;
SerializedProperty serializedManipulatorStrengthDistance;
SerializedProperty serializedManipulatorApplyLifetimeStrength;
SerializedProperty serializedManipulatorLifetimeStrength;
thisManipulator.enabled = EditorGUILayout.ToggleLeft(playgroundLanguage.enabled, thisManipulator.enabled);
GUI.enabled = thisManipulator.enabled;
EditorGUILayout.PropertyField(serializedManipulator.FindPropertyRelative("transform").FindPropertyRelative("transform"), new GUIContent(playgroundLanguage.transform));
if (thisManipulator.transform.available && thisManipulator.transform.transform!=null) {
EditorGUI.indentLevel++;
thisManipulator.transform.transform.position = EditorGUILayout.Vector3Field(playgroundLanguage.position, thisManipulator.transform.transform.position);
thisManipulator.transform.transform.rotation = Quaternion.Euler(EditorGUILayout.Vector3Field(playgroundLanguage.rotation, thisManipulator.transform.transform.rotation.eulerAngles));
thisManipulator.transform.transform.localScale = EditorGUILayout.Vector3Field(playgroundLanguage.scale, thisManipulator.transform.transform.localScale);
EditorGUI.indentLevel--;
}
EditorGUILayout.Separator();
EditorGUILayout.PropertyField(serializedManipulator.FindPropertyRelative("type"), new GUIContent(playgroundLanguage.type));
// Render properties
if (thisManipulator.type==MANIPULATORTYPEC.Property)
{
GUI.enabled = thisManipulator.enabled;
RenderManipulatorProperty(thisManipulator, thisManipulator.property, serializedManipulator.FindPropertyRelative("property"));
}
if (thisManipulator.type==MANIPULATORTYPEC.Combined) {
if (thisManipulator.properties.Count>0) {
SerializedProperty serializedManipulatorProperties = serializedManipulator.FindPropertyRelative("properties");
int prevPropertyCount = thisManipulator.properties.Count;
for (int i = 0; i<thisManipulator.properties.Count; i++) {
if (thisManipulator.properties.Count!=prevPropertyCount) return;
EditorGUILayout.BeginVertical(boxStyle, GUILayout.MinHeight(26));
EditorGUILayout.BeginHorizontal();
GUILayout.Label(i.ToString(), EditorStyles.miniLabel, GUILayout.Width(18));
thisManipulator.properties[i].unfolded = GUILayout.Toggle(thisManipulator.properties[i].unfolded, thisManipulator.properties[i].type.ToString(), EditorStyles.foldout);
EditorGUILayout.Separator();
GUI.enabled = (thisManipulator.enabled&&thisManipulator.properties.Count>1);
if(GUILayout.Button(playgroundLanguage.upSymbol, EditorStyles.toolbarButton, new GUILayoutOption[]{GUILayout.Width(18), GUILayout.Height(16)})){
serializedManipulatorProperties.MoveArrayElement(i, i==0?thisManipulator.properties.Count-1:i-1);
}
if(GUILayout.Button(playgroundLanguage.downSymbol, EditorStyles.toolbarButton, new GUILayoutOption[]{GUILayout.Width(18), GUILayout.Height(16)})){
serializedManipulatorProperties.MoveArrayElement(i, i<thisManipulator.properties.Count-1?i+1:0);
}
GUI.enabled = thisManipulator.enabled;
if(GUILayout.Button("-", EditorStyles.toolbarButton, new GUILayoutOption[]{GUILayout.Width(18), GUILayout.Height(16)})){
thisManipulator.properties.RemoveAt(i);
return;
}
EditorGUILayout.EndHorizontal();
if (thisManipulator.properties[i].unfolded)
RenderManipulatorProperty(thisManipulator, thisManipulator.properties[i], serializedManipulatorProperties.GetArrayElementAtIndex(i));
EditorGUILayout.EndVertical();
}
} else {
EditorGUILayout.HelpBox(playgroundLanguage.noProperties, MessageType.Info);
}
if(GUILayout.Button(playgroundLanguage.create, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))){
thisManipulator.properties.Add(new ManipulatorPropertyC());
}
}
GUI.enabled = thisManipulator.enabled;
EditorGUILayout.Separator();
EditorGUILayout.PropertyField(serializedManipulator.FindPropertyRelative("shape"), new GUIContent(playgroundLanguage.shape));
if (thisManipulator.shape==MANIPULATORSHAPEC.Sphere) {
serializedManipulatorSize = serializedManipulator.FindPropertyRelative("size");
serializedManipulatorSize.floatValue = EditorGUILayout.Slider(playgroundLanguage.size, serializedManipulatorSize.floatValue, 0, playgroundSettings.maximumAllowedManipulatorSize);
} else if (thisManipulator.shape==MANIPULATORSHAPEC.Box) {
EditorGUILayout.PropertyField(serializedManipulator.FindPropertyRelative("bounds"), new GUIContent(playgroundLanguage.bounds));
}
EditorGUILayout.Separator();
serializedManipulatorStrength = serializedManipulator.FindPropertyRelative("strength");
serializedManipulatorStrength.floatValue = EditorGUILayout.Slider(playgroundLanguage.manipulatorStrength, serializedManipulatorStrength.floatValue, 0, playgroundSettings.maximumAllowedManipulatorStrength);
EditorGUI.indentLevel++;
serializedManipulatorStrengthSmoothing = serializedManipulator.FindPropertyRelative("strengthSmoothing");
serializedManipulatorStrengthSmoothing.floatValue = EditorGUILayout.Slider(playgroundLanguage.smoothingEffect, serializedManipulatorStrengthSmoothing.floatValue, 0, playgroundSettings.maximumAllowedManipulatorStrengthEffectors);
serializedManipulatorStrengthDistance = serializedManipulator.FindPropertyRelative("strengthDistanceEffect");
serializedManipulatorStrengthDistance.floatValue = EditorGUILayout.Slider(playgroundLanguage.distanceEffect, serializedManipulatorStrengthDistance.floatValue, 0, playgroundSettings.maximumAllowedManipulatorStrengthEffectors);
EditorGUI.indentLevel--;
EditorGUILayout.BeginHorizontal();
serializedManipulatorApplyLifetimeStrength = serializedManipulator.FindPropertyRelative("applyParticleLifetimeStrength");
serializedManipulatorLifetimeStrength = serializedManipulator.FindPropertyRelative("particleLifetimeStrength");
serializedManipulatorApplyLifetimeStrength.boolValue = EditorGUILayout.ToggleLeft(playgroundLanguage.particleLifetimeStrength, serializedManipulatorApplyLifetimeStrength.boolValue, GUILayout.MaxWidth (150));
GUILayout.FlexibleSpace();
GUI.enabled = serializedManipulatorApplyLifetimeStrength.boolValue && thisManipulator.enabled;
EditorGUILayout.PropertyField(serializedManipulatorLifetimeStrength, new GUIContent(""));
GUI.enabled = thisManipulator.enabled;
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
GUILayout.BeginHorizontal();
thisManipulator.applyLifetimeFilter = EditorGUILayout.ToggleLeft (playgroundLanguage.lifetimeFilter, thisManipulator.applyLifetimeFilter, GUILayout.MaxWidth(120));
float minFilter = thisManipulator.lifetimeFilterMinimum;
float maxFilter = thisManipulator.lifetimeFilterMaximum;
EditorGUILayout.MinMaxSlider (ref minFilter, ref maxFilter, 0f, 1f, GUILayout.ExpandWidth(false));
thisManipulator.lifetimeFilterMinimum = EditorGUILayout.FloatField(Mathf.Clamp01(minFilter), GUILayout.Width(50));
thisManipulator.lifetimeFilterMaximum = EditorGUILayout.FloatField(Mathf.Clamp01(maxFilter), GUILayout.Width(50));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
thisManipulator.applyParticleFilter = EditorGUILayout.ToggleLeft (playgroundLanguage.particleFilter, thisManipulator.applyParticleFilter, GUILayout.MaxWidth(120));
minFilter = thisManipulator.particleFilterMinimum;
maxFilter = thisManipulator.particleFilterMaximum;
EditorGUILayout.MinMaxSlider (ref minFilter, ref maxFilter, 0f, 1f, GUILayout.ExpandWidth(false));
thisManipulator.particleFilterMinimum = EditorGUILayout.FloatField(Mathf.Clamp01(minFilter), GUILayout.Width(50));
thisManipulator.particleFilterMaximum = EditorGUILayout.FloatField(Mathf.Clamp01(maxFilter), GUILayout.Width(50));
GUILayout.EndHorizontal();
EditorGUILayout.Separator();
if (thisManipulator.shape != MANIPULATORSHAPEC.Infinite)
thisManipulator.inverseBounds = EditorGUILayout.Toggle(playgroundLanguage.inverseBounds, thisManipulator.inverseBounds);
EditorGUILayout.Separator();
// Axis constraints
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField(playgroundLanguage.axisConstraints, GUILayout.MaxWidth(120));
GUILayout.Label("X", GUILayout.Width(10));
thisManipulator.axisConstraints.x = EditorGUILayout.Toggle(thisManipulator.axisConstraints.x, GUILayout.Width(16));
GUILayout.Label("Y", GUILayout.Width(10));
thisManipulator.axisConstraints.y = EditorGUILayout.Toggle(thisManipulator.axisConstraints.y, GUILayout.Width(16));
GUILayout.Label("Z", GUILayout.Width(10));
thisManipulator.axisConstraints.z = EditorGUILayout.Toggle(thisManipulator.axisConstraints.z, GUILayout.Width(16));
GUILayout.EndHorizontal();
if (isPlayground) {
EditorGUILayout.Separator();
EditorGUILayout.PropertyField(serializedManipulatorAffects, new GUIContent(playgroundLanguage.affects));
}
EditorGUILayout.Separator();
GUILayout.BeginVertical(boxStyle);
GUILayout.BeginHorizontal();
thisManipulator.sendEventsUnfolded = GUILayout.Toggle(thisManipulator.sendEventsUnfolded, playgroundLanguage.events, EditorStyles.foldout, GUILayout.ExpandWidth(false));
if (thisManipulator.trackParticles) {
thisManipulator.sendEventsUnfolded = GUILayout.Toggle(thisManipulator.sendEventsUnfolded, thisManipulator.particles.Count+" "+playgroundLanguage.particles, EditorStyles.label, GUILayout.ExpandWidth(true));
} else {
thisManipulator.sendEventsUnfolded = GUILayout.Toggle(thisManipulator.sendEventsUnfolded, "("+playgroundLanguage.off+")", EditorStyles.label, GUILayout.ExpandWidth(true));
}
GUILayout.EndHorizontal();
if (thisManipulator.sendEventsUnfolded) {
thisManipulator.trackParticles = EditorGUILayout.Toggle (playgroundLanguage.trackParticles, thisManipulator.trackParticles);
EditorGUI.indentLevel++;
GUI.enabled = thisManipulator.trackParticles;
thisManipulator.trackingMethod = (TrackingMethod)EditorGUILayout.EnumPopup(playgroundLanguage.trackingMethod, thisManipulator.trackingMethod);
thisManipulator.sendEventEnter = EditorGUILayout.Toggle (playgroundLanguage.sendEnterEvents, thisManipulator.sendEventEnter);
thisManipulator.sendEventExit = EditorGUILayout.Toggle (playgroundLanguage.sendExitEvents, thisManipulator.sendEventExit);
thisManipulator.sendEventBirth = EditorGUILayout.Toggle (playgroundLanguage.sendBirthEvents, thisManipulator.sendEventBirth);
thisManipulator.sendEventDeath = EditorGUILayout.Toggle (playgroundLanguage.sendDeathEvents, thisManipulator.sendEventDeath);
thisManipulator.sendEventCollision = EditorGUILayout.Toggle (playgroundLanguage.sendCollisionEvents, thisManipulator.sendEventCollision);
GUI.enabled = true;
EditorGUI.indentLevel--;
}
GUILayout.EndVertical();
}
public static void RenderManipulatorProperty (ManipulatorObjectC thisManipulator, ManipulatorPropertyC thisManipulatorProperty, SerializedProperty serializedManipulatorProperty) {
if (thisManipulatorProperty == null) thisManipulatorProperty = new ManipulatorPropertyC();
thisManipulatorProperty.type = (MANIPULATORPROPERTYTYPEC)EditorGUILayout.EnumPopup(playgroundLanguage.propertyType, thisManipulatorProperty.type);
bool guiEnabled = GUI.enabled;
bool hasRange = thisManipulator.shape != MANIPULATORSHAPEC.Infinite;
EditorGUILayout.Separator();
// Velocity
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.Velocity || thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.AdditiveVelocity) {
thisManipulatorProperty.velocity = EditorGUILayout.Vector3Field(playgroundLanguage.particleVelocity, thisManipulatorProperty.velocity);
thisManipulatorProperty.strength = EditorGUILayout.FloatField(playgroundLanguage.velocityStrength, thisManipulatorProperty.strength);
thisManipulatorProperty.useLocalRotation = EditorGUILayout.Toggle(playgroundLanguage.localRotation, thisManipulatorProperty.useLocalRotation);
} else
// Color
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.Color) {
thisManipulatorProperty.color = EditorGUILayout.ColorField(playgroundLanguage.particleColor, thisManipulatorProperty.color);
thisManipulatorProperty.strength = EditorGUILayout.FloatField(playgroundLanguage.colorStrength, thisManipulatorProperty.strength);
thisManipulatorProperty.onlyColorInRange = EditorGUILayout.Toggle(playgroundLanguage.onlyColorInRange, thisManipulatorProperty.onlyColorInRange);
thisManipulatorProperty.keepColorAlphas = EditorGUILayout.Toggle(playgroundLanguage.keepColorAlphas, thisManipulatorProperty.keepColorAlphas);
} else
// Size
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.Size) {
thisManipulatorProperty.size = EditorGUILayout.FloatField(playgroundLanguage.particleSize, thisManipulatorProperty.size);
thisManipulatorProperty.strength = EditorGUILayout.FloatField(playgroundLanguage.sizeStrength, thisManipulatorProperty.strength);
thisManipulatorProperty.onlySizeInRange = EditorGUILayout.Toggle(playgroundLanguage.onlySizeInRange, thisManipulatorProperty.onlySizeInRange);
} else
// Target
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.Target) {
// Target List
bool hasNull = false;
EditorGUILayout.BeginVertical(boxStyle);
playgroundSettings.manipulatorTargetsFoldout = GUILayout.Toggle(playgroundSettings.manipulatorTargetsFoldout, playgroundLanguage.targets+" ("+thisManipulatorProperty.targets.Count+")", EditorStyles.foldout);
if (playgroundSettings.manipulatorTargetsFoldout) {
if (thisManipulatorProperty.targets.Count>0) {
for (int t = 0; t<thisManipulatorProperty.targets.Count; t++) {
EditorGUILayout.BeginVertical(boxStyle, GUILayout.MinHeight(26));
EditorGUILayout.BeginHorizontal();
GUILayout.Label(t.ToString(), EditorStyles.miniLabel, GUILayout.Width(18));
thisManipulatorProperty.targets[t].transform = EditorGUILayout.ObjectField("", thisManipulatorProperty.targets[t].transform, typeof(Transform), true, GUILayout.MinWidth(40)) as Transform;
if (!thisManipulatorProperty.targets[t].available) hasNull = true;
EditorGUILayout.Separator();
if(GUILayout.Button("-", EditorStyles.toolbarButton, new GUILayoutOption[]{GUILayout.Width(18), GUILayout.Height(16)})){
thisManipulatorProperty.targets.RemoveAt(t);
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
}
} else {
EditorGUILayout.HelpBox(playgroundLanguage.noTargets, MessageType.Info);
}
if (hasNull)
EditorGUILayout.HelpBox(playgroundLanguage.allTargets, MessageType.Warning);
if(GUILayout.Button(playgroundLanguage.create, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))){
PlaygroundTransformC newPlaygroundTransform = new PlaygroundTransformC();
newPlaygroundTransform.transform = thisManipulator.transform.transform;
newPlaygroundTransform.Update ();
thisManipulatorProperty.targets.Add(newPlaygroundTransform);
}
EditorGUILayout.Separator();
}
EditorGUILayout.EndVertical();
thisManipulatorProperty.strength = EditorGUILayout.FloatField(playgroundLanguage.targetStrength, thisManipulatorProperty.strength);
if (hasRange)
thisManipulatorProperty.onlyPositionInRange = EditorGUILayout.Toggle(playgroundLanguage.onlyPositionInRange, thisManipulatorProperty.onlyPositionInRange);
thisManipulatorProperty.zeroVelocityStrength = EditorGUILayout.Slider(playgroundLanguage.manipulatorZeroVelocityStrength, thisManipulatorProperty.zeroVelocityStrength, 0, playgroundSettings.maximumAllowedManipulatorZeroVelocity);
} else
// Death
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.Death) {
thisManipulatorProperty.strength = EditorGUILayout.FloatField(playgroundLanguage.deathStrength, thisManipulatorProperty.strength);
} else
// Attractor
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.Attractor) {
thisManipulatorProperty.strength = EditorGUILayout.FloatField(playgroundLanguage.attractorStrength, thisManipulatorProperty.strength);
} else
// Gravitational
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.Gravitational) {
thisManipulatorProperty.strength = EditorGUILayout.FloatField(playgroundLanguage.gravitationalStrength, thisManipulatorProperty.strength);
} else
// Repellent
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.Repellent) {
thisManipulatorProperty.strength = EditorGUILayout.FloatField(playgroundLanguage.repellentStrength, thisManipulatorProperty.strength);
} else
// Vortex
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.Vortex) {
thisManipulatorProperty.strength = EditorGUILayout.FloatField(playgroundLanguage.vortexStrength, thisManipulatorProperty.strength);
} else
// Turbulence
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.Turbulence) {
thisManipulatorProperty.turbulenceType = (TURBULENCETYPE)EditorGUILayout.EnumPopup (playgroundLanguage.turbulenceType, thisManipulatorProperty.turbulenceType);
EditorGUI.indentLevel++;
thisManipulatorProperty.strength = EditorGUILayout.Slider(playgroundLanguage.strength, thisManipulatorProperty.strength, 0f, playgroundSettings.maximumAllowedTurbulenceStrength);
thisManipulatorProperty.turbulenceScale = EditorGUILayout.Slider(playgroundLanguage.scale, thisManipulatorProperty.turbulenceScale, 0f, playgroundSettings.maximumAllowedTurbulenceScale);
thisManipulatorProperty.turbulenceTimeScale = EditorGUILayout.Slider(playgroundLanguage.timeScale, thisManipulatorProperty.turbulenceTimeScale, 0f, playgroundSettings.maximumAllowedTurbulenceTimeScale);
EditorGUILayout.BeginHorizontal();
thisManipulatorProperty.turbulenceApplyLifetimeStrength = EditorGUILayout.ToggleLeft (playgroundLanguage.lifetimeStrength, thisManipulatorProperty.turbulenceApplyLifetimeStrength, GUILayout.Width (140));
GUILayout.FlexibleSpace();
GUI.enabled = (thisManipulatorProperty.turbulenceApplyLifetimeStrength && thisManipulatorProperty.turbulenceType!=TURBULENCETYPE.None);
serializedManipulatorProperty.FindPropertyRelative("turbulenceLifetimeStrength").animationCurveValue = EditorGUILayout.CurveField(serializedManipulatorProperty.FindPropertyRelative("turbulenceLifetimeStrength").animationCurveValue);
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
EditorGUI.indentLevel--;
} else
// Lifetime Color
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.LifetimeColor) {
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("lifetimeColor"), new GUIContent(playgroundLanguage.lifetimeColor));
thisManipulatorProperty.strength = EditorGUILayout.FloatField(playgroundLanguage.colorStrength, thisManipulatorProperty.strength);
if (hasRange)
thisManipulatorProperty.onlyColorInRange = EditorGUILayout.Toggle(playgroundLanguage.onlyColorInRange, thisManipulatorProperty.onlyColorInRange);
} else
// Mesh target
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.MeshTarget) {
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("meshTarget").FindPropertyRelative("gameObject"), new GUIContent(playgroundLanguage.meshTarget));
GUILayout.BeginVertical(boxStyle);
EditorGUILayout.LabelField(playgroundLanguage.proceduralOptions);
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("meshTargetIsProcedural"), new GUIContent(
playgroundLanguage.meshVerticesUpdate,
playgroundLanguage.meshVerticesUpdateDescription
));
GUI.enabled = guiEnabled&&serializedManipulatorProperty.FindPropertyRelative("meshTargetIsProcedural").boolValue;
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("meshTarget").FindPropertyRelative("updateNormals"), new GUIContent(
playgroundLanguage.meshNormalsUpdate,
playgroundLanguage.meshNormalsUpdateDescription
));
GUI.enabled = guiEnabled;
GUILayout.EndVertical();
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("targetSorting"), new GUIContent(playgroundLanguage.targetSorting));
thisManipulatorProperty.strength = EditorGUILayout.FloatField(playgroundLanguage.targetStrength, thisManipulatorProperty.strength);
if (hasRange)
thisManipulatorProperty.onlyPositionInRange = EditorGUILayout.Toggle(playgroundLanguage.onlyPositionInRange, thisManipulatorProperty.onlyPositionInRange);
thisManipulatorProperty.zeroVelocityStrength = EditorGUILayout.Slider(playgroundLanguage.manipulatorZeroVelocityStrength, thisManipulatorProperty.zeroVelocityStrength, 0, playgroundSettings.maximumAllowedManipulatorZeroVelocity);
} else
// Skinned mesh target
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.SkinnedMeshTarget) {
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("skinnedMeshTarget").FindPropertyRelative("gameObject"), new GUIContent(playgroundLanguage.skinnedMeshTarget));
GUILayout.BeginVertical(boxStyle);
EditorGUILayout.LabelField(playgroundLanguage.proceduralOptions);
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("meshTargetIsProcedural"), new GUIContent(
playgroundLanguage.meshVerticesUpdate,
playgroundLanguage.meshVerticesUpdateDescription
));
GUI.enabled = guiEnabled&&serializedManipulatorProperty.FindPropertyRelative("meshTargetIsProcedural").boolValue;
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("skinnedMeshTarget").FindPropertyRelative("updateNormals"), new GUIContent(
playgroundLanguage.meshNormalsUpdate,
playgroundLanguage.meshNormalsUpdateDescription
));
GUI.enabled = guiEnabled;
GUILayout.EndVertical();
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("targetSorting"), new GUIContent(playgroundLanguage.targetSorting));
thisManipulatorProperty.strength = EditorGUILayout.FloatField(playgroundLanguage.targetStrength, thisManipulatorProperty.strength);
if (hasRange)
thisManipulatorProperty.onlyPositionInRange = EditorGUILayout.Toggle(playgroundLanguage.onlyPositionInRange, thisManipulatorProperty.onlyPositionInRange);
thisManipulatorProperty.zeroVelocityStrength = EditorGUILayout.Slider(playgroundLanguage.manipulatorZeroVelocityStrength, thisManipulatorProperty.zeroVelocityStrength, 0, playgroundSettings.maximumAllowedManipulatorZeroVelocity);
} else
// State target
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.StateTarget) {
if (thisManipulatorProperty.stateTarget.stateTransform==null)
thisManipulatorProperty.stateTarget.stateTransform = thisManipulator.transform.transform;
GUILayout.BeginVertical(boxStyle);
Texture2D currentStateTexture = thisManipulatorProperty.stateTarget.stateTexture;
Mesh currentStateMesh = thisManipulatorProperty.stateTarget.stateMesh;
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("stateTarget").FindPropertyRelative("stateTransform"), new GUIContent(playgroundLanguage.transform));
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("stateTarget").FindPropertyRelative("stateMesh"), new GUIContent(playgroundLanguage.mesh));
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("stateTarget").FindPropertyRelative("stateTexture"), new GUIContent(playgroundLanguage.texture));
if (currentStateTexture!=thisManipulatorProperty.stateTarget.stateTexture || currentStateMesh!=thisManipulatorProperty.stateTarget.stateMesh)
thisManipulatorProperty.stateTarget.Initialize();
if (thisManipulatorProperty.stateTarget.stateTexture!=null)
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("stateTarget").FindPropertyRelative("stateDepthmap"), new GUIContent(playgroundLanguage.depthmap));
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("stateTarget").FindPropertyRelative("stateScale"), new GUIContent(playgroundLanguage.scale, playgroundLanguage.stateScaleDescription));
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("stateTarget").FindPropertyRelative("stateOffset"), new GUIContent(playgroundLanguage.offset, playgroundLanguage.stateOffsetDescription));
if (thisManipulatorProperty.stateTarget.stateMesh==null) {
GUILayout.BeginHorizontal();
bool currentApplyChromaKey = thisManipulatorProperty.stateTarget.applyChromaKey;
thisManipulatorProperty.stateTarget.applyChromaKey = EditorGUILayout.Toggle (playgroundLanguage.chromaKey, thisManipulatorProperty.stateTarget.applyChromaKey);
GUI.enabled = guiEnabled&&thisManipulatorProperty.stateTarget.applyChromaKey;
EditorGUIUtility.labelWidth = 1f;
Color currentChroma = new Color(thisManipulatorProperty.stateTarget.chromaKey.r,thisManipulatorProperty.stateTarget.chromaKey.g, thisManipulatorProperty.stateTarget.chromaKey.b);
thisManipulatorProperty.stateTarget.chromaKey = (Color32)EditorGUILayout.ColorField((Color)thisManipulatorProperty.stateTarget.chromaKey);
EditorGUIUtility.labelWidth = 50f;
float currentSpread = thisManipulatorProperty.stateTarget.chromaKeySpread;
thisManipulatorProperty.stateTarget.chromaKeySpread = EditorGUILayout.Slider(playgroundLanguage.spread, thisManipulatorProperty.stateTarget.chromaKeySpread, 0, 1f);
if (currentChroma!=new Color(thisManipulatorProperty.stateTarget.chromaKey.r,thisManipulatorProperty.stateTarget.chromaKey.g, thisManipulatorProperty.stateTarget.chromaKey.b) || currentSpread!=thisManipulatorProperty.stateTarget.chromaKeySpread || currentApplyChromaKey!=thisManipulatorProperty.stateTarget.applyChromaKey)
thisManipulatorProperty.stateTarget.Initialize();
GUI.enabled = guiEnabled;
EditorGUIUtility.labelWidth = 0;
GUILayout.EndHorizontal();
}
GUILayout.BeginHorizontal();
if(GUILayout.Button(playgroundLanguage.refresh, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))){
thisManipulatorProperty.stateTarget.Initialize();
}
EditorGUILayout.Separator();
EditorGUIUtility.labelWidth = 40f;
EditorGUILayout.PrefixLabel(playgroundLanguage.points+":");
EditorGUIUtility.labelWidth = 0;
EditorGUILayout.SelectableLabel(thisManipulatorProperty.stateTarget.positionLength.ToString(), GUILayout.MaxWidth(80));
GUILayout.EndHorizontal();
GUILayout.EndVertical();
EditorGUILayout.PropertyField(serializedManipulatorProperty.FindPropertyRelative("targetSorting"), new GUIContent(playgroundLanguage.targetSorting));
thisManipulatorProperty.strength = EditorGUILayout.FloatField(playgroundLanguage.targetStrength, thisManipulatorProperty.strength);
if (hasRange)
thisManipulatorProperty.onlyPositionInRange = EditorGUILayout.Toggle(playgroundLanguage.onlyPositionInRange, thisManipulatorProperty.onlyPositionInRange);
thisManipulatorProperty.zeroVelocityStrength = EditorGUILayout.Slider(playgroundLanguage.manipulatorZeroVelocityStrength, thisManipulatorProperty.zeroVelocityStrength, 0, playgroundSettings.maximumAllowedManipulatorZeroVelocity);
} else
// Spline target
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.SplineTarget) {
EditorGUILayout.BeginVertical(boxStyle);
thisManipulatorProperty.splineTarget = (PlaygroundSpline)EditorGUILayout.ObjectField(playgroundLanguage.spline, thisManipulatorProperty.splineTarget, typeof(PlaygroundSpline), true);
if (thisManipulatorProperty.splineTarget==null)
EditorGUILayout.HelpBox(playgroundLanguage.newSplineMessage, MessageType.Info);
else thisManipulatorProperty.splineTimeOffset = EditorGUILayout.Slider (playgroundLanguage.timeOffset, thisManipulatorProperty.splineTimeOffset, 0, 1f);
EditorGUILayout.Separator();
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button (playgroundLanguage.create, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) {
PlaygroundSpline spline = PlaygroundC.CreateSpline(thisManipulatorProperty);
spline.transform.parent = Selection.activeTransform;
Selection.activeGameObject = thisManipulatorProperty.splineTarget.gameObject;
}
GUI.enabled = thisManipulatorProperty.splineTarget!=null;
if (GUILayout.Button (playgroundLanguage.edit, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
Selection.activeGameObject = thisManipulatorProperty.splineTarget.gameObject;
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
EditorGUILayout.Separator();
thisManipulatorProperty.splineTargetMethod = (SPLINETARGETMETHOD)EditorGUILayout.EnumPopup(playgroundLanguage.targetMethod, thisManipulatorProperty.splineTargetMethod);
thisManipulatorProperty.strength = EditorGUILayout.FloatField(playgroundLanguage.targetStrength, thisManipulatorProperty.strength);
if (hasRange)
thisManipulatorProperty.onlyPositionInRange = EditorGUILayout.Toggle(playgroundLanguage.onlyPositionInRange, thisManipulatorProperty.onlyPositionInRange);
thisManipulatorProperty.zeroVelocityStrength = EditorGUILayout.Slider(playgroundLanguage.manipulatorZeroVelocityStrength, thisManipulatorProperty.zeroVelocityStrength, 0, playgroundSettings.maximumAllowedManipulatorZeroVelocity);
} else
if (thisManipulatorProperty.type==MANIPULATORPROPERTYTYPEC.Math) {
thisManipulatorProperty.mathProperty.property = (MATHMANIPULATORPROPERTY)EditorGUILayout.EnumPopup(playgroundLanguage.particleProperty, thisManipulatorProperty.mathProperty.property);
thisManipulatorProperty.mathProperty.type = (MATHMANIPULATORTYPE)EditorGUILayout.EnumPopup(playgroundLanguage.type, thisManipulatorProperty.mathProperty.type);
thisManipulatorProperty.mathProperty.clamp = (MATHMANIPULATORCLAMP)EditorGUILayout.EnumPopup(playgroundLanguage.clamp, thisManipulatorProperty.mathProperty.clamp);
if (thisManipulatorProperty.mathProperty.clamp!=MATHMANIPULATORCLAMP.None) {
EditorGUI.indentLevel++;
thisManipulatorProperty.mathProperty.clampFloor = EditorGUILayout.FloatField(playgroundLanguage.floor, thisManipulatorProperty.mathProperty.clampFloor);
thisManipulatorProperty.mathProperty.clampCeil = EditorGUILayout.FloatField(playgroundLanguage.ceil, thisManipulatorProperty.mathProperty.clampCeil);
EditorGUI.indentLevel--;
}
if (thisManipulatorProperty.mathProperty.property == MATHMANIPULATORPROPERTY.Rotation || thisManipulatorProperty.mathProperty.property == MATHMANIPULATORPROPERTY.Size) {
thisManipulatorProperty.mathProperty.value = EditorGUILayout.FloatField(playgroundLanguage.value, thisManipulatorProperty.mathProperty.value);
thisManipulatorProperty.mathProperty.rate = EditorGUILayout.FloatField(playgroundLanguage.rate, thisManipulatorProperty.mathProperty.rate);
} else {
thisManipulatorProperty.mathProperty.value3 = EditorGUILayout.Vector3Field(playgroundLanguage.value, thisManipulatorProperty.mathProperty.value3);
thisManipulatorProperty.mathProperty.rate3 = EditorGUILayout.Vector3Field(playgroundLanguage.rate, thisManipulatorProperty.mathProperty.rate3);
}
}
EditorGUILayout.Separator();
if (thisManipulatorProperty.type!=MANIPULATORPROPERTYTYPEC.None &&
thisManipulatorProperty.type!=MANIPULATORPROPERTYTYPEC.Attractor &&
thisManipulatorProperty.type!=MANIPULATORPROPERTYTYPEC.Gravitational &&
thisManipulatorProperty.type!=MANIPULATORPROPERTYTYPEC.Repellent &&
thisManipulatorProperty.type!=MANIPULATORPROPERTYTYPEC.Vortex &&
thisManipulatorProperty.type!=MANIPULATORPROPERTYTYPEC.Turbulence &&
thisManipulatorProperty.type!=MANIPULATORPROPERTYTYPEC.Math
) {
GUI.enabled = guiEnabled&&thisManipulatorProperty.type!=MANIPULATORPROPERTYTYPEC.AdditiveVelocity;
thisManipulatorProperty.transition = (MANIPULATORPROPERTYTRANSITIONC)EditorGUILayout.EnumPopup(playgroundLanguage.transition, thisManipulatorProperty.transition);
GUI.enabled = guiEnabled;
}
}
// Return name of a MANIPULATORTYPE
public static string ManipulatorTypeName (MANIPULATORTYPEC mType) {
string returnString;
switch (mType) {
case MANIPULATORTYPEC.None: returnString = playgroundLanguage.none; break;
case MANIPULATORTYPEC.Attractor: returnString = playgroundLanguage.attractor; break;
case MANIPULATORTYPEC.AttractorGravitational: returnString = playgroundLanguage.gravitational; break;
case MANIPULATORTYPEC.Repellent: returnString = playgroundLanguage.repellent; break;
case MANIPULATORTYPEC.Property: returnString = playgroundLanguage.property; break;
case MANIPULATORTYPEC.Combined: returnString = playgroundLanguage.combined; break;
case MANIPULATORTYPEC.Vortex: returnString = playgroundLanguage.vortex; break;
default: returnString = playgroundLanguage.manipulator; break;
}
return returnString;
}
// Return name of a MANIPULATORSHAPE
public static string ManipulatorTypeName (MANIPULATORSHAPEC mShape) {
string returnString;
switch (mShape) {
case MANIPULATORSHAPEC.Sphere: returnString = playgroundLanguage.sphere; break;
case MANIPULATORSHAPEC.Box: returnString = playgroundLanguage.box; break;
case MANIPULATORSHAPEC.Infinite: returnString = playgroundLanguage.infinite; break;
default: returnString = playgroundLanguage.nullName; break;
}
return returnString;
}
}
[InitializeOnLoad()]
class PlaygroundHierarchyIcon {
static Texture2D iconActive;
static Texture2D iconInactive;
static Texture2D iconHeavy;
static PlaygroundSettingsC playgroundSettings;
static PlaygroundHierarchyIcon () {
Set();
}
public static void Set () {
playgroundSettings = PlaygroundSettingsC.GetReference();
if (playgroundSettings.hierarchyIcon) {
iconActive = playgroundSettings.playgroundIcon;
iconInactive = playgroundSettings.playgroundIconInactive;
iconHeavy = playgroundSettings.playgroundIconHeavy;
if (iconActive!=null&&iconInactive!=null&&iconHeavy!=null) {
EditorApplication.hierarchyWindowItemOnGUI -= DrawHierarchyIcon;
EditorApplication.hierarchyWindowItemOnGUI += DrawHierarchyIcon;
}
} else EditorApplication.hierarchyWindowItemOnGUI -= DrawHierarchyIcon;
EditorApplication.RepaintHierarchyWindow();
}
static void DrawHierarchyIcon (int instanceID, Rect instanceRect) {
if (PlaygroundC.reference!=null) {
if (!playgroundSettings.hierarchyIcon) {
EditorApplication.hierarchyWindowItemOnGUI -= DrawHierarchyIcon;
return;
}
for (int i = 0; i<PlaygroundC.reference.particleSystems.Count; i++) {
if (PlaygroundC.reference.particleSystems[i] != null && instanceID==PlaygroundC.reference.particleSystems[i].particleSystemGameObject.GetInstanceID()) {
Rect rOffset = new Rect (instanceRect);
rOffset.x = 0;
if (PlaygroundC.reference.particleSystems[i].particleSystemGameObject.activeInHierarchy && PlaygroundC.reference.calculate && PlaygroundC.reference.particleSystems[i].calculate && PlaygroundC.reference.particleSystems[i].IsAlive())
if (EditorApplication.isPlaying && PlaygroundC.reference.particleSystems[i].IsReportingBadUpdateRate())
GUI.Label (rOffset, iconHeavy);
else
GUI.Label (rOffset, iconActive);
else
GUI.Label (rOffset, iconInactive);
}
}
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Drawing.Printing;
using System.Reflection;
using C1.Win.C1Preview;
using C1.C1Report;
using PCSUtils.Framework.ReportFrame;
using PCSUtils.Utils;
using C1PrintPreviewDialog = PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog;
namespace SaleByLicensor
{
public class SaleByLicensor : MarshalByRefObject, IDynamicReport
{
#region IDynamicReport Members
private string mConnectionString;
/// <summary>
/// ConnectionString, provide for the Dynamic Report
/// ALlow Dynamic Report to access the DataBase of PCS
/// </summary>
public string PCSConnectionString
{
get { return mConnectionString; }
set { mConnectionString = value; }
}
private ReportBuilder mReportBuilder;
/// <summary>
/// Report Builder Utility Object
/// Dynamic Report can use this object to render, modify, layout the report
/// </summary>
public ReportBuilder PCSReportBuilder
{
get { return mReportBuilder; }
set { mReportBuilder = value; }
}
private C1PrintPreviewControl mViewer;
/// <summary>
/// ReportViewer Object, provide for the DynamicReport,
/// allow Dynamic Report to manipulate with the REportViewer,
/// modify the report after rendered if needed
/// </summary>
public C1PrintPreviewControl PCSReportViewer
{
get { return mViewer; }
set { mViewer = value; }
}
private object mResult;
/// <summary>
/// Store other result if any. Ussually we store return DataTable here to display on the ReportViewer Form's Grid
/// </summary>
public object Result
{
get { return mResult; }
set { mResult = value; }
}
private bool mUseEngine;
/// <summary>
/// Notify PCS whether the rendering report process is run by
/// this IDynamicReport
/// or the ReportViewer Engine (in the ReportViewer form)
/// </summary>
public bool UseReportViewerRenderEngine
{
get { return mUseEngine; }
set { mUseEngine = value; }
}
private string mReportFolder;
/// <summary>
/// Inform External Process where to find out the ReportLayout ( the PCS' ReportDefinition Folder Path )
/// </summary>
public string ReportDefinitionFolder
{
get { return mReportFolder; }
set { mReportFolder = value; }
}
private string mLayoutFile;
/// <summary>
/// Inform External Process about the Layout file
/// in which PCS instruct to use
/// (PCS will assign this property while ReportViewer Form execute,
/// ReportVIewer form will use the layout file in the report config entry to put in this property)
/// </summary>
public string ReportLayoutFile
{
get { return mLayoutFile; }
set { mLayoutFile = value; }
}
/// <summary>
///
/// </summary>
/// <param name="pstrMethod">name of the method to call (which declare in the DynamicReport C# file)</param>
/// <param name="pobjParameters">Array of parameters provide to call the Method with method name = pstrMethod</param>
/// <returns></returns>
public object Invoke(string pstrMethod, object[] pobjParameters)
{
return this.GetType().InvokeMember(pstrMethod, BindingFlags.InvokeMethod, null, this, pobjParameters);
}
#endregion
public DataTable ExecuteReport(string pstrCCNID, string pstrFromDate, string pstrToDate, string pstrLicensorID, string pstrMakeItem)
{
int intMakeItem = -1;
if (pstrMakeItem != null && pstrMakeItem != string.Empty)
intMakeItem = Convert.ToInt32(Convert.ToBoolean(pstrMakeItem));
DateTime dtmFromDate = Convert.ToDateTime(pstrFromDate);
DateTime dtmToDate = Convert.ToDateTime(pstrToDate);
#region report table
DataTable dtbData = new DataTable();
dtbData.Columns.Add(new DataColumn("Licensor", typeof (string)));
dtbData.Columns.Add(new DataColumn("Model", typeof (string)));
dtbData.Columns.Add(new DataColumn("PartNo", typeof (string)));
dtbData.Columns.Add(new DataColumn("PartName", typeof (string)));
dtbData.Columns.Add(new DataColumn("Quantity", typeof (decimal)));
dtbData.Columns.Add(new DataColumn("Amount", typeof (decimal)));
dtbData.Columns.Add(new DataColumn("CostOfGoodsSold", typeof (decimal)));
#endregion
#region build report data
DataTable dtbReportData = GetReportData(pstrCCNID, dtmFromDate, dtmToDate, pstrLicensorID, intMakeItem);
DataTable dtbActualCost = GetActualCost(pstrCCNID);
DataTable dtbStdCost = GetStdCost();
DataTable dtbChargeAllocation = GetChargeAllocation(pstrCCNID);
string strLastProductID = string.Empty;
string strLastPartyID = string.Empty;
foreach (DataRow drowData in dtbReportData.Rows)
{
// party id
string strPartyID = drowData["PartyID"].ToString();
// product id
string strProductID = drowData["ProductID"].ToString();
if (strLastProductID == strProductID && strLastPartyID == strPartyID)
continue;
strLastProductID = strProductID;
strLastPartyID = strPartyID;
DataRow drowReport = dtbData.NewRow();
drowReport["Licensor"] = drowData["Licensor"];
drowReport["Model"] = drowData["Model"];
drowReport["PartNo"] = drowData["PartNo"];
drowReport["PartName"] = drowData["PartName"];
string strFilter = "PartyID = '" + strPartyID + "' AND ProductID = '" + strProductID + "'";
decimal decQuantity = 0, decAmount = 0, decDSAmount = 0;
decimal decRecycleAmount = 0, decAdjustAmount = 0;
decimal decOHDSAmount = 0, decOHRecAmount = 0, decOHAdjAmount = 0;
decimal decSumQuantity = 0, decCharge = 0, decRate = 0;
try
{
decQuantity = Convert.ToDecimal(dtbReportData.Compute("SUM(Quantity)", strFilter));
}
catch{}
try
{
decSumQuantity = Convert.ToDecimal(dtbReportData.Compute("SUM(Quantity)", "ProductID = " + strProductID));
}
catch{}
decRate = decQuantity / decSumQuantity;
try
{
decAmount = Convert.ToDecimal(dtbReportData.Compute("SUM(Amount)", strFilter));
}
catch{}
drowReport["Quantity"] = decQuantity;
drowReport["Amount"] = decAmount;
#region calculate cost of goods sold for each item
// shipped date to determine which cost period will take effect here
DateTime dtmShippedDate = (DateTime) drowData["ShippedDate"];
dtmShippedDate = new DateTime(dtmShippedDate.Year, dtmShippedDate.Month, dtmShippedDate.Day);
// filter condition
string strFilterCondition = "ProductID = '" + strProductID + "'"
+ " AND FromDate <= '" + dtmShippedDate.ToString("G") + "'"
+ " AND ToDate >= '" + dtmShippedDate.ToString("G") + "'";
#region DS Amount
try
{
decDSAmount = Convert.ToDecimal(dtbChargeAllocation.Compute("SUM(DSAmount)", strFilterCondition));
}
catch
{
decDSAmount = 0;
}
#endregion
#region Recycle Amount
try
{
decRecycleAmount = Convert.ToDecimal(dtbChargeAllocation.Compute("SUM(RecycleAmount)", strFilterCondition));
}
catch
{
decRecycleAmount = 0;
}
#endregion
#region Adjust Amount
try
{
decAdjustAmount = Convert.ToDecimal(dtbChargeAllocation.Compute("SUM(AdjustAmount)", strFilterCondition));
}
catch
{
decAdjustAmount = 0;
}
#endregion
#region OH DS Amount
try
{
decOHDSAmount = Convert.ToDecimal(dtbChargeAllocation.Compute("SUM(OH_DSAmount)", strFilterCondition));
}
catch
{
decOHDSAmount = 0;
}
#endregion
#region OH Recycle Amount
try
{
decOHRecAmount = Convert.ToDecimal(dtbChargeAllocation.Compute("SUM(OH_RecycleAmount)", strFilterCondition));
}
catch
{
decOHRecAmount = 0;
}
#endregion
#region OH Adjust Amount
try
{
decOHAdjAmount = Convert.ToDecimal(dtbChargeAllocation.Compute("SUM(OH_AdjustAmount)", strFilterCondition));
}
catch
{
decOHAdjAmount = 0;
}
#endregion
decCharge = (decDSAmount - decRecycleAmount - decAdjustAmount)
+ (decOHDSAmount - decOHRecAmount - decOHAdjAmount);
// try to get actual cost of item
DataRow[] drowActualCost = dtbActualCost.Select(strFilterCondition);
if (drowActualCost.Length > 0)
{
decimal decActualCost = 0;
try
{
decActualCost = Convert.ToDecimal(dtbActualCost.Compute("SUM(ActualCost)", strFilterCondition));
drowReport["CostOfGoodsSold"] = decQuantity * decActualCost + decCharge * decRate;
}
catch{}
}
else
{
// if item not yet rollup actual cost, try to get standard cost
DataRow[] drowStdCost = dtbStdCost.Select("ProductID = '" + strProductID + "'");
if (drowStdCost.Length > 0)
{
decimal decStdCost = 0;
try
{
decStdCost = Convert.ToDecimal(dtbStdCost.Compute("SUM(Cost)", "ProductID = '" + strProductID + "'"));
drowReport["CostOfGoodsSold"] = decQuantity * decStdCost + decCharge * decRate;
}
catch{}
}
else // if item dot have any cost
drowReport["CostOfGoodsSold"] = decimal.Zero;
}
#endregion
dtbData.Rows.Add(drowReport);
}
#endregion
#region report
C1Report rptReport = new C1Report();
mLayoutFile = "SaleByLicensor.xml";
rptReport.Load(mReportFolder + "\\" + mLayoutFile, rptReport.GetReportInfo(mReportFolder + "\\" + mLayoutFile)[0]);
rptReport.Layout.PaperSize = PaperKind.A4;
#region report parameter
try
{
rptReport.Fields["fldCCN"].Text = GetCCN(pstrCCNID);
}
catch{}
try
{
rptReport.Fields["fldFromDate"].Text = dtmFromDate.ToString("dd-MM-yyyy HH:mm");
}
catch{}
try
{
rptReport.Fields["fldToDate"].Text = dtmToDate.ToString("dd-MM-yyyy HH:mm");
}
catch{}
try
{
if (pstrLicensorID.Split(",".ToCharArray()).Length > 1)
rptReport.Fields["fldLic"].Text = "Multi-Selection";
else if (pstrLicensorID.Length > 0)
rptReport.Fields["fldLic"].Text = GetCustomerInfo(pstrLicensorID);
}
catch{}
#endregion
// set datasource object that provides data to report.
rptReport.DataSource.Recordset = dtbData;
// render report
rptReport.Render();
// render the report into the PrintPreviewControl
C1PrintPreviewDialog ppvViewer = new C1PrintPreviewDialog();
ppvViewer.FormTitle = "Sale Revenue Report (Classified By Licensors)";
ppvViewer.ReportViewer.Document = rptReport.Document;
ppvViewer.Show();
#endregion
return dtbData;
}
private DataTable GetReportData(string pstrCCNID, DateTime pdtmFromDate, DateTime pdtmToDate, string pstrLicensorID, int pintMakeItem)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS;
try
{
string strSql = "SELECT SO_ConfirmShipDetail.InvoiceQty AS Quantity, SO_ConfirmShipDetail.InvoiceQty * ISNULL(SO_ConfirmShipDetail.Price,0) * SO_ConfirmShipMaster.ExchangeRate AS Amount,"
+ " ITM_Product.Code AS PartNo, ITM_Product.Description AS PartName, ITM_Product.Revision AS Model,"
+ " MST_Party.Code AS Licensor, SO_ConfirmShipDetail.ProductID,"
+ " ShippedDate, ITM_Product.InventorID AS PartyID"
+ " FROM SO_ConfirmShipMaster JOIN SO_ConfirmShipDetail"
+ " ON SO_ConfirmShipMaster.ConfirmShipMasterID = SO_ConfirmShipDetail.ConfirmShipMasterID"
+ " JOIN ITM_Product"
+ " ON SO_ConfirmShipDetail.ProductID = ITM_Product.ProductID"
+ " JOIN SO_SaleOrderMaster"
+ " ON SO_ConfirmShipMaster.SaleOrderMasterID = SO_SaleOrderMaster.SaleOrderMasterID"
+ " JOIN SO_SaleOrderDetail"
+ " ON SO_ConfirmShipDetail.SaleOrderDetailID = SO_SaleOrderDetail.SaleOrderDetailID"
+ " JOIN MST_Party"
+ " ON ITM_Product.InventorID = MST_Party.PartyID"
+ " WHERE ShippedDate >= ?"
+ " AND ShippedDate <= ?"
+ " AND SO_ConfirmShipDetail.InvoiceQty > 0"
+ " AND SO_SaleOrderMaster.CCNID = " + pstrCCNID;
if (pstrLicensorID.Length > 0)
strSql += " AND ITM_Product.InventorID IN (" + pstrLicensorID + ")";
if (pintMakeItem >= 0)
strSql += " AND ITM_Product.MakeItem = " + pintMakeItem;
//hacked by duongna
strSql +=
" UNION ALL " +
" " +
" SELECT " +
" -SO_ReturnedGoodsDetail.ReceiveQuantity AS Quantity, " +
" -SO_ReturnedGoodsDetail.ReceiveQuantity * ISNULL(SO_ReturnedGoodsDetail.UnitPrice,0) * SO_ReturnedGoodsMaster.ExchangeRate AS Amount, " +
" ITM_Product.Code AS PartNo, " +
" ITM_Product.Description AS PartName, " +
" ITM_Product.Revision AS Model, " +
" MST_Party.Code AS Licensor, " +
" SO_ReturnedGoodsDetail.ProductID, " +
" PostDate AS ShippedDate, " +
" ITM_Product.InventorID AS PartyID " +
" FROM " +
" SO_ReturnedGoodsMaster " +
" JOIN SO_ReturnedGoodsDetail " +
" ON SO_ReturnedGoodsMaster.ReturnedGoodsMasterID = SO_ReturnedGoodsDetail.ReturnedGoodsMasterID " +
" JOIN ITM_Product " +
" ON SO_ReturnedGoodsDetail.ProductID = ITM_Product.ProductID " +
" JOIN MST_Party " +
" ON ITM_Product.InventorID = MST_Party.PartyID " +
" WHERE " +
" PostDate >= ? " +
" AND PostDate <= ? " +
" AND SO_ReturnedGoodsDetail.ReceiveQuantity > 0 " +
" AND SO_ReturnedGoodsMaster.CCNID = " + pstrCCNID;
if (pstrLicensorID.Length > 0)
strSql += " AND ITM_Product.InventorID IN (" + pstrLicensorID + ")";
if (pintMakeItem >= 0)
strSql += " AND ITM_Product.MakeItem = " + pintMakeItem;
strSql += " ORDER BY MST_Party.Code, ITM_Product.Revision, ITM_Product.Code, ITM_Product.Description";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Parameters.Add(new OleDbParameter("FromDate", OleDbType.Date)).Value = pdtmFromDate;
ocmdPCS.Parameters.Add(new OleDbParameter("ToDate", OleDbType.Date)).Value = pdtmToDate;
ocmdPCS.Parameters.Add(new OleDbParameter("FromDateReturn", OleDbType.Date)).Value = pdtmFromDate;
ocmdPCS.Parameters.Add(new OleDbParameter("ToDateReturn", OleDbType.Date)).Value = pdtmToDate;
ocmdPCS.Connection.Open();
DataTable dtbData = new DataTable();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dtbData);
return dtbData;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private DataTable GetActualCost(string pstrCCNID)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS;
try
{
string strSql = "SELECT SUM(CST_ActualCostHistory.ActualCost) AS ActualCost, CST_ActualCostHistory.ProductID,"
+ " CST_ActualCostHistory.ActCostAllocationMasterID,"
+ " CST_ActCostAllocationMaster.FromDate, CST_ActCostAllocationMaster.ToDate"
+ " FROM CST_ActualCostHistory JOIN CST_ActCostAllocationMaster"
+ " ON CST_ActualCostHistory.ActCostAllocationMasterID = CST_ActCostAllocationMaster.ActCostAllocationMasterID"
+ " WHERE CST_ActCostAllocationMaster.CCNID = " + pstrCCNID
+ " GROUP BY CST_ActualCostHistory.ProductID, CST_ActualCostHistory.ActCostAllocationMasterID,"
+ " CST_ActCostAllocationMaster.FromDate, CST_ActCostAllocationMaster.ToDate"
+ " ORDER BY CST_ActCostAllocationMaster.FromDate";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
DataTable dtbData = new DataTable();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dtbData);
return dtbData;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private DataTable GetStdCost()
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS;
try
{
string strSql = "SELECT SUM(Cost) AS Cost, ProductID"
+ " FROM CST_STDItemCost GROUP BY ProductID ORDER BY ProductID";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
DataTable dtbData = new DataTable();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dtbData);
return dtbData;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private string GetCCN(string pstrCCNID)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS;
try
{
string strSql = "SELECT Code + ' (' + Description + ')' FROM MST_CCN WHERE CCNID = " + pstrCCNID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
return objResult.ToString();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private string GetCustomerInfo(string pstrCustomerID)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS;
try
{
string strSql = "SELECT Code + ' (' + Name + ')' FROM MST_Party WHERE PartyID = " + pstrCustomerID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
return objResult.ToString();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private DataTable GetChargeAllocation(string pstrCCNID)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS;
try
{
string strSql = "SELECT SUM(CST_DSAndRecycleAllocation.DSAmount) AS DSAmount,"
+ " SUM(CST_DSAndRecycleAllocation.RecycleAmount) AS RecycleAmount,"
+ " SUM(CST_DSAndRecycleAllocation.AdjustAmount) AS AdjustAmount,"
+ " SUM(CST_DSAndRecycleAllocation.OH_RecycleAmount) AS OH_RecycleAmount,"
+ " SUM(CST_DSAndRecycleAllocation.OH_DSAmount) AS OH_DSAmount,"
+ " SUM(CST_DSAndRecycleAllocation.OH_AdjustAmount) AS OH_AdjustAmount,"
+ " CST_DSAndRecycleAllocation.ProductID,"
+ " CST_DSAndRecycleAllocation.ActCostAllocationMasterID,"
+ " CST_ActCostAllocationMaster.FromDate, CST_ActCostAllocationMaster.ToDate, STD_CostElementType.Code AS CostElementType"
+ " FROM CST_DSAndRecycleAllocation JOIN CST_ActCostAllocationMaster"
+ " ON CST_DSAndRecycleAllocation.ActCostAllocationMasterID = CST_ActCostAllocationMaster.ActCostAllocationMasterID"
+ " JOIN STD_CostElement"
+ " ON CST_DSAndRecycleAllocation.CostElementID = STD_CostElement.CostElementID"
+ " JOIN STD_CostElementType"
+ " ON STD_CostElement.CostElementTypeID = STD_CostElementType.CostElementTypeID"
+ " WHERE CST_ActCostAllocationMaster.CCNID = " + pstrCCNID
+ " GROUP BY CST_DSAndRecycleAllocation.ProductID, CST_DSAndRecycleAllocation.ActCostAllocationMasterID,"
+ " CST_ActCostAllocationMaster.FromDate, CST_ActCostAllocationMaster.ToDate, STD_CostElementType.Code"
+ " ORDER BY CST_ActCostAllocationMaster.FromDate";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
DataTable dtbData = new DataTable();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dtbData);
return dtbData;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
}
}
| |
// 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.InteropServices;
using Internal.Runtime.CompilerServices;
#pragma warning disable SA1121 // explicitly using type aliases instead of built-in types
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System.Runtime.CompilerServices
{
public static partial class RuntimeHelpers
{
// The special dll name to be used for DllImport of QCalls
internal const string QCall = "QCall";
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void InitializeArray(Array array, RuntimeFieldHandle fldHandle);
// GetObjectValue is intended to allow value classes to be manipulated as 'Object'
// but have aliasing behavior of a value class. The intent is that you would use
// this function just before an assignment to a variable of type 'Object'. If the
// value being assigned is a mutable value class, then a shallow copy is returned
// (because value classes have copy semantics), but otherwise the object itself
// is returned.
//
// Note: VB calls this method when they're about to assign to an Object
// or pass it as a parameter. The goal is to make sure that boxed
// value types work identical to unboxed value types - ie, they get
// cloned when you pass them around, and are always passed by value.
// Of course, reference types are not cloned.
//
[MethodImpl(MethodImplOptions.InternalCall)]
[return: NotNullIfNotNull("obj")]
public static extern object? GetObjectValue(object? obj);
// RunClassConstructor causes the class constructor for the given type to be triggered
// in the current domain. After this call returns, the class constructor is guaranteed to
// have at least been started by some thread. In the absence of class constructor
// deadlock conditions, the call is further guaranteed to have completed.
//
// This call will generate an exception if the specified class constructor threw an
// exception when it ran.
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _RunClassConstructor(RuntimeType type);
public static void RunClassConstructor(RuntimeTypeHandle type)
{
_RunClassConstructor(type.GetRuntimeType());
}
// RunModuleConstructor causes the module constructor for the given type to be triggered
// in the current domain. After this call returns, the module constructor is guaranteed to
// have at least been started by some thread. In the absence of module constructor
// deadlock conditions, the call is further guaranteed to have completed.
//
// This call will generate an exception if the specified module constructor threw an
// exception when it ran.
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _RunModuleConstructor(System.Reflection.RuntimeModule module);
public static void RunModuleConstructor(ModuleHandle module)
{
_RunModuleConstructor(module.GetRuntimeModule());
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern void _CompileMethod(RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern unsafe void _PrepareMethod(IRuntimeMethodInfo method, IntPtr* pInstantiation, int cInstantiation);
public static void PrepareMethod(RuntimeMethodHandle method)
{
unsafe
{
_PrepareMethod(method.GetMethodInfo(), null, 0);
}
}
public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[]? instantiation)
{
unsafe
{
int length;
IntPtr[]? instantiationHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(instantiation, out length);
fixed (IntPtr* pInstantiation = instantiationHandles)
{
_PrepareMethod(method.GetMethodInfo(), pInstantiation, length);
GC.KeepAlive(instantiation);
}
}
}
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void PrepareDelegate(Delegate d);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetHashCode(object o);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern new bool Equals(object? o1, object? o2);
public static int OffsetToStringData
{
// This offset is baked in by string indexer intrinsic, so there is no harm
// in getting it baked in here as well.
[System.Runtime.Versioning.NonVersionable]
get =>
// Number of bytes from the address pointed to by a reference to
// a String to the first 16-bit character in the String. Skip
// over the MethodTable pointer, & String
// length. Of course, the String reference points to the memory
// after the sync block, so don't count that.
// This property allows C#'s fixed statement to work on Strings.
// On 64 bit platforms, this should be 12 (8+4) and on 32 bit 8 (4+4).
#if BIT64
12;
#else // 32
8;
#endif // BIT64
}
// This method ensures that there is sufficient stack to execute the average Framework function.
// If there is not enough stack, then it throws System.InsufficientExecutionStackException.
// Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack
// below.
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void EnsureSufficientExecutionStack();
// This method ensures that there is sufficient stack to execute the average Framework function.
// If there is not enough stack, then it return false.
// Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack
// below.
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern bool TryEnsureSufficientExecutionStack();
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern object GetUninitializedObjectInternal(Type type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object AllocateUninitializedClone(object obj);
/// <returns>true if given type is reference type or value type that contains references</returns>
[Intrinsic]
public static bool IsReferenceOrContainsReferences<T>()
{
// The body of this function will be replaced by the EE with unsafe code!!!
// See getILIntrinsicImplementationForRuntimeHelpers for how this happens.
throw new InvalidOperationException();
}
/// <returns>true if given type is bitwise equatable (memcmp can be used for equality checking)</returns>
/// <remarks>
/// Only use the result of this for Equals() comparison, not for CompareTo() comparison.
/// </remarks>
[Intrinsic]
internal static bool IsBitwiseEquatable<T>()
{
// The body of this function will be replaced by the EE with unsafe code!!!
// See getILIntrinsicImplementationForRuntimeHelpers for how this happens.
throw new InvalidOperationException();
}
[Intrinsic]
internal static bool EnumEquals<T>(T x, T y) where T : struct, Enum
{
// The body of this function will be replaced by the EE with unsafe code
// See getILIntrinsicImplementation for how this happens.
return x.Equals(y);
}
[Intrinsic]
internal static int EnumCompareTo<T>(T x, T y) where T : struct, Enum
{
// The body of this function will be replaced by the EE with unsafe code
// See getILIntrinsicImplementation for how this happens.
return x.CompareTo(y);
}
internal static ref byte GetRawData(this object obj) =>
ref Unsafe.As<RawData>(obj).Data;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe nuint GetRawObjectDataSize(object obj)
{
MethodTable* pMT = GetMethodTable(obj);
// See comment on RawArrayData for details
nuint rawSize = pMT->BaseSize - (nuint)(2 * sizeof(IntPtr));
if (pMT->HasComponentSize)
rawSize += (uint)Unsafe.As<RawArrayData>(obj).Length * (nuint)pMT->ComponentSize;
GC.KeepAlive(obj); // Keep MethodTable alive
return rawSize;
}
[Intrinsic]
internal static ref byte GetRawSzArrayData(this Array array) =>
ref Unsafe.As<RawArrayData>(array).Data;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe ref byte GetRawArrayData(this Array array) =>
// See comment on RawArrayData for details
ref Unsafe.AddByteOffset(ref Unsafe.As<RawData>(array).Data, (nuint)GetMethodTable(array)->BaseSize - (nuint)(2 * sizeof(IntPtr)));
internal static unsafe ushort GetElementSize(this Array array)
{
Debug.Assert(ObjectHasComponentSize(array));
return GetMethodTable(array)->ComponentSize;
}
// Returns pointer to the multi-dimensional array bounds.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe ref int GetMultiDimensionalArrayBounds(Array array)
{
Debug.Assert(GetMultiDimensionalArrayRank(array) > 0);
// See comment on RawArrayData for details
return ref Unsafe.As<byte, int>(ref Unsafe.As<RawArrayData>(array).Data);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe int GetMultiDimensionalArrayRank(Array array)
{
int rank = GetMethodTable(array)->MultiDimensionalArrayRank;
GC.KeepAlive(array); // Keep MethodTable alive
return rank;
}
// Returns true iff the object has a component size;
// i.e., is variable length like System.String or Array.
// Callers are required to keep obj alive
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe bool ObjectHasComponentSize(object obj)
{
return GetMethodTable(obj)->HasComponentSize;
}
// Given an object reference, returns its MethodTable*.
//
// WARNING: The caller has to ensure that MethodTable* does not get unloaded. The most robust way
// to achieve this is by using GC.KeepAlive on the object that the MethodTable* was fetched from, e.g.:
//
// MethodTable* pMT = GetMethodTable(o);
//
// ... work with pMT ...
//
// GC.KeepAlive(o);
//
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe MethodTable* GetMethodTable(object obj)
{
Debug.Assert(obj != null);
// We know that the first data field in any managed object is immediately after the
// method table pointer, so just back up one pointer and immediately deref.
// This is not ideal in terms of minimizing instruction count but is the best we can do at the moment.
return (MethodTable *)Unsafe.Add(ref Unsafe.As<byte, IntPtr>(ref obj.GetRawData()), -1);
// The JIT currently implements this as:
// lea tmp, [rax + 8h] ; assume rax contains the object reference, tmp is type IntPtr&
// mov tmp, qword ptr [tmp - 8h] ; tmp now contains the MethodTable* pointer
//
// Ideally this would just be a single dereference:
// mov tmp, qword ptr [rax] ; rax = obj ref, tmp = MethodTable* pointer
}
}
// Helper class to assist with unsafe pinning of arbitrary objects.
// It's used by VM code.
internal class RawData
{
public byte Data;
}
// CLR arrays are laid out in memory as follows (multidimensional array bounds are optional):
// [ sync block || pMethodTable || num components || MD array bounds || array data .. ]
// ^ ^ ^ returned reference
// | \-- ref Unsafe.As<RawData>(array).Data
// \-- array
// The BaseSize of an array includes all the fields before the array data,
// including the sync block and method table. The reference to RawData.Data
// points at the number of components, skipping over these two pointer-sized fields.
internal class RawArrayData
{
public uint Length; // Array._numComponents padded to IntPtr
#if BIT64
public uint Padding;
#endif
public byte Data;
}
// Subset of src\vm\methodtable.h
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct MethodTable
{
[FieldOffset(0)]
public ushort ComponentSize;
[FieldOffset(0)]
private uint Flags;
[FieldOffset(4)]
public uint BaseSize;
// WFLAGS_HIGH_ENUM
private const uint enum_flag_ContainsPointers = 0x01000000;
private const uint enum_flag_HasComponentSize = 0x80000000;
public bool HasComponentSize
{
get
{
return (Flags & enum_flag_HasComponentSize) != 0;
}
}
public bool ContainsGCPointers
{
get
{
return (Flags & enum_flag_ContainsPointers) != 0;
}
}
public bool IsMultiDimensionalArray
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
Debug.Assert(HasComponentSize);
// See comment on RawArrayData for details
return BaseSize > (uint)(3 * sizeof(IntPtr));
}
}
// Returns rank of multi-dimensional array rank, 0 for sz arrays
public int MultiDimensionalArrayRank
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
Debug.Assert(HasComponentSize);
// See comment on RawArrayData for details
return (int)((BaseSize - (uint)(3 * sizeof(IntPtr))) / (uint)(2 * sizeof(int)));
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
#if DEBUG
using System.Diagnostics;
#endif
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Tagging
{
/// <summary>
/// Base type of all asynchronous tagger providers (<see cref="ITaggerProvider"/> and <see cref="IViewTaggerProvider"/>).
/// </summary>
internal abstract partial class AbstractAsynchronousTaggerProvider<TTag> : ForegroundThreadAffinitizedObject where TTag : ITag
{
private readonly object _uniqueKey = new object();
private readonly IAsynchronousOperationListener _asyncListener;
private readonly IForegroundNotificationService _notificationService;
/// <summary>
/// The behavior the tagger engine will have when text changes happen to the subject buffer
/// it is attached to. Most taggers can simply use <see cref="TaggerTextChangeBehavior.None"/>.
/// However, advanced taggers that want to perform specialized behavior depending on what has
/// actually changed in the file can specify <see cref="TaggerTextChangeBehavior.TrackTextChanges"/>.
///
/// If this is specified the tagger engine will track text changes and pass them along as
/// <see cref="TaggerContext{TTag}.TextChangeRange"/> when calling
/// <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>.
/// </summary>
protected virtual TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.None;
/// <summary>
/// The behavior the tagger will have when changes happen to the caret.
/// </summary>
protected virtual TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.None;
/// <summary>
/// The behavior of tags that are created by the async tagger. This will matter for tags
/// created for a previous version of a document that are mapped forward by the async
/// tagging architecture. This value cannot be <see cref="SpanTrackingMode.Custom"/>.
/// </summary>
protected virtual SpanTrackingMode SpanTrackingMode => SpanTrackingMode.EdgeExclusive;
/// <summary>
/// Comparer used to determine if two <see cref="ITag"/>s are the same. This is used by
/// the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> to determine if a previous set of
/// computed tags and a current set of computed tags should be considered the same or not.
/// If they are the same, then the UI will not be updated. If they are different then
/// the UI will be updated for sets of tags that have been removed or added.
/// </summary>
protected virtual IEqualityComparer<TTag> TagComparer => EqualityComparer<TTag>.Default;
/// <summary>
/// Options controlling this tagger. The tagger infrastructure will check this option
/// against the buffer it is associated with to see if it should tag or not.
///
/// An empty enumerable, or null, can be returned to indicate that this tagger should
/// run unconditionally.
/// </summary>
protected virtual IEnumerable<Option<bool>> Options => SpecializedCollections.EmptyEnumerable<Option<bool>>();
protected virtual IEnumerable<PerLanguageOption<bool>> PerLanguageOptions => SpecializedCollections.EmptyEnumerable<PerLanguageOption<bool>>();
/// <summary>
/// This controls what delay tagger will use to let editor know about newly inserted tags
/// </summary>
protected virtual TaggerDelay AddedTagNotificationDelay => TaggerDelay.NearImmediate;
/// <summary>
/// This controls what delay tagger will use to let editor know about just deleted tags.
/// </summary>
protected virtual TaggerDelay RemovedTagNotificationDelay => TaggerDelay.NearImmediate;
#if DEBUG
public readonly string StackTrace;
#endif
protected AbstractAsynchronousTaggerProvider(
IAsynchronousOperationListener asyncListener,
IForegroundNotificationService notificationService)
{
_asyncListener = asyncListener;
_notificationService = notificationService;
#if DEBUG
StackTrace = new StackTrace().ToString();
#endif
}
private TagSource CreateTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
return new TagSource(textViewOpt, subjectBuffer, this, _asyncListener, _notificationService);
}
internal IAccurateTagger<T> GetOrCreateTagger<T>(ITextView textViewOpt, ITextBuffer subjectBuffer) where T : ITag
{
if (!subjectBuffer.GetFeatureOnOffOption(EditorComponentOnOffOptions.Tagger))
{
return null;
}
var tagSource = GetOrCreateTagSource(textViewOpt, subjectBuffer);
if (tagSource == null)
{
return null;
}
return new Tagger(_asyncListener, _notificationService, tagSource, subjectBuffer) as IAccurateTagger<T>;
}
private TagSource GetOrCreateTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
if (!this.TryRetrieveTagSource(textViewOpt, subjectBuffer, out var tagSource))
{
tagSource = this.CreateTagSource(textViewOpt, subjectBuffer);
if (tagSource == null)
{
return null;
}
this.StoreTagSource(textViewOpt, subjectBuffer, tagSource);
tagSource.Disposed += (s, e) => this.RemoveTagSource(textViewOpt, subjectBuffer);
}
return tagSource;
}
private bool TryRetrieveTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer, out TagSource tagSource)
{
return textViewOpt != null
? textViewOpt.TryGetPerSubjectBufferProperty(subjectBuffer, _uniqueKey, out tagSource)
: subjectBuffer.Properties.TryGetProperty(_uniqueKey, out tagSource);
}
private void RemoveTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
if (textViewOpt != null)
{
textViewOpt.RemovePerSubjectBufferProperty<TagSource, ITextView>(subjectBuffer, _uniqueKey);
}
else
{
subjectBuffer.Properties.RemoveProperty(_uniqueKey);
}
}
private void StoreTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer, TagSource tagSource)
{
if (textViewOpt != null)
{
textViewOpt.AddPerSubjectBufferProperty(subjectBuffer, _uniqueKey, tagSource);
}
else
{
subjectBuffer.Properties.AddProperty(_uniqueKey, tagSource);
}
}
/// <summary>
/// Called by the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> infrastructure to
/// determine the caret position. This value will be passed in as the value to
/// <see cref="TaggerContext{TTag}.CaretPosition"/> in the call to
/// <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>.
/// </summary>
protected virtual SnapshotPoint? GetCaretPoint(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
return textViewOpt?.GetCaretPoint(subjectBuffer);
}
/// <summary>
/// Called by the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> infrastructure to determine
/// the set of spans that it should asynchronously tag. This will be called in response to
/// notifications from the <see cref="ITaggerEventSource"/> that something has changed, and
/// will only be called from the UI thread. The tagger infrastructure will then determine
/// the <see cref="DocumentSnapshotSpan"/>s associated with these <see cref="SnapshotSpan"/>s
/// and will asynchronously call into <see cref="ProduceTagsAsync(TaggerContext{TTag})"/> at some point in
/// the future to produce tags for these spans.
/// </summary>
protected virtual IEnumerable<SnapshotSpan> GetSpansToTag(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
// For a standard tagger, the spans to tag is the span of the entire snapshot.
return new[] { subjectBuffer.CurrentSnapshot.GetFullSpan() };
}
/// <summary>
/// Creates the <see cref="ITaggerEventSource"/> that notifies the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/>
/// that it should recompute tags for the text buffer after an appropriate <see cref="TaggerDelay"/>.
/// </summary>
protected abstract ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer);
internal Task ProduceTagsAsync_ForTestingPurposesOnly(TaggerContext<TTag> context)
{
return ProduceTagsAsync(context);
}
/// <summary>
/// Produce tags for the given context.
/// Keep in sync with <see cref="ProduceTagsSynchronously(TaggerContext{TTag})"/>
/// </summary>
protected virtual async Task ProduceTagsAsync(TaggerContext<TTag> context)
{
foreach (var spanToTag in context.SpansToTag)
{
context.CancellationToken.ThrowIfCancellationRequested();
await ProduceTagsAsync(
context, spanToTag,
GetCaretPosition(context.CaretPosition, spanToTag.SnapshotSpan)).ConfigureAwait(false);
}
}
/// <summary>
/// Produce tags for the given context.
/// Keep in sync with <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>
/// </summary>
protected void ProduceTagsSynchronously(TaggerContext<TTag> context)
{
foreach (var spanToTag in context.SpansToTag)
{
context.CancellationToken.ThrowIfCancellationRequested();
ProduceTagsSynchronously(
context, spanToTag,
GetCaretPosition(context.CaretPosition, spanToTag.SnapshotSpan));
}
}
private static int? GetCaretPosition(SnapshotPoint? caretPosition, SnapshotSpan snapshotSpan)
{
return caretPosition.HasValue && caretPosition.Value.Snapshot == snapshotSpan.Snapshot
? caretPosition.Value.Position : (int?)null;
}
protected virtual Task ProduceTagsAsync(TaggerContext<TTag> context, DocumentSnapshotSpan spanToTag, int? caretPosition)
{
return SpecializedTasks.EmptyTask;
}
protected virtual void ProduceTagsSynchronously(TaggerContext<TTag> context, DocumentSnapshotSpan spanToTag, int? caretPosition)
{
// By default we implement the sync version of this by blocking on the async version.
//
// The benefit of this is that all taggers can implicitly be used as IAccurateTaggers
// without any code changes.
//
// However, the drawback is that it means the UI thread might be blocked waiting for
// tasks to be scheduled and run on the threadpool.
//
// Taggers that need to be called accurately should override this method to produce
// results quickly if possible.
ProduceTagsAsync(context, spanToTag, caretPosition).Wait(context.CancellationToken);
}
private struct DiffResult
{
public NormalizedSnapshotSpanCollection Added { get; }
public NormalizedSnapshotSpanCollection Removed { get; }
public DiffResult(List<SnapshotSpan> added, List<SnapshotSpan> removed) :
this(added?.Count == 0 ? null : (IEnumerable<SnapshotSpan>)added, removed?.Count == 0 ? null : (IEnumerable<SnapshotSpan>)removed)
{
}
public DiffResult(IEnumerable<SnapshotSpan> added, IEnumerable<SnapshotSpan> removed)
{
Added = added != null ? new NormalizedSnapshotSpanCollection(added) : NormalizedSnapshotSpanCollection.Empty;
Removed = removed != null ? new NormalizedSnapshotSpanCollection(removed) : NormalizedSnapshotSpanCollection.Empty;
}
public int Count => Added.Count + Removed.Count;
}
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using System.Text;
namespace dnlib.DotNet {
/// <summary>
/// Compares byte arrays
/// </summary>
sealed class ByteArrayEqualityComparer : IEqualityComparer<byte[]> {
/// <summary>
/// Default instance
/// </summary>
public static readonly ByteArrayEqualityComparer Instance = new ByteArrayEqualityComparer();
/// <inheritdoc/>
public bool Equals(byte[] x, byte[] y) => Utils.Equals(x, y);
/// <inheritdoc/>
public int GetHashCode(byte[] obj) => Utils.GetHashCode(obj);
}
static class Utils {
/// <summary>
/// Returns an assembly name string
/// </summary>
/// <param name="name">Simple assembly name</param>
/// <param name="version">Version or <c>null</c></param>
/// <param name="culture">Culture or <c>null</c></param>
/// <param name="publicKey">Public key / public key token or <c>null</c></param>
/// <param name="attributes">Assembly attributes</param>
/// <returns>An assembly name string</returns>
internal static string GetAssemblyNameString(UTF8String name, Version version, UTF8String culture, PublicKeyBase publicKey, AssemblyAttributes attributes) {
var sb = new StringBuilder();
foreach (var c in UTF8String.ToSystemStringOrEmpty(name)) {
if (c == ',' || c == '=')
sb.Append('\\');
sb.Append(c);
}
if (version is not null) {
sb.Append(", Version=");
sb.Append(CreateVersionWithNoUndefinedValues(version).ToString());
}
if (culture is not null) {
sb.Append(", Culture=");
sb.Append(UTF8String.IsNullOrEmpty(culture) ? "neutral" : culture.String);
}
sb.Append(", ");
sb.Append(publicKey is null || publicKey is PublicKeyToken ? "PublicKeyToken=" : "PublicKey=");
sb.Append(publicKey is null ? "null" : publicKey.ToString());
if ((attributes & AssemblyAttributes.Retargetable) != 0)
sb.Append(", Retargetable=Yes");
if ((attributes & AssemblyAttributes.ContentType_Mask) == AssemblyAttributes.ContentType_WindowsRuntime)
sb.Append(", ContentType=WindowsRuntime");
return sb.ToString();
}
/// <summary>
/// Convert a byte[] to a <see cref="string"/>
/// </summary>
/// <param name="bytes">All bytes</param>
/// <param name="upper"><c>true</c> if output should be in upper case hex</param>
/// <returns><paramref name="bytes"/> as a hex string</returns>
internal static string ToHex(byte[] bytes, bool upper) {
if (bytes is null)
return "";
var chars = new char[bytes.Length * 2];
for (int i = 0, j = 0; i < bytes.Length; i++) {
byte b = bytes[i];
chars[j++] = ToHexChar(b >> 4, upper);
chars[j++] = ToHexChar(b & 0x0F, upper);
}
return new string(chars);
}
static char ToHexChar(int val, bool upper) {
if (0 <= val && val <= 9)
return (char)(val + (int)'0');
return (char)(val - 10 + (upper ? (int)'A' : (int)'a'));
}
/// <summary>
/// Converts a hex string to a byte[]
/// </summary>
/// <param name="hexString">A string with an even number of hex characters</param>
/// <returns><paramref name="hexString"/> converted to a byte[] or <c>null</c>
/// if <paramref name="hexString"/> is invalid</returns>
internal static byte[] ParseBytes(string hexString) {
try {
if (hexString.Length % 2 != 0)
return null;
var bytes = new byte[hexString.Length / 2];
for (int i = 0; i < hexString.Length; i += 2) {
int upper = TryParseHexChar(hexString[i]);
int lower = TryParseHexChar(hexString[i + 1]);
if (upper < 0 || lower < 0)
return null;
bytes[i / 2] = (byte)((upper << 4) | lower);
}
return bytes;
}
catch {
return null;
}
}
/// <summary>
/// Converts a character to a hex digit
/// </summary>
/// <param name="c">Hex character</param>
/// <returns><c>0x00</c>-<c>0x0F</c> if successful, <c>-1</c> if <paramref name="c"/> is not
/// a valid hex digit</returns>
static int TryParseHexChar(char c) {
if ('0' <= c && c <= '9')
return (ushort)c - (ushort)'0';
if ('a' <= c && c <= 'f')
return 10 + (ushort)c - (ushort)'a';
if ('A' <= c && c <= 'F')
return 10 + (ushort)c - (ushort)'A';
return -1;
}
/// <summary>
/// Compares two byte arrays
/// </summary>
/// <param name="a">Byte array #1</param>
/// <param name="b">Byte array #2</param>
/// <returns>< 0 if a < b, 0 if a == b, > 0 if a > b</returns>
internal static int CompareTo(byte[] a, byte[] b) {
if (a == b)
return 0;
if (a is null)
return -1;
if (b is null)
return 1;
int count = Math.Min(a.Length, b.Length);
for (int i = 0; i < count; i++) {
var ai = a[i];
var bi = b[i];
if (ai < bi)
return -1;
if (ai > bi)
return 1;
}
return a.Length.CompareTo(b.Length);
}
/// <summary>
/// Checks whether two byte arrays are equal
/// </summary>
/// <param name="a">First</param>
/// <param name="b">Second</param>
/// <returns><c>true</c> if same, <c>false</c> otherwise</returns>
internal static bool Equals(byte[] a, byte[] b) {
if (a == b)
return true;
if (a is null || b is null)
return false;
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++) {
if (a[i] != b[i])
return false;
}
return true;
}
/// <summary>
/// Gets the hash code of a byte array
/// </summary>
/// <param name="a">Byte array</param>
/// <returns>The hash code</returns>
internal static int GetHashCode(byte[] a) {
if (a is null || a.Length == 0)
return 0;
int count = Math.Min(a.Length / 2, 20);
if (count == 0)
count = 1;
uint hash = 0;
for (int i = 0, j = a.Length - 1; i < count; i++, j--) {
hash ^= a[i] | ((uint)a[j] << 8);
hash = (hash << 13) | (hash >> 19);
}
return (int)hash;
}
/// <summary>
/// Compares two versions
/// </summary>
/// <remarks>This differs from <see cref="System.Version.CompareTo(Version)"/> if the build
/// and/or revision numbers haven't been initialized or if one of the args is <c>null</c>.
/// </remarks>
/// <param name="a">Version #1 or <c>null</c> to be treated as v0.0.0.0</param>
/// <param name="b">Version #2 or <c>null</c> to be treated as v0.0.0.0</param>
/// <returns>< 0 if a < b, 0 if a == b, > 0 if a > b</returns>
internal static int CompareTo(Version a, Version b) {
if (a is null)
a = new Version();
if (b is null)
b = new Version();
if (a.Major != b.Major)
return a.Major.CompareTo(b.Major);
if (a.Minor != b.Minor)
return a.Minor.CompareTo(b.Minor);
if (GetDefaultVersionValue(a.Build) != GetDefaultVersionValue(b.Build))
return GetDefaultVersionValue(a.Build).CompareTo(GetDefaultVersionValue(b.Build));
return GetDefaultVersionValue(a.Revision).CompareTo(GetDefaultVersionValue(b.Revision));
}
/// <summary>
/// Checks whether two versions are the same
/// </summary>
/// <remarks>This differs from <see cref="System.Version.Equals(Version)"/> if the build
/// and/or revision numbers haven't been initialized or if one of the args is <c>null</c>.
/// </remarks>
/// <param name="a">Version #1 or <c>null</c> to be treated as v0.0.0.0</param>
/// <param name="b">Version #2 or <c>null</c> to be treated as v0.0.0.0</param>
/// <returns><c>true</c> if same, <c>false</c> otherwise</returns>
internal static bool Equals(Version a, Version b) => CompareTo(a, b) == 0;
/// <summary>
/// Creates a new <see cref="Version"/> instance with no undefined version values (eg.
/// the build and revision values won't be -1).
/// </summary>
/// <param name="a">A <see cref="Version"/> instance</param>
/// <returns>A new <see cref="Version"/> instance</returns>
internal static Version CreateVersionWithNoUndefinedValues(Version a) {
if (a is null)
return new Version(0, 0, 0, 0);
return new Version(a.Major, a.Minor, GetDefaultVersionValue(a.Build), GetDefaultVersionValue(a.Revision));
}
static int GetDefaultVersionValue(int val) => val == -1 ? 0 : val;
/// <summary>
/// Parses a version string
/// </summary>
/// <param name="versionString">Version string</param>
/// <returns>A new <see cref="Version"/> or <c>null</c> if <paramref name="versionString"/>
/// is an invalid version</returns>
internal static Version ParseVersion(string versionString) {
try {
return Utils.CreateVersionWithNoUndefinedValues(new Version(versionString));
}
catch {
return null;
}
}
/// <summary>
/// Compares two locales (cultures)
/// </summary>
/// <param name="a">First</param>
/// <param name="b">Second</param>
/// <returns>< 0 if a < b, 0 if a == b, > 0 if a > b</returns>
internal static int LocaleCompareTo(UTF8String a, UTF8String b) => GetCanonicalLocale(a).CompareTo(GetCanonicalLocale(b));
/// <summary>
/// Compares two locales (cultures)
/// </summary>
/// <param name="a">First</param>
/// <param name="b">Second</param>
/// <returns><c>true</c> if same, <c>false</c> otherwise</returns>
internal static bool LocaleEquals(UTF8String a, UTF8String b) => LocaleCompareTo(a, b) == 0;
/// <summary>
/// Compares two locales (cultures)
/// </summary>
/// <param name="a">First</param>
/// <param name="b">Second</param>
/// <returns>< 0 if a < b, 0 if a == b, > 0 if a > b</returns>
internal static int LocaleCompareTo(UTF8String a, string b) => GetCanonicalLocale(a).CompareTo(GetCanonicalLocale(b));
/// <summary>
/// Compares two locales (cultures)
/// </summary>
/// <param name="a">First</param>
/// <param name="b">Second</param>
/// <returns><c>true</c> if same, <c>false</c> otherwise</returns>
internal static bool LocaleEquals(UTF8String a, string b) => LocaleCompareTo(a, b) == 0;
/// <summary>
/// Gets the hash code of a locale
/// </summary>
/// <param name="a">Value</param>
/// <returns>The hash code</returns>
internal static int GetHashCodeLocale(UTF8String a) => GetCanonicalLocale(a).GetHashCode();
static string GetCanonicalLocale(UTF8String locale) => GetCanonicalLocale(UTF8String.ToSystemStringOrEmpty(locale));
static string GetCanonicalLocale(string locale) {
var s = locale.ToUpperInvariant();
if (s == "NEUTRAL")
s = string.Empty;
return s;
}
/// <summary>
/// Align up
/// </summary>
/// <param name="v">Value</param>
/// <param name="alignment">Alignment</param>
public static uint AlignUp(uint v, uint alignment) => (v + alignment - 1) & ~(alignment - 1);
/// <summary>
/// Align up
/// </summary>
/// <param name="v">Value</param>
/// <param name="alignment">Alignment</param>
public static int AlignUp(int v, uint alignment) => (int)AlignUp((uint)v, alignment);
}
}
| |
namespace Palmmedia.ReportGenerator.Parser
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using log4net;
using Palmmedia.ReportGenerator.Common;
using Palmmedia.ReportGenerator.Parser.Analysis;
using Palmmedia.ReportGenerator.Properties;
using System.Diagnostics.Contracts;
/// <summary>
/// Parser for XML reports generated by OpenCover.
/// </summary>
public class OpenCoverParser : ParserBase
{
private static readonly ILog logger = LogManager.GetLogger(typeof(OpenCoverParser));
private readonly XElement[] modules;
private readonly XElement[] files;
private readonly IDictionary<string, string> trackedMethods;
/// <summary>
/// Initializes a new instance of the <see cref="OpenCoverParser"/> class.
/// </summary>
/// <param name="report">The report file as XContainer.</param>
public OpenCoverParser(XContainer report)
{
Contract.Requires<ArgumentNullException>(report != null);
this.modules = report.Descendants("Module")
.Where(m => m.Attribute("skippedDueTo") == null)
.ToArray();
this.files = report.Descendants("File").ToArray();
this.trackedMethods = report.Descendants("TrackedMethod")
.ToDictionary(t => t.Attribute("uid").Value, t => t.Attribute("name").Value);
var assemblyNames = this.modules
.Select(m => m.Element("ModuleName").Value)
.Distinct()
.OrderBy(a => a)
.ToArray();
// Parallel.ForEach(assemblyNames, assemblyName => this.AddAssembly(this.ProcessAssembly(assemblyName)));
foreach (var assemblyName in assemblyNames)
{
var processedAssembly = this.ProcessAssembly(assemblyName);
this.AddAssembly(processedAssembly);
}
this.modules = null;
this.files = null;
this.trackedMethods = null;
}
/// <summary>
/// Extracts the metrics from the given <see cref="XElement">XElements</see>.
/// </summary>
/// <param name="methods">The methods.</param>
/// <param name="class">The class.</param>
private static void SetMethodMetrics(IEnumerable<XElement> methods, Class @class)
{
foreach (var methodGroup in methods.GroupBy(m => m.Element("Name").Value))
{
var method = methodGroup.First();
// Exclude properties and lambda expressions
if (method.Attribute("skippedDueTo") != null
|| method.HasAttributeWithValue("isGetter", "true")
|| method.HasAttributeWithValue("isSetter", "true")
|| Regex.IsMatch(methodGroup.Key, "::<.+>.+__"))
{
continue;
}
var metrics = new[]
{
new Metric(
"Cyclomatic Complexity",
methodGroup.Max(m => int.Parse(m.Attribute("cyclomaticComplexity").Value, CultureInfo.InvariantCulture))),
new Metric(
"Sequence Coverage",
methodGroup.Max(m => decimal.Parse(m.Attribute("sequenceCoverage").Value, CultureInfo.InvariantCulture))),
new Metric(
"Branch Coverage",
methodGroup.Max(m => decimal.Parse(m.Attribute("branchCoverage").Value, CultureInfo.InvariantCulture)))
};
@class.AddMethodMetric(new MethodMetric(methodGroup.Key, metrics));
}
}
/// <summary>
/// Gets the branches by line number.
/// </summary>
/// <param name="methods">The methods.</param>
/// <param name="fileIds">The file ids of the class.</param>
/// <returns>The branches by line number.</returns>
private static Dictionary<int, List<Branch>> GetBranches(XElement[] methods, HashSet<string> fileIds)
{
var result = new Dictionary<int, List<Branch>>();
var branchPoints = methods
.Elements("BranchPoints")
.Elements("BranchPoint")
.ToArray();
// OpenCover supports this since version 4.5.3207
if (branchPoints.Length == 0 || branchPoints[0].Attribute("sl") == null)
{
return result;
}
foreach (var branchPoint in branchPoints)
{
if (branchPoint.Attribute("fileid") != null
&& !fileIds.Contains(branchPoint.Attribute("fileid").Value))
{
// If fileid is available, verify that branch belongs to same file (available since version OpenCover.4.5.3418)
continue;
}
int lineNumber = int.Parse(branchPoint.Attribute("sl").Value, CultureInfo.InvariantCulture);
string identifier = string.Format(
CultureInfo.InvariantCulture,
"{0}_{1}_{2}_{3}",
lineNumber,
branchPoint.Attribute("path").Value,
branchPoint.Attribute("offset").Value,
branchPoint.Attribute("offsetend").Value);
var branch = new Branch(
int.Parse(branchPoint.Attribute("vc").Value, CultureInfo.InvariantCulture),
identifier);
List<Branch> branches = null;
if (result.TryGetValue(lineNumber, out branches))
{
branches.Add(branch);
}
else
{
branches = new List<Branch>();
branches.Add(branch);
result.Add(lineNumber, branches);
}
}
return result;
}
/// <summary>
/// Processes the given assembly.
/// </summary>
/// <param name="assemblyName">Name of the assembly.</param>
/// <returns>The <see cref="Assembly"/>.</returns>
private Assembly ProcessAssembly(string assemblyName)
{
logger.DebugFormat(" " + Resources.CurrentAssembly, assemblyName);
var fileIdsByFilename = this.modules
.Where(m => m.Element("ModuleName").Value.Equals(assemblyName))
.Elements("Files")
.Elements("File")
.GroupBy(f => f.Attribute("fullPath").Value, f => f.Attribute("uid").Value)
.ToDictionary(g => g.Key, g => g.ToHashSet());
var classNames = this.modules
.Where(m => m.Element("ModuleName").Value.Equals(assemblyName))
.Elements("Classes")
.Elements("Class")
.Where(c => !c.Element("FullName").Value.Contains("__")
&& !c.Element("FullName").Value.Contains("<")
&& c.Attribute("skippedDueTo") == null)
.Select(c =>
{
string fullname = c.Element("FullName").Value;
int nestedClassSeparatorIndex = fullname.IndexOf('/');
return nestedClassSeparatorIndex > -1 ? fullname.Substring(0, nestedClassSeparatorIndex) : fullname;
})
.Distinct()
.OrderBy(name => name)
.ToArray();
var assembly = new Assembly(assemblyName);
// Parallel.ForEach(classNames, className => assembly.AddClass(this.ProcessClass(fileIdsByFilename, assembly, className)));
foreach (var className in classNames)
{
var processedClass = this.ProcessClass(fileIdsByFilename, assembly, className);
assembly.AddClass(processedClass);
}
return assembly;
}
/// <summary>
/// Processes the given class.
/// </summary>
/// <param name="fileIdsByFilename">Dictionary containing the file ids by filename.</param>
/// <param name="assembly">The assembly.</param>
/// <param name="className">Name of the class.</param>
/// <returns>The <see cref="Class"/>.</returns>
private Class ProcessClass(Dictionary<string, HashSet<string>> fileIdsByFilename, Assembly assembly, string className)
{
var methods = this.modules
.Where(m => m.Element("ModuleName").Value.Equals(assembly.Name))
.Elements("Classes")
.Elements("Class")
.Where(c => c.Element("FullName").Value.Equals(className)
|| c.Element("FullName").Value.StartsWith(className + "/", StringComparison.Ordinal))
.Elements("Methods")
.Elements("Method");
var fileIdsOfClassInSequencePoints = methods
.Elements("SequencePoints")
.Elements("SequencePoint")
.Where(seqpnt => seqpnt.Attribute("fileid") != null
&& seqpnt.Attribute("fileid").Value != "0")
.Select(seqpnt => seqpnt.Attribute("fileid").Value)
.ToArray();
// Only required for backwards compatibility, older versions of OpenCover did not apply fileid for partial classes
var fileIdsOfClassInFileRef = methods
.Where(m => m.Element("FileRef") != null)
.Select(m => m.Element("FileRef").Attribute("uid").Value)
.ToArray();
var fileIdsOfClass = fileIdsOfClassInSequencePoints
.Concat(fileIdsOfClassInFileRef)
.Distinct()
.ToHashSet();
var filesOfClass = this.files
.Where(file => fileIdsOfClass.Contains(file.Attribute("uid").Value))
.Select(file => file.Attribute("fullPath").Value)
.Distinct()
.ToArray();
var @class = new Class(className, assembly);
foreach (var file in filesOfClass)
{
@class.AddFile(this.ProcessFile(fileIdsByFilename[file], @class, file));
}
@class.CoverageQuota = this.GetCoverageQuotaOfClass(assembly, className);
return @class;
}
/// <summary>
/// Processes the file.
/// </summary>
/// <param name="fileIds">The file ids of the class.</param>
/// <param name="class">The class.</param>
/// <param name="filePath">The file path.</param>
/// <returns>The <see cref="CodeFile"/>.</returns>
private CodeFile ProcessFile(HashSet<string> fileIds, Class @class, string filePath)
{
var methods = this.modules
.Where(m => m.Element("ModuleName").Value.Equals(@class.Assembly.Name))
.Elements("Classes")
.Elements("Class")
.Where(c => c.Element("FullName").Value.Equals(@class.Name)
|| c.Element("FullName").Value.StartsWith(@class.Name + "/", StringComparison.Ordinal))
.Elements("Methods")
.Elements("Method")
.ToArray();
var methodsOfFile = methods
.Where(m => m.Element("FileRef") != null && fileIds.Contains(m.Element("FileRef").Attribute("uid").Value))
.ToArray();
SetMethodMetrics(methodsOfFile, @class);
var seqpntsOfFile = methods
.Elements("SequencePoints")
.Elements("SequencePoint")
.Where(seqpnt => (seqpnt.Attribute("fileid") != null
&& fileIds.Contains(seqpnt.Attribute("fileid").Value))
|| (seqpnt.Attribute("fileid") == null && seqpnt.Parent.Parent.Element("FileRef") != null
&& fileIds.Contains(seqpnt.Parent.Parent.Element("FileRef").Attribute("uid").Value)))
.Select(seqpnt => new
{
LineNumberStart = int.Parse(seqpnt.Attribute("sl").Value, CultureInfo.InvariantCulture),
LineNumberEnd = seqpnt.Attribute("el") != null ? int.Parse(seqpnt.Attribute("el").Value, CultureInfo.InvariantCulture) : int.Parse(seqpnt.Attribute("sl").Value, CultureInfo.InvariantCulture),
Visits = int.Parse(seqpnt.Attribute("vc").Value, CultureInfo.InvariantCulture),
TrackedMethodRefs = seqpnt.Elements("TrackedMethodRefs")
.Elements("TrackedMethodRef")
.Select(t => new
{
Visits = int.Parse(t.Attribute("vc").Value, CultureInfo.InvariantCulture),
TrackedMethodId = t.Attribute("uid").Value
})
})
.OrderBy(seqpnt => seqpnt.LineNumberEnd)
.ToArray();
int[] coverage = new int[] { };
var branches = GetBranches(methods, fileIds);
var trackedMethodsCoverage = seqpntsOfFile
.SelectMany(s => s.TrackedMethodRefs)
.Select(t => t.TrackedMethodId)
.Distinct()
.ToDictionary(id => id, id => new int[] { });
if (seqpntsOfFile.Length > 0)
{
coverage = new int[seqpntsOfFile[seqpntsOfFile.LongLength - 1].LineNumberEnd + 1];
for (int i = 0; i < coverage.Length; i++)
{
coverage[i] = -1;
}
foreach (var name in trackedMethodsCoverage.Keys.ToArray())
{
trackedMethodsCoverage[name] = (int[])coverage.Clone();
}
foreach (var seqpnt in seqpntsOfFile)
{
for (int lineNumber = seqpnt.LineNumberStart; lineNumber <= seqpnt.LineNumberEnd; lineNumber++)
{
int visits = coverage[lineNumber] == -1 ? seqpnt.Visits : coverage[lineNumber] + seqpnt.Visits;
coverage[lineNumber] = visits;
if (visits > -1)
{
foreach (var trackedMethodCoverage in trackedMethodsCoverage)
{
if (trackedMethodCoverage.Value[lineNumber] == -1)
{
trackedMethodCoverage.Value[lineNumber] = 0;
}
}
}
foreach (var trackedMethod in seqpnt.TrackedMethodRefs)
{
var trackedMethodCoverage = trackedMethodsCoverage[trackedMethod.TrackedMethodId];
trackedMethodCoverage[lineNumber] = trackedMethodCoverage[lineNumber] == -1 ? trackedMethod.Visits : trackedMethodCoverage[lineNumber] + trackedMethod.Visits;
}
}
}
}
var codeFile = new CodeFile(filePath, coverage, branches);
foreach (var trackedMethodCoverage in trackedMethodsCoverage)
{
string name = null;
// Sometimes no corresponding MethodRef element exists
if (this.trackedMethods.TryGetValue(trackedMethodCoverage.Key, out name))
{
string shortName = name.Substring(name.Substring(0, name.IndexOf(':') + 1).LastIndexOf('.') + 1);
TestMethod testMethod = new TestMethod(name, shortName);
codeFile.AddCoverageByTestMethod(testMethod, trackedMethodCoverage.Value);
}
}
return codeFile;
}
/// <summary>
/// Gets the coverage quota of a class.
/// This method is used to get coverage quota if line coverage is not available.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <param name="className">Name of the class.</param>
/// <returns>The coverage quota.</returns>
private decimal? GetCoverageQuotaOfClass(Assembly assembly, string className)
{
var methodGroups = this.modules
.Where(m => m.Element("ModuleName").Value.Equals(assembly.Name))
.Elements("Classes")
.Elements("Class")
.Where(c => c.Element("FullName").Value.Equals(className)
|| c.Element("FullName").Value.StartsWith(className + "/", StringComparison.Ordinal))
.Elements("Methods")
.Elements("Method")
.Where(m => m.Attribute("skippedDueTo") == null && m.Element("FileRef") == null && !m.Element("Name").Value.EndsWith(".ctor()", StringComparison.OrdinalIgnoreCase))
.GroupBy(m => m.Element("Name").Value)
.ToArray();
int visitedMethods = methodGroups.Count(g => g.Any(m => m.Attribute("visited").Value == "true"));
return (methodGroups.Length == 0) ? (decimal?)null : (decimal)Math.Truncate(1000 * (double)visitedMethods / (double)methodGroups.Length) / 10;
}
}
}
| |
/* ====================================================================
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.
==================================================================== */
namespace NPOI.HSSF.UserModel
{
using System;
using NPOI.DDF;
using NPOI.HSSF.Record;
using NPOI.SS.UserModel;
/// <summary>
/// A textbox Is a shape that may hold a rich text string.
/// @author Glen Stampoultzis (glens at apache.org)
/// </summary>
[Serializable]
public class HSSFTextbox : HSSFSimpleShape
{
public const short OBJECT_TYPE_TEXT = 6;
public HSSFTextbox(EscherContainerRecord spContainer, ObjRecord objRecord, TextObjectRecord textObjectRecord)
: base(spContainer, objRecord, textObjectRecord)
{
}
HSSFRichTextString str = new HSSFRichTextString("");
/// <summary>
/// Construct a new textbox with the given parent and anchor.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="anchor">One of HSSFClientAnchor or HSSFChildAnchor</param>
public HSSFTextbox(HSSFShape parent, HSSFAnchor anchor)
: base(parent, anchor)
{
HorizontalAlignment = HorizontalTextAlignment.Left;
VerticalAlignment = VerticalTextAlignment.Top;
this.String = (new HSSFRichTextString(""));
}
protected override ObjRecord CreateObjRecord()
{
ObjRecord obj = new ObjRecord();
CommonObjectDataSubRecord c = new CommonObjectDataSubRecord();
c.ObjectType = CommonObjectType.Text;
c.IsLocked = (true);
c.IsPrintable = (true);
c.IsAutoFill = (true);
c.IsAutoline = (true);
EndSubRecord e = new EndSubRecord();
obj.AddSubRecord(c);
obj.AddSubRecord(e);
return obj;
}
protected override EscherContainerRecord CreateSpContainer()
{
EscherContainerRecord spContainer = new EscherContainerRecord();
EscherSpRecord sp = new EscherSpRecord();
EscherOptRecord opt = new EscherOptRecord();
EscherClientDataRecord clientData = new EscherClientDataRecord();
EscherTextboxRecord escherTextbox = new EscherTextboxRecord();
spContainer.RecordId = (EscherContainerRecord.SP_CONTAINER);
spContainer.Options = ((short)0x000F);
sp.RecordId = (EscherSpRecord.RECORD_ID);
sp.Options = ((short)((EscherAggregate.ST_TEXTBOX << 4) | 0x2));
sp.Flags = (EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE);
opt.RecordId = (EscherOptRecord.RECORD_ID);
opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.TEXT__TEXTID, 0));
opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.TEXT__WRAPTEXT, 0));
opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.TEXT__ANCHORTEXT, 0));
opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.GROUPSHAPE__PRINT, 0x00080000));
opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.TEXT__TEXTLEFT, 0));
opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.TEXT__TEXTRIGHT, 0));
opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.TEXT__TEXTTOP, 0));
opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.TEXT__TEXTBOTTOM, 0));
opt.SetEscherProperty(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINEDASHING, LINESTYLE_SOLID));
opt.SetEscherProperty(new EscherBoolProperty(EscherProperties.LINESTYLE__NOLINEDRAWDASH, 0x00080008));
opt.SetEscherProperty(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINEWIDTH, LINEWIDTH_DEFAULT));
opt.SetEscherProperty(new EscherRGBProperty(EscherProperties.FILL__FILLCOLOR, FILL__FILLCOLOR_DEFAULT));
opt.SetEscherProperty(new EscherRGBProperty(EscherProperties.LINESTYLE__COLOR, LINESTYLE__COLOR_DEFAULT));
opt.SetEscherProperty(new EscherBoolProperty(EscherProperties.FILL__NOFILLHITTEST, NO_FILLHITTEST_FALSE));
opt.SetEscherProperty(new EscherBoolProperty(EscherProperties.GROUPSHAPE__PRINT, 0x080000));
EscherRecord anchor = Anchor.GetEscherAnchor();
clientData.RecordId = (EscherClientDataRecord.RECORD_ID);
clientData.Options = ((short)0x0000);
escherTextbox.RecordId = (EscherTextboxRecord.RECORD_ID);
escherTextbox.Options = ((short)0x0000);
spContainer.AddChildRecord(sp);
spContainer.AddChildRecord(opt);
spContainer.AddChildRecord(anchor);
spContainer.AddChildRecord(clientData);
spContainer.AddChildRecord(escherTextbox);
return spContainer;
}
internal override void AfterInsert(HSSFPatriarch patriarch)
{
EscherAggregate agg = patriarch.getBoundAggregate();
agg.AssociateShapeToObjRecord(GetEscherContainer().GetChildById(EscherClientDataRecord.RECORD_ID), GetObjRecord());
if (GetTextObjectRecord() != null)
{
agg.AssociateShapeToObjRecord(GetEscherContainer().GetChildById(EscherTextboxRecord.RECORD_ID), GetTextObjectRecord());
}
}
internal override HSSFShape CloneShape()
{
TextObjectRecord txo = GetTextObjectRecord() == null ? null : (TextObjectRecord)GetTextObjectRecord().CloneViaReserialise();
EscherContainerRecord spContainer = new EscherContainerRecord();
byte[] inSp = GetEscherContainer().Serialize();
spContainer.FillFields(inSp, 0, new DefaultEscherRecordFactory());
ObjRecord obj = (ObjRecord)GetObjRecord().CloneViaReserialise();
return new HSSFTextbox(spContainer, obj, txo);
}
internal override void AfterRemove(HSSFPatriarch patriarch)
{
patriarch.getBoundAggregate().RemoveShapeToObjRecord(GetEscherContainer().GetChildById(EscherClientDataRecord.RECORD_ID));
patriarch.getBoundAggregate().RemoveShapeToObjRecord(GetEscherContainer().GetChildById(EscherTextboxRecord.RECORD_ID));
}
/// <summary>
/// Gets or sets the left margin within the textbox.
/// </summary>
/// <value>The margin left.</value>
public int MarginLeft
{
get
{
EscherSimpleProperty property = (EscherSimpleProperty)GetOptRecord().Lookup(EscherProperties.TEXT__TEXTLEFT);
return property == null ? 0 : property.PropertyValue;
}
set { SetPropertyValue(new EscherSimpleProperty(EscherProperties.TEXT__TEXTLEFT, value)); }
}
/// <summary>
/// Gets or sets the right margin within the textbox.
/// </summary>
/// <value>The margin right.</value>
public int MarginRight
{
get
{
EscherSimpleProperty property = (EscherSimpleProperty)GetOptRecord().Lookup(EscherProperties.TEXT__TEXTRIGHT);
return property == null ? 0 : property.PropertyValue;
}
set { SetPropertyValue(new EscherSimpleProperty(EscherProperties.TEXT__TEXTRIGHT, value)); }
}
/// <summary>
/// Gets or sets the top margin within the textbox
/// </summary>
/// <value>The top margin.</value>
public int MarginTop
{
get
{
EscherSimpleProperty property = (EscherSimpleProperty)GetOptRecord().Lookup(EscherProperties.TEXT__TEXTTOP);
return property == null ? 0 : property.PropertyValue;
}
set { SetPropertyValue(new EscherSimpleProperty(EscherProperties.TEXT__TEXTTOP, value)); }
}
/// <summary>
/// Gets or sets the bottom margin within the textbox.
/// </summary>
/// <value>The margin bottom.</value>
public int MarginBottom
{
get
{
EscherSimpleProperty property = (EscherSimpleProperty)GetOptRecord().Lookup(EscherProperties.TEXT__TEXTBOTTOM);
return property == null ? 0 : property.PropertyValue;
}
set { SetPropertyValue(new EscherSimpleProperty(EscherProperties.TEXT__TEXTBOTTOM, value)); }
}
/// <summary>
/// Gets or sets the horizontal alignment.
/// </summary>
/// <value>The horizontal alignment.</value>
public HorizontalTextAlignment HorizontalAlignment
{
get { return GetTextObjectRecord().HorizontalTextAlignment; }
set { GetTextObjectRecord().HorizontalTextAlignment = value; }
}
/// <summary>
/// Gets or sets the vertical alignment.
/// </summary>
/// <value>The vertical alignment.</value>
public VerticalTextAlignment VerticalAlignment
{
get { return GetTextObjectRecord().VerticalTextAlignment; }
set { GetTextObjectRecord().VerticalTextAlignment = value; }
}
public override int ShapeType
{
get { return base.ShapeType; }
set
{
throw new InvalidOperationException("Shape type can not be changed in " + this.GetType().Name);
}
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.LSNPoolBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBLSNPoolLSNPoolStatistics))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBLSNPoolLSNPoolStatistics_v2))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonVLANFilterList))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonPortRange))]
public partial class LocalLBLSNPool : iControlInterface {
public LocalLBLSNPool() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_backup_member
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void add_backup_member(
string [] pools,
string [] [] members
) {
this.Invoke("add_backup_member", new object [] {
pools,
members});
}
public System.IAsyncResult Beginadd_backup_member(string [] pools,string [] [] members, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_backup_member", new object[] {
pools,
members}, callback, asyncState);
}
public void Endadd_backup_member(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_member
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void add_member(
string [] pools,
string [] [] members
) {
this.Invoke("add_member", new object [] {
pools,
members});
}
public System.IAsyncResult Beginadd_member(string [] pools,string [] [] members, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_member", new object[] {
pools,
members}, callback, asyncState);
}
public void Endadd_member(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void create(
string [] pools,
string [] [] members
) {
this.Invoke("create", new object [] {
pools,
members});
}
public System.IAsyncResult Begincreate(string [] pools,string [] [] members, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
pools,
members}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_lsn_pools
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void delete_all_lsn_pools(
) {
this.Invoke("delete_all_lsn_pools", new object [0]);
}
public System.IAsyncResult Begindelete_all_lsn_pools(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_lsn_pools", new object[0], callback, asyncState);
}
public void Enddelete_all_lsn_pools(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_lsn_pool
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void delete_lsn_pool(
string [] pools
) {
this.Invoke("delete_lsn_pool", new object [] {
pools});
}
public System.IAsyncResult Begindelete_lsn_pool(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_lsn_pool", new object[] {
pools}, callback, asyncState);
}
public void Enddelete_lsn_pool(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_all_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBLSNPoolLSNPoolStatistics get_all_statistics(
) {
object [] results = this.Invoke("get_all_statistics", new object [0]);
return ((LocalLBLSNPoolLSNPoolStatistics)(results[0]));
}
public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState);
}
public LocalLBLSNPoolLSNPoolStatistics Endget_all_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBLSNPoolLSNPoolStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_all_statistics_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBLSNPoolLSNPoolStatistics_v2 get_all_statistics_v2(
) {
object [] results = this.Invoke("get_all_statistics_v2", new object [0]);
return ((LocalLBLSNPoolLSNPoolStatistics_v2)(results[0]));
}
public System.IAsyncResult Beginget_all_statistics_v2(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics_v2", new object[0], callback, asyncState);
}
public LocalLBLSNPoolLSNPoolStatistics_v2 Endget_all_statistics_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBLSNPoolLSNPoolStatistics_v2)(results[0]));
}
//-----------------------------------------------------------------------
// get_backup_member
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_backup_member(
string [] pools
) {
object [] results = this.Invoke("get_backup_member", new object [] {
pools});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_backup_member(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_backup_member", new object[] {
pools}, callback, asyncState);
}
public string [] [] Endget_backup_member(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_block_idle_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_block_idle_timeout(
string [] pools
) {
object [] results = this.Invoke("get_block_idle_timeout", new object [] {
pools});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_block_idle_timeout(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_block_idle_timeout", new object[] {
pools}, callback, asyncState);
}
public long [] Endget_block_idle_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_block_lifetime
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_block_lifetime(
string [] pools
) {
object [] results = this.Invoke("get_block_lifetime", new object [] {
pools});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_block_lifetime(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_block_lifetime", new object[] {
pools}, callback, asyncState);
}
public long [] Endget_block_lifetime(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_block_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_block_size(
string [] pools
) {
object [] results = this.Invoke("get_block_size", new object [] {
pools});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_block_size(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_block_size", new object[] {
pools}, callback, asyncState);
}
public long [] Endget_block_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_client_block_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_client_block_limit(
string [] pools
) {
object [] results = this.Invoke("get_client_block_limit", new object [] {
pools});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_client_block_limit(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_client_block_limit", new object[] {
pools}, callback, asyncState);
}
public long [] Endget_client_block_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_connection_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_connection_limit(
string [] pools
) {
object [] results = this.Invoke("get_connection_limit", new object [] {
pools});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_connection_limit(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_connection_limit", new object[] {
pools}, callback, asyncState);
}
public long [] Endget_connection_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] pools
) {
object [] results = this.Invoke("get_description", new object [] {
pools});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
pools}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_egress_interface
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonVLANFilterList [] get_egress_interface(
string [] pools
) {
object [] results = this.Invoke("get_egress_interface", new object [] {
pools});
return ((CommonVLANFilterList [])(results[0]));
}
public System.IAsyncResult Beginget_egress_interface(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_egress_interface", new object[] {
pools}, callback, asyncState);
}
public CommonVLANFilterList [] Endget_egress_interface(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonVLANFilterList [])(results[0]));
}
//-----------------------------------------------------------------------
// get_egress_interface_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_egress_interface_state(
string [] pools
) {
object [] results = this.Invoke("get_egress_interface_state", new object [] {
pools});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_egress_interface_state(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_egress_interface_state", new object[] {
pools}, callback, asyncState);
}
public CommonEnabledState [] Endget_egress_interface_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_hairpin_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBLSNPoolHairpinMode [] get_hairpin_mode(
string [] pools
) {
object [] results = this.Invoke("get_hairpin_mode", new object [] {
pools});
return ((LocalLBLSNPoolHairpinMode [])(results[0]));
}
public System.IAsyncResult Beginget_hairpin_mode(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_hairpin_mode", new object[] {
pools}, callback, asyncState);
}
public LocalLBLSNPoolHairpinMode [] Endget_hairpin_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBLSNPoolHairpinMode [])(results[0]));
}
//-----------------------------------------------------------------------
// get_icmp_echo_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_icmp_echo_state(
string [] pools
) {
object [] results = this.Invoke("get_icmp_echo_state", new object [] {
pools});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_icmp_echo_state(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_icmp_echo_state", new object[] {
pools}, callback, asyncState);
}
public CommonEnabledState [] Endget_icmp_echo_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_inbound_connection_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_inbound_connection_state(
string [] pools
) {
object [] results = this.Invoke("get_inbound_connection_state", new object [] {
pools});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_inbound_connection_state(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_inbound_connection_state", new object[] {
pools}, callback, asyncState);
}
public CommonEnabledState [] Endget_inbound_connection_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_inbound_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBLSNPoolInboundMode [] get_inbound_mode(
string [] pools
) {
object [] results = this.Invoke("get_inbound_mode", new object [] {
pools});
return ((LocalLBLSNPoolInboundMode [])(results[0]));
}
public System.IAsyncResult Beginget_inbound_mode(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_inbound_mode", new object[] {
pools}, callback, asyncState);
}
public LocalLBLSNPoolInboundMode [] Endget_inbound_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBLSNPoolInboundMode [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_log_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_log_profile(
string [] pools
) {
object [] results = this.Invoke("get_log_profile", new object [] {
pools});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_log_profile(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_log_profile", new object[] {
pools}, callback, asyncState);
}
public string [] Endget_log_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_log_publisher
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_log_publisher(
string [] pools
) {
object [] results = this.Invoke("get_log_publisher", new object [] {
pools});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_log_publisher(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_log_publisher", new object[] {
pools}, callback, asyncState);
}
public string [] Endget_log_publisher(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_member
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_member(
string [] pools
) {
object [] results = this.Invoke("get_member", new object [] {
pools});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_member(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_member", new object[] {
pools}, callback, asyncState);
}
public string [] [] Endget_member(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_nat_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBLSNPoolNATMode [] get_nat_mode(
string [] pools
) {
object [] results = this.Invoke("get_nat_mode", new object [] {
pools});
return ((LocalLBLSNPoolNATMode [])(results[0]));
}
public System.IAsyncResult Beginget_nat_mode(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_nat_mode", new object[] {
pools}, callback, asyncState);
}
public LocalLBLSNPoolNATMode [] Endget_nat_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBLSNPoolNATMode [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pcp_dslite_tunnel
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_pcp_dslite_tunnel(
string [] pools
) {
object [] results = this.Invoke("get_pcp_dslite_tunnel", new object [] {
pools});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_pcp_dslite_tunnel(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pcp_dslite_tunnel", new object[] {
pools}, callback, asyncState);
}
public string [] Endget_pcp_dslite_tunnel(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pcp_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_pcp_profile(
string [] pools
) {
object [] results = this.Invoke("get_pcp_profile", new object [] {
pools});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_pcp_profile(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pcp_profile", new object[] {
pools}, callback, asyncState);
}
public string [] Endget_pcp_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pcp_selfip
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_pcp_selfip(
string [] pools
) {
object [] results = this.Invoke("get_pcp_selfip", new object [] {
pools});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_pcp_selfip(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pcp_selfip", new object[] {
pools}, callback, asyncState);
}
public string [] Endget_pcp_selfip(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_persistence_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBLSNPoolPersistMode [] get_persistence_mode(
string [] pools
) {
object [] results = this.Invoke("get_persistence_mode", new object [] {
pools});
return ((LocalLBLSNPoolPersistMode [])(results[0]));
}
public System.IAsyncResult Beginget_persistence_mode(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_persistence_mode", new object[] {
pools}, callback, asyncState);
}
public LocalLBLSNPoolPersistMode [] Endget_persistence_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBLSNPoolPersistMode [])(results[0]));
}
//-----------------------------------------------------------------------
// get_persistence_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_persistence_timeout(
string [] pools
) {
object [] results = this.Invoke("get_persistence_timeout", new object [] {
pools});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_persistence_timeout(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_persistence_timeout", new object[] {
pools}, callback, asyncState);
}
public long [] Endget_persistence_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_route_advertisement_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_route_advertisement_state(
string [] pools
) {
object [] results = this.Invoke("get_route_advertisement_state", new object [] {
pools});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_route_advertisement_state(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_route_advertisement_state", new object[] {
pools}, callback, asyncState);
}
public CommonEnabledState [] Endget_route_advertisement_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBLSNPoolLSNPoolStatistics get_statistics(
string [] pools
) {
object [] results = this.Invoke("get_statistics", new object [] {
pools});
return ((LocalLBLSNPoolLSNPoolStatistics)(results[0]));
}
public System.IAsyncResult Beginget_statistics(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics", new object[] {
pools}, callback, asyncState);
}
public LocalLBLSNPoolLSNPoolStatistics Endget_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBLSNPoolLSNPoolStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBLSNPoolLSNPoolStatistics_v2 get_statistics_v2(
string [] pools
) {
object [] results = this.Invoke("get_statistics_v2", new object [] {
pools});
return ((LocalLBLSNPoolLSNPoolStatistics_v2)(results[0]));
}
public System.IAsyncResult Beginget_statistics_v2(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics_v2", new object[] {
pools}, callback, asyncState);
}
public LocalLBLSNPoolLSNPoolStatistics_v2 Endget_statistics_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBLSNPoolLSNPoolStatistics_v2)(results[0]));
}
//-----------------------------------------------------------------------
// get_translation_port_range
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonPortRange [] get_translation_port_range(
string [] pools
) {
object [] results = this.Invoke("get_translation_port_range", new object [] {
pools});
return ((CommonPortRange [])(results[0]));
}
public System.IAsyncResult Beginget_translation_port_range(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_translation_port_range", new object[] {
pools}, callback, asyncState);
}
public CommonPortRange [] Endget_translation_port_range(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonPortRange [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// get_zombie_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_zombie_timeout(
string [] pools
) {
object [] results = this.Invoke("get_zombie_timeout", new object [] {
pools});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_zombie_timeout(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_zombie_timeout", new object[] {
pools}, callback, asyncState);
}
public long [] Endget_zombie_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_backup_members
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void remove_all_backup_members(
string [] pools
) {
this.Invoke("remove_all_backup_members", new object [] {
pools});
}
public System.IAsyncResult Beginremove_all_backup_members(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_backup_members", new object[] {
pools}, callback, asyncState);
}
public void Endremove_all_backup_members(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_members
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void remove_all_members(
string [] pools
) {
this.Invoke("remove_all_members", new object [] {
pools});
}
public System.IAsyncResult Beginremove_all_members(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_members", new object[] {
pools}, callback, asyncState);
}
public void Endremove_all_members(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_backup_member
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void remove_backup_member(
string [] pools,
string [] [] members
) {
this.Invoke("remove_backup_member", new object [] {
pools,
members});
}
public System.IAsyncResult Beginremove_backup_member(string [] pools,string [] [] members, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_backup_member", new object[] {
pools,
members}, callback, asyncState);
}
public void Endremove_backup_member(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_member
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void remove_member(
string [] pools,
string [] [] members
) {
this.Invoke("remove_member", new object [] {
pools,
members});
}
public System.IAsyncResult Beginremove_member(string [] pools,string [] [] members, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_member", new object[] {
pools,
members}, callback, asyncState);
}
public void Endremove_member(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// reset_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void reset_statistics(
string [] pools
) {
this.Invoke("reset_statistics", new object [] {
pools});
}
public System.IAsyncResult Beginreset_statistics(string [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics", new object[] {
pools}, callback, asyncState);
}
public void Endreset_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_block_idle_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_block_idle_timeout(
string [] pools,
long [] timeouts
) {
this.Invoke("set_block_idle_timeout", new object [] {
pools,
timeouts});
}
public System.IAsyncResult Beginset_block_idle_timeout(string [] pools,long [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_block_idle_timeout", new object[] {
pools,
timeouts}, callback, asyncState);
}
public void Endset_block_idle_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_block_lifetime
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_block_lifetime(
string [] pools,
long [] values
) {
this.Invoke("set_block_lifetime", new object [] {
pools,
values});
}
public System.IAsyncResult Beginset_block_lifetime(string [] pools,long [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_block_lifetime", new object[] {
pools,
values}, callback, asyncState);
}
public void Endset_block_lifetime(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_block_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_block_size(
string [] pools,
long [] sizes
) {
this.Invoke("set_block_size", new object [] {
pools,
sizes});
}
public System.IAsyncResult Beginset_block_size(string [] pools,long [] sizes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_block_size", new object[] {
pools,
sizes}, callback, asyncState);
}
public void Endset_block_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_client_block_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_client_block_limit(
string [] pools,
long [] limits
) {
this.Invoke("set_client_block_limit", new object [] {
pools,
limits});
}
public System.IAsyncResult Beginset_client_block_limit(string [] pools,long [] limits, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_client_block_limit", new object[] {
pools,
limits}, callback, asyncState);
}
public void Endset_client_block_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_connection_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_connection_limit(
string [] pools,
long [] limits
) {
this.Invoke("set_connection_limit", new object [] {
pools,
limits});
}
public System.IAsyncResult Beginset_connection_limit(string [] pools,long [] limits, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_connection_limit", new object[] {
pools,
limits}, callback, asyncState);
}
public void Endset_connection_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_description(
string [] pools,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
pools,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] pools,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
pools,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_egress_interface
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_egress_interface(
string [] pools,
CommonVLANFilterList [] interfaces
) {
this.Invoke("set_egress_interface", new object [] {
pools,
interfaces});
}
public System.IAsyncResult Beginset_egress_interface(string [] pools,CommonVLANFilterList [] interfaces, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_egress_interface", new object[] {
pools,
interfaces}, callback, asyncState);
}
public void Endset_egress_interface(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_egress_interface_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_egress_interface_state(
string [] pools,
CommonEnabledState [] states
) {
this.Invoke("set_egress_interface_state", new object [] {
pools,
states});
}
public System.IAsyncResult Beginset_egress_interface_state(string [] pools,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_egress_interface_state", new object[] {
pools,
states}, callback, asyncState);
}
public void Endset_egress_interface_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_hairpin_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_hairpin_mode(
string [] pools,
LocalLBLSNPoolHairpinMode [] modes
) {
this.Invoke("set_hairpin_mode", new object [] {
pools,
modes});
}
public System.IAsyncResult Beginset_hairpin_mode(string [] pools,LocalLBLSNPoolHairpinMode [] modes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_hairpin_mode", new object[] {
pools,
modes}, callback, asyncState);
}
public void Endset_hairpin_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_icmp_echo_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_icmp_echo_state(
string [] pools,
CommonEnabledState [] states
) {
this.Invoke("set_icmp_echo_state", new object [] {
pools,
states});
}
public System.IAsyncResult Beginset_icmp_echo_state(string [] pools,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_icmp_echo_state", new object[] {
pools,
states}, callback, asyncState);
}
public void Endset_icmp_echo_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_inbound_connection_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_inbound_connection_state(
string [] pools,
CommonEnabledState [] states
) {
this.Invoke("set_inbound_connection_state", new object [] {
pools,
states});
}
public System.IAsyncResult Beginset_inbound_connection_state(string [] pools,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_inbound_connection_state", new object[] {
pools,
states}, callback, asyncState);
}
public void Endset_inbound_connection_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_inbound_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_inbound_mode(
string [] pools,
LocalLBLSNPoolInboundMode [] modes
) {
this.Invoke("set_inbound_mode", new object [] {
pools,
modes});
}
public System.IAsyncResult Beginset_inbound_mode(string [] pools,LocalLBLSNPoolInboundMode [] modes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_inbound_mode", new object[] {
pools,
modes}, callback, asyncState);
}
public void Endset_inbound_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_log_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_log_profile(
string [] pools,
string [] profiles
) {
this.Invoke("set_log_profile", new object [] {
pools,
profiles});
}
public System.IAsyncResult Beginset_log_profile(string [] pools,string [] profiles, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_log_profile", new object[] {
pools,
profiles}, callback, asyncState);
}
public void Endset_log_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_log_publisher
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_log_publisher(
string [] pools,
string [] publishers
) {
this.Invoke("set_log_publisher", new object [] {
pools,
publishers});
}
public System.IAsyncResult Beginset_log_publisher(string [] pools,string [] publishers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_log_publisher", new object[] {
pools,
publishers}, callback, asyncState);
}
public void Endset_log_publisher(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_nat_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_nat_mode(
string [] pools,
LocalLBLSNPoolNATMode [] modes
) {
this.Invoke("set_nat_mode", new object [] {
pools,
modes});
}
public System.IAsyncResult Beginset_nat_mode(string [] pools,LocalLBLSNPoolNATMode [] modes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_nat_mode", new object[] {
pools,
modes}, callback, asyncState);
}
public void Endset_nat_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_pcp_dslite_tunnel
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_pcp_dslite_tunnel(
string [] pools,
string [] tunnels
) {
this.Invoke("set_pcp_dslite_tunnel", new object [] {
pools,
tunnels});
}
public System.IAsyncResult Beginset_pcp_dslite_tunnel(string [] pools,string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_pcp_dslite_tunnel", new object[] {
pools,
tunnels}, callback, asyncState);
}
public void Endset_pcp_dslite_tunnel(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_pcp_full_config
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_pcp_full_config(
string [] pools,
string [] profiles,
string [] self_ips,
string [] tunnels
) {
this.Invoke("set_pcp_full_config", new object [] {
pools,
profiles,
self_ips,
tunnels});
}
public System.IAsyncResult Beginset_pcp_full_config(string [] pools,string [] profiles,string [] self_ips,string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_pcp_full_config", new object[] {
pools,
profiles,
self_ips,
tunnels}, callback, asyncState);
}
public void Endset_pcp_full_config(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_pcp_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_pcp_profile(
string [] pools,
string [] profiles
) {
this.Invoke("set_pcp_profile", new object [] {
pools,
profiles});
}
public System.IAsyncResult Beginset_pcp_profile(string [] pools,string [] profiles, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_pcp_profile", new object[] {
pools,
profiles}, callback, asyncState);
}
public void Endset_pcp_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_pcp_selfip
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_pcp_selfip(
string [] pools,
string [] self_ips
) {
this.Invoke("set_pcp_selfip", new object [] {
pools,
self_ips});
}
public System.IAsyncResult Beginset_pcp_selfip(string [] pools,string [] self_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_pcp_selfip", new object[] {
pools,
self_ips}, callback, asyncState);
}
public void Endset_pcp_selfip(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_persistence_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_persistence_mode(
string [] pools,
LocalLBLSNPoolPersistMode [] modes
) {
this.Invoke("set_persistence_mode", new object [] {
pools,
modes});
}
public System.IAsyncResult Beginset_persistence_mode(string [] pools,LocalLBLSNPoolPersistMode [] modes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_persistence_mode", new object[] {
pools,
modes}, callback, asyncState);
}
public void Endset_persistence_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_persistence_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_persistence_timeout(
string [] pools,
long [] timeouts
) {
this.Invoke("set_persistence_timeout", new object [] {
pools,
timeouts});
}
public System.IAsyncResult Beginset_persistence_timeout(string [] pools,long [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_persistence_timeout", new object[] {
pools,
timeouts}, callback, asyncState);
}
public void Endset_persistence_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_route_advertisement_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_route_advertisement_state(
string [] pools,
CommonEnabledState [] states
) {
this.Invoke("set_route_advertisement_state", new object [] {
pools,
states});
}
public System.IAsyncResult Beginset_route_advertisement_state(string [] pools,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_route_advertisement_state", new object[] {
pools,
states}, callback, asyncState);
}
public void Endset_route_advertisement_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_translation_port_range
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_translation_port_range(
string [] pools,
CommonPortRange [] ranges
) {
this.Invoke("set_translation_port_range", new object [] {
pools,
ranges});
}
public System.IAsyncResult Beginset_translation_port_range(string [] pools,CommonPortRange [] ranges, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_translation_port_range", new object[] {
pools,
ranges}, callback, asyncState);
}
public void Endset_translation_port_range(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_zombie_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/LSNPool",
RequestNamespace="urn:iControl:LocalLB/LSNPool", ResponseNamespace="urn:iControl:LocalLB/LSNPool")]
public void set_zombie_timeout(
string [] pools,
long [] timeouts
) {
this.Invoke("set_zombie_timeout", new object [] {
pools,
timeouts});
}
public System.IAsyncResult Beginset_zombie_timeout(string [] pools,long [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_zombie_timeout", new object[] {
pools,
timeouts}, callback, asyncState);
}
public void Endset_zombie_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.LSNPool.HairpinMode", Namespace = "urn:iControl")]
public enum LocalLBLSNPoolHairpinMode
{
LSN_HAIRPIN_MODE_UNKNOWN,
LSN_HAIRPIN_MODE_DISABLED,
LSN_HAIRPIN_MODE_ENABLED,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.LSNPool.InboundMode", Namespace = "urn:iControl")]
public enum LocalLBLSNPoolInboundMode
{
LSN_INBOUND_MODE_UNKNOWN,
LSN_INBOUND_MODE_DISABLED,
LSN_INBOUND_MODE_EXPLICIT,
LSN_INBOUND_MODE_AUTOMATIC,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.LSNPool.NATMode", Namespace = "urn:iControl")]
public enum LocalLBLSNPoolNATMode
{
LSN_MODE_UNKNOWN,
LSN_MODE_NAPT,
LSN_MODE_DETERMINISTIC,
LSN_MODE_PBA,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.LSNPool.PersistMode", Namespace = "urn:iControl")]
public enum LocalLBLSNPoolPersistMode
{
LSN_PERSIST_MODE_UNKNOWN,
LSN_PERSIST_MODE_NONE,
LSN_PERSIST_MODE_ADDRESS,
LSN_PERSIST_MODE_ADDRESS_PORT,
}
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.LSNPool.LSNPoolFailureStatistic", Namespace = "urn:iControl")]
public partial class LocalLBLSNPoolLSNPoolFailureStatistic
{
private string failure_causeField;
public string failure_cause
{
get { return this.failure_causeField; }
set { this.failure_causeField = value; }
}
private CommonULong64 failure_countField;
public CommonULong64 failure_count
{
get { return this.failure_countField; }
set { this.failure_countField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.LSNPool.LSNPoolStatisticEntry", Namespace = "urn:iControl")]
public partial class LocalLBLSNPoolLSNPoolStatisticEntry
{
private string poolField;
public string pool
{
get { return this.poolField; }
set { this.poolField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.LSNPool.LSNPoolStatisticEntry_v2", Namespace = "urn:iControl")]
public partial class LocalLBLSNPoolLSNPoolStatisticEntry_v2
{
private string poolField;
public string pool
{
get { return this.poolField; }
set { this.poolField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private LocalLBLSNPoolLSNPoolFailureStatistic [] failuresField;
public LocalLBLSNPoolLSNPoolFailureStatistic [] failures
{
get { return this.failuresField; }
set { this.failuresField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.LSNPool.LSNPoolStatistics", Namespace = "urn:iControl")]
public partial class LocalLBLSNPoolLSNPoolStatistics
{
private LocalLBLSNPoolLSNPoolStatisticEntry [] statisticsField;
public LocalLBLSNPoolLSNPoolStatisticEntry [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.LSNPool.LSNPoolStatistics_v2", Namespace = "urn:iControl")]
public partial class LocalLBLSNPoolLSNPoolStatistics_v2
{
private LocalLBLSNPoolLSNPoolStatisticEntry_v2 [] statisticsField;
public LocalLBLSNPoolLSNPoolStatisticEntry_v2 [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.