context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace FTAnalyzer.Utilities
{
public class MultiSelectTreeview : TreeView
{
#region Selected Node(s) Properties
readonly List<TreeNode> m_SelectedNodes;
public List<TreeNode> SelectedNodes
{
get => m_SelectedNodes;
set
{
ClearSelectedNodes();
if (value != null)
{
foreach (TreeNode node in value)
{
ToggleNode(node, true);
}
}
}
}
// Note we use the new keyword to Hide the native treeview's SelectedNode property.
private TreeNode m_SelectedNode;
public new TreeNode SelectedNode
{
get => m_SelectedNode;
set
{
ClearSelectedNodes();
if (value != null)
{
SelectNode(value);
}
}
}
#endregion
public MultiSelectTreeview()
{
m_SelectedNodes = new List<TreeNode>();
base.SelectedNode = null;
}
#region Overridden Events
protected override void OnGotFocus(EventArgs e)
{
// Make sure at least one node has a selection
// this way we can tab to the ctrl and use the
// keyboard to select nodes
try
{
if (m_SelectedNode == null && this.TopNode != null)
{
ToggleNode(this.TopNode, true);
OnAfterSelect(new TreeViewEventArgs(m_SelectedNode));
}
// Handle if HideSelection property is in use.
// Always redraw as highlighted when we gain focus
HighlightSelection();
base.OnGotFocus(e);
}
catch (Exception ex)
{
HandleException(ex);
}
}
protected override void OnLostFocus(EventArgs e)
{
try
{
// Handle if HideSelection property is in use.
if (this.HideSelection)
{
DimSelection();
}
base.OnLostFocus(e);
}
catch (Exception ex)
{
HandleException(ex);
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
// If the user clicks on a node that was not
// previously selected, select it now.
try
{
base.SelectedNode = null;
TreeNode node = this.GetNodeAt(e.Location);
if (node != null)
{
int leftBound = node.Bounds.X; // - 20; // Allow user to click on image
int rightBound = node.Bounds.Right + 10; // Give a little extra room
if (e.Location.X > leftBound && e.Location.X < rightBound)
{
if (ModifierKeys == Keys.None && (m_SelectedNodes.Contains(node)))
{
// Potential Drag Operation
// Let Mouse Up do select
}
else
{
SelectNode(node);
}
}
}
base.OnMouseDown(e);
}
catch (Exception ex)
{
HandleException(ex);
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
// If the clicked on a node that WAS previously
// selected then, reselect it now. This will clear
// any other selected nodes. e.g. A B C D are selected
// the user clicks on B, now A C & D are no longer selected.
try
{
// Check to see if a node was clicked on
TreeNode node = this.GetNodeAt(e.Location);
if (node != null)
{
if (ModifierKeys == Keys.None && m_SelectedNodes.Contains(node) && m_SelectedNodes.Count > 1)
{
int leftBound = node.Bounds.X; // -20; // Allow user to click on image
int rightBound = node.Bounds.Right + 10; // Give a little extra room
if (e.Location.X > leftBound && e.Location.X < rightBound)
{
SelectNode(node);
}
}
}
base.OnMouseUp(e);
}
catch (Exception ex)
{
HandleException(ex);
}
}
//protected override void OnItemDrag(ItemDragEventArgs e)
//{
// // If the user drags a node and the node being dragged is NOT
// // selected, then clear the active selection, select the
// // node being dragged and drag it. Otherwise if the node being
// // dragged is selected, drag the entire selection.
// try
// {
// TreeNode node = e.Item as TreeNode;
// if (node != null)
// {
// if (!m_SelectedNodes.Contains(node))
// {
// SelectSingleNode(node);
// ToggleNode(node, true);
// }
// }
// base.OnItemDrag(e);
// }
// catch (Exception ex)
// {
// HandleException(ex);
// }
//}
protected override void OnBeforeSelect(TreeViewCancelEventArgs e)
{
// Never allow base.SelectedNode to be set!
try
{
base.SelectedNode = null;
e.Cancel = true;
base.OnBeforeSelect(e);
}
catch (Exception ex)
{
HandleException(ex);
}
}
protected override void OnAfterSelect(TreeViewEventArgs e)
{
// Never allow base.SelectedNode to be set!
try
{
base.OnAfterSelect(e);
base.SelectedNode = null;
}
catch (Exception ex)
{
HandleException(ex);
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
// Handle all possible key strokes for the control.
// including navigation, selection, etc.
base.OnKeyDown(e);
if (e.KeyCode == Keys.ShiftKey) return;
if (e.KeyCode == Keys.ControlKey) return;
//this.BeginUpdate();
bool bShift = (ModifierKeys == Keys.Shift);
try
{
// Nothing is selected in the tree, this isn't a good state
// select the top node
if (m_SelectedNode == null && this.TopNode != null)
{
ToggleNode(this.TopNode, true);
OnAfterSelect(new TreeViewEventArgs(m_SelectedNode));
}
// Nothing is still selected in the tree, this isn't a good state, leave.
if (m_SelectedNode == null) return;
if (e.KeyCode == Keys.Left)
{
if (m_SelectedNode.IsExpanded && m_SelectedNode.Nodes.Count > 0)
{
// Collapse an expanded node that has children
m_SelectedNode.Collapse();
}
else if (m_SelectedNode.Parent != null)
{
// Node is already collapsed, try to select its parent.
SelectSingleNode(m_SelectedNode.Parent);
}
}
else if (e.KeyCode == Keys.Right)
{
if (!m_SelectedNode.IsExpanded)
{
// Expand a collpased node's children
m_SelectedNode.Expand();
}
else
{
// Node was already expanded, select the first child
SelectSingleNode(m_SelectedNode.FirstNode);
}
}
else if (e.KeyCode == Keys.Up)
{
// Select the previous node
if (m_SelectedNode.PrevVisibleNode != null)
{
SelectNode(m_SelectedNode.PrevVisibleNode);
}
}
else if (e.KeyCode == Keys.Down)
{
// Select the next node
if (m_SelectedNode.NextVisibleNode != null)
{
SelectNode(m_SelectedNode.NextVisibleNode);
}
}
else if (e.KeyCode == Keys.Home)
{
if (bShift)
{
if (m_SelectedNode.Parent == null)
{
// Select all of the root nodes up to this point
if (this.Nodes.Count > 0)
{
SelectNode(this.Nodes[0]);
}
}
else
{
// Select all of the nodes up to this point under this nodes parent
SelectNode(m_SelectedNode.Parent.FirstNode);
}
}
else
{
// Select this first node in the tree
if (this.Nodes.Count > 0)
{
SelectSingleNode(this.Nodes[0]);
}
}
}
else if (e.KeyCode == Keys.End)
{
if (bShift)
{
if (m_SelectedNode.Parent == null)
{
// Select the last ROOT node in the tree
if (this.Nodes.Count > 0)
{
SelectNode(this.Nodes[this.Nodes.Count - 1]);
}
}
else
{
// Select the last node in this branch
SelectNode(m_SelectedNode.Parent.LastNode);
}
}
else
{
if (this.Nodes.Count > 0)
{
// Select the last node visible node in the tree.
// Don't expand branches incase the tree is virtual
TreeNode ndLast = this.Nodes[0].LastNode;
while (ndLast.IsExpanded && (ndLast.LastNode != null))
{
ndLast = ndLast.LastNode;
}
SelectSingleNode(ndLast);
}
}
}
else if (e.KeyCode == Keys.PageUp)
{
// Select the highest node in the display
int nCount = this.VisibleCount;
TreeNode ndCurrent = m_SelectedNode;
while ((nCount) > 0 && (ndCurrent.PrevVisibleNode != null))
{
ndCurrent = ndCurrent.PrevVisibleNode;
nCount--;
}
SelectSingleNode(ndCurrent);
}
else if (e.KeyCode == Keys.PageDown)
{
// Select the lowest node in the display
int nCount = this.VisibleCount;
TreeNode ndCurrent = m_SelectedNode;
while ((nCount) > 0 && (ndCurrent.NextVisibleNode != null))
{
ndCurrent = ndCurrent.NextVisibleNode;
nCount--;
}
SelectSingleNode(ndCurrent);
}
else if (e.Control && (e.KeyCode == Keys.A))
{
// Select All (CTRL-A), selects all top level nodes
this.ClearSelectedNodes();
this.CollapseAll();
TreeNode ndCurrent = this.TopNode;
while (ndCurrent != null)
{
ToggleNode(ndCurrent, true);
ndCurrent = ndCurrent.NextNode;
}
}
else
{
// Assume this is a search character a-z, A-Z, 0-9, etc.
// Select the first node after the current node that
// starts with this character
string sSearch = ((char)e.KeyValue).ToString();
TreeNode ndCurrent = m_SelectedNode;
while ((ndCurrent.NextVisibleNode != null))
{
ndCurrent = ndCurrent.NextVisibleNode;
if (ndCurrent.Text.StartsWith(sSearch))
{
SelectSingleNode(ndCurrent);
break;
}
}
}
}
catch (Exception ex)
{
HandleException(ex);
}
finally
{
this.EndUpdate();
}
}
#endregion
#region Helper Methods
void HighlightSelection()
{
foreach (TreeNode node in SelectedNodes)
{
node.BackColor = SystemColors.Highlight;
node.ForeColor = SystemColors.HighlightText;
}
}
void DimSelection()
{
foreach (TreeNode node in SelectedNodes)
{
node.BackColor = SystemColors.Control;
node.ForeColor = this.ForeColor;
}
}
void SelectNode(TreeNode node)
{
try
{
this.BeginUpdate();
if (m_SelectedNode == null || ModifierKeys == Keys.Control)
{
// Ctrl+Click selects an unselected node, or unselects a selected node.
bool bIsSelected = m_SelectedNodes.Contains(node);
ToggleNode(node, !bIsSelected);
OnAfterSelect(new TreeViewEventArgs(m_SelectedNode));
}
else if (ModifierKeys == Keys.Shift)
{
// Shift+Click selects nodes between the selected node and here.
TreeNode ndStart = m_SelectedNode;
TreeNode ndEnd = node;
if (ndStart.Parent == ndEnd.Parent)
{
// Selected node and clicked node have same parent, easy case.
if (ndStart.Index < ndEnd.Index)
{
// If the selected node is beneath the clicked node walk down
// selecting each Visible node until we reach the end.
while (ndStart != ndEnd)
{
ndStart = ndStart.NextVisibleNode;
if (ndStart == null) break;
ToggleNode(ndStart, true);
}
}
else if (ndStart.Index == ndEnd.Index)
{
// Clicked same node, do nothing
}
else
{
// If the selected node is above the clicked node walk up
// selecting each Visible node until we reach the end.
while (ndStart != ndEnd)
{
ndStart = ndStart.PrevVisibleNode;
if (ndStart == null) break;
ToggleNode(ndStart, true);
}
}
}
else
{
// Selected node and clicked node have same parent, hard case.
// We need to find a common parent to determine if we need
// to walk down selecting, or walk up selecting.
TreeNode ndStartP = ndStart;
TreeNode ndEndP = ndEnd;
int startDepth = Math.Min(ndStartP.Level, ndEndP.Level);
// Bring lower node up to common depth
while (ndStartP.Level > startDepth)
{
ndStartP = ndStartP.Parent;
}
// Bring lower node up to common depth
while (ndEndP.Level > startDepth)
{
ndEndP = ndEndP.Parent;
}
// Walk up the tree until we find the common parent
while (ndStartP.Parent != ndEndP.Parent)
{
ndStartP = ndStartP.Parent;
ndEndP = ndEndP.Parent;
}
// Select the node
if (ndStartP.Index < ndEndP.Index)
{
// If the selected node is beneath the clicked node walk down
// selecting each Visible node until we reach the end.
while (ndStart != ndEnd)
{
ndStart = ndStart.NextVisibleNode;
if (ndStart == null) break;
ToggleNode(ndStart, true);
}
}
else if (ndStartP.Index == ndEndP.Index)
{
if (ndStart.Level < ndEnd.Level)
{
while (ndStart != ndEnd)
{
ndStart = ndStart.NextVisibleNode;
if (ndStart == null) break;
ToggleNode(ndStart, true);
}
}
else
{
while (ndStart != ndEnd)
{
ndStart = ndStart.PrevVisibleNode;
if (ndStart == null) break;
ToggleNode(ndStart, true);
}
}
}
else
{
// If the selected node is above the clicked node walk up
// selecting each Visible node until we reach the end.
while (ndStart != ndEnd)
{
ndStart = ndStart.PrevVisibleNode;
if (ndStart == null) break;
ToggleNode(ndStart, true);
}
}
}
OnAfterSelect(new TreeViewEventArgs(m_SelectedNode));
}
else
{
// Just clicked a node, select it
SelectSingleNode(node);
}
}
finally
{
this.EndUpdate();
}
}
void ClearSelectedNodes()
{
try
{
foreach (TreeNode node in m_SelectedNodes)
{
node.BackColor = this.BackColor;
node.ForeColor = this.ForeColor;
}
}
finally
{
m_SelectedNodes.Clear();
m_SelectedNode = null;
}
}
void SelectSingleNode(TreeNode node)
{
if (node == null)
{
return;
}
ClearSelectedNodes();
ToggleNode(node, true);
node.EnsureVisible();
OnAfterSelect(new TreeViewEventArgs(node));
}
void ToggleNode(TreeNode node, bool bSelectNode)
{
if (bSelectNode)
{
m_SelectedNode = node;
if (!m_SelectedNodes.Contains(node))
{
m_SelectedNodes.Add(node);
}
node.BackColor = SystemColors.Highlight;
node.ForeColor = SystemColors.HighlightText;
}
else
{
m_SelectedNodes.Remove(node);
node.BackColor = this.BackColor;
node.ForeColor = this.ForeColor;
}
}
void HandleException(Exception ex)
{
// Perform some error handling here.
// We don't want to bubble errors to the CLR.
MessageBox.Show(ex.Message);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Piczy.Types;
namespace Piczy.Resizer
{
public class WorkerRole : RoleEntryPoint
{
List<Size> _imageSizes = new List<Size>();
static RetryManager RetryManager { get; set; }
static Microsoft.Practices.TransientFaultHandling.RetryPolicy StorageRetryPolicy { get; set; }
public override void Run()
{
var storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
CloudBlobClient blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("photos");
CloudQueueClient queueStorage = storageAccount.CreateCloudQueueClient();
CloudQueue queue = queueStorage.GetQueueReference("resizer");
CloudTableClient tableStorage = storageAccount.CreateCloudTableClient();
string tableName = "photos";
// create container and queue if not created
StorageRetryPolicy.ExecuteAction(() =>
{
container.CreateIfNotExist();
var permissions = container.GetPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Container;
container.SetPermissions(permissions);
queue.CreateIfNotExist();
tableStorage.CreateTableIfNotExist(tableName);
});
var tableContext = tableStorage.GetDataServiceContext();
// dequeue and process messages from the queue
while (true)
{
try
{
var msg = queue.GetMessage();
if (msg != null)
{
// get the base name of the image
string path = msg.AsString;
var baseName = Path.GetFileNameWithoutExtension(path);
// download image from blob into memory
var blob = container.GetBlockBlobReference(path);
using (var sourceImageStream = new MemoryStream())
{
blob.DownloadToStream(sourceImageStream);
// build resized images for each image size and upload to blob
foreach (var size in _imageSizes)
{
sourceImageStream.Seek(0, SeekOrigin.Begin);
using (var targetImageStream = ResizeImage(sourceImageStream, size.Width, size.Height))
{
// upload to blob
var imageName = String.Format("{0}-{1}x{2}.jpg", baseName, size.Width, size.Height);
var resizedBlob = container.GetBlockBlobReference(imageName);
resizedBlob.Properties.ContentType = "image/jpeg";
targetImageStream.Seek(0, SeekOrigin.Begin);
resizedBlob.UploadFromStream(targetImageStream);
}
}
}
// get the entity from the table based on file name and upate status
var rowKey = Path.GetFileName(path);
var partitionKey = rowKey[0].ToString();
var query = (from photo in tableContext.CreateQuery<Photo>(tableName)
where photo.PartitionKey == partitionKey && photo.RowKey == rowKey
select photo).AsTableServiceQuery<Photo>();
var photoEntity = query.First();
photoEntity.Status = (int)FileStatus.Processed;
tableContext.UpdateObject(photoEntity);
tableContext.SaveChangesWithRetries();
queue.DeleteMessage(msg);
}
else
{
System.Threading.Thread.Sleep(1000);
}
}
catch (StorageException ex)
{
System.Threading.Thread.Sleep(5000);
Trace.TraceError(string.Format("Exception when processing queue item. Message: '{0}'", ex.Message));
}
}
}
static WorkerRole()
{
InitializeRetryPolicies();
}
private static void InitializeRetryPolicies()
{
if(RetryManager == null)
{
RetryManager = EnterpriseLibraryContainer.Current.GetInstance<RetryManager>();
}
if (StorageRetryPolicy == null)
{
StorageRetryPolicy = RetryManager.GetDefaultAzureStorageRetryPolicy();
}
}
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
#region Setup CloudStorageAccount Configuration Setting Publisher
// This code sets up a handler to update CloudStorageAccount instances when their corresponding
// configuration settings change in the service configuration file.
CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
{
// Provide the configSetter with the initial value
configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
RoleEnvironment.Changed += (sender, arg) =>
{
if (arg.Changes.OfType<RoleEnvironmentConfigurationSettingChange>()
.Any((change) => (change.ConfigurationSettingName == configName)))
{
// The corresponding configuration setting has changed, propagate the value
if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))
{
// In this case, the change to the storage account credentials in the
// service configuration is significant enough that the role needs to be
// recycled in order to use the latest settings. (for example, the
// endpoint has changed)
RoleEnvironment.RequestRecycle();
}
}
};
});
#endregion
// load up the desired image sizes
var imageSizes = RoleEnvironment.GetConfigurationSettingValue("ImageSizes");
foreach (var size in imageSizes.Split(','))
{
var dims = size.Split('x');
_imageSizes.Add(new Size(Int32.Parse(dims[0]), Int32.Parse(dims[1])));
}
return base.OnStart();
}
private Stream ResizeImage(Stream sourceImageStream, int width, int height)
{
using (var sourceImage = Image.FromStream(sourceImageStream))
{
// compute target dimensions respecting aspect ratio
if (sourceImage.Width > sourceImage.Height)
{
height = (int)((double)sourceImage.Height * ((double)width / (double)sourceImage.Width));
}
else
{
width = (int)((double)sourceImage.Width * ((double)height / (double)sourceImage.Height));
}
// resize and render image
using (Image targetImage = new Bitmap(width, height, sourceImage.PixelFormat))
{
using (Graphics g = Graphics.FromImage(targetImage))
{
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle rect = new Rectangle(0, 0, width, height);
g.DrawImage(sourceImage, rect);
var targetImageStream = new MemoryStream();
targetImage.Save(targetImageStream, ImageFormat.Jpeg);
return targetImageStream;
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace MixedRealityToolkit.Build
{
/// <summary>
/// Base class for auto configuration build windows.
/// </summary>
public abstract class AutoConfigureWindow<TSetting> : EditorWindow
{
#region Member Fields
private Dictionary<TSetting, bool> values = new Dictionary<TSetting, bool>();
private Dictionary<TSetting, string> names = new Dictionary<TSetting, string>();
private Dictionary<TSetting, string> descriptions = new Dictionary<TSetting, string>();
private string statusMessage = string.Empty;
private Vector2 scrollPosition = Vector2.zero;
private GUIStyle wrapStyle;
#endregion // Member Fields
#region Internal Methods
private void SettingToggle(TSetting setting)
{
EditorGUI.BeginChangeCheck();
// Draw and update setting flag
values[setting] = GUILayout.Toggle(values[setting], new GUIContent(names[setting]));
if (EditorGUI.EndChangeCheck())
{
OnGuiChanged();
}
// If this control is the one under the mouse, update the status message
if (Event.current.type == EventType.Repaint && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
{
StatusMessage = descriptions[setting];
Repaint();
}
}
/// <summary>
/// Gets or sets the status message displayed at the bottom of the window.
/// </summary>
private string StatusMessage { get { return statusMessage; } set { statusMessage = value; } }
/// <summary>
/// Checks all the checkboxes in the window.
/// </summary>
private void SelectAll()
{
var keys = values.Keys.ToArray();
for (int iKey = 0; iKey < keys.Length; iKey++)
{
Values[keys[iKey]] = true;
}
}
/// <summary>
/// Unchecks all the checkboxes in the window.
/// </summary>
private void SelectNone()
{
var keys = values.Keys.ToArray();
for (int iKey = 0; iKey < keys.Length; iKey++)
{
Values[keys[iKey]] = false;
}
}
#endregion // Internal Methods
#region Overridables / Event Triggers
/// <summary>
/// Called when settings should be applied.
/// </summary>
protected abstract void ApplySettings();
/// <summary>
/// Called when settings should be loaded.
/// </summary>
protected abstract void LoadSettings();
/// <summary>
/// Called when string names and descriptions should be loaded.
/// </summary>
protected abstract void LoadStrings();
/// <summary>
/// Called when a toggle has been flipped and a change has been detected.
/// </summary>
protected abstract void OnGuiChanged();
#endregion // Overridables / Event Triggers
#region Overrides / Event Handlers
/// <summary>
/// Called when the window is created.
/// </summary>
protected virtual void Awake()
{
wrapStyle = new GUIStyle("label")
{
wordWrap = true,
richText = true
};
}
protected virtual void OnEnable()
{
LoadStrings();
LoadSettings();
}
/// <summary>
/// Renders the GUI
/// </summary>
protected virtual void OnGUI()
{
// Begin Settings Section
GUILayout.BeginVertical(EditorStyles.helpBox);
// Individual Settings
var keys = values.Keys.ToArray();
for (int iKey = 0; iKey < keys.Length; iKey++)
{
SettingToggle(keys[iKey]);
}
// End Settings Section
GUILayout.EndVertical();
// Status box area
GUILayout.BeginVertical(EditorStyles.helpBox);
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
GUILayout.Label(statusMessage, wrapStyle);
GUILayout.EndScrollView();
GUILayout.EndVertical();
// Buttons
GUILayout.BeginHorizontal(EditorStyles.miniButtonRight);
bool selectAllClicked = GUILayout.Button("Select All");
bool selectNoneClicked = GUILayout.Button("Select None");
bool applyClicked = GUILayout.Button("Apply");
GUILayout.EndHorizontal();
// Clicked?
if (selectAllClicked)
{
SelectAll();
}
if (selectNoneClicked)
{
SelectNone();
}
if (applyClicked)
{
ApplySettings();
}
}
#endregion // Overrides / Event Handlers
#region Protected Properties
/// <summary>
/// Gets the descriptions of the settings.
/// </summary>
protected Dictionary<TSetting, string> Descriptions
{
get
{
return descriptions;
}
set
{
descriptions = value;
}
}
/// <summary>
/// Gets the names of the settings.
/// </summary>
protected Dictionary<TSetting, string> Names
{
get
{
return names;
}
set
{
names = value;
}
}
/// <summary>
/// Gets the values of the settings.
/// </summary>
protected Dictionary<TSetting, bool> Values
{
get
{
return values;
}
set
{
values = value;
}
}
#endregion // Protected Properties
}
}
| |
/*
*
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
Copyright (c) 2010 devFU Pty Ltd, Josh Wilson and Others (http://reportfu.org)
This file has been modified with suggestiong from forum users.
*Obtained from Forum, User: sinnovasoft http://www.fyireporting.com/forum/viewtopic.php?t=1049
Refactored by Daniel Romanowski http://dotlink.pl
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using fyiReporting.RDL.Utility;
using System.Security;
using System.Globalization;
namespace fyiReporting.RDL
{
///<summary>
/// Renders a report to PDF. This is a page oriented formatting renderer.
///</summary>
[SecuritySafeCritical]
internal abstract class RenderBase : IPresent
{
#region private
Stream _streamGen; // where the output is going
Report _report; // report
#endregion
#region properties
private PdfPageSize _pageSize;
internal protected PdfPageSize PageSize
{
get { return _pageSize; }
private set { _pageSize = value; }
}
#endregion
#region abstract methods
/// <summary>
/// Page line element at the X Y to X2 Y2 position
/// </summary>
/// <returns></returns>
internal abstract protected void CreateDocument();
internal abstract protected void EndDocument(Stream sg);
#endregion
#region virtual methods
internal virtual protected void CreatePage() { }
internal virtual protected void AfterProcessPage() { }
internal virtual protected void AddBookmark(PageText pt) { }
internal virtual protected void AddLine(float x, float y, float x2, float y2, float width, System.Drawing.Color c, BorderStyleEnum ls) { }
/// <summary>
/// Add image to the page.
/// </summary>
/// <returns>string Image name</returns>
internal virtual protected void AddImage(string name, StyleInfo si,
ImageFormat imf, float x, float y, float width, float height, RectangleF clipRect,
byte[] im, int samplesW, int samplesH, string url, string tooltip) { }
/// <summary>
/// Page Polygon
/// </summary>
/// <param name="pts"></param>
/// <param name="si"></param>
/// <param name="url"></param>
/// <param name="patterns"></param>
internal virtual protected void AddPolygon(PointF[] pts, StyleInfo si, string url) { }
/// <summary>
/// Page Rectangle element at the X Y position
/// </summary>
/// <returns></returns>
internal virtual protected void AddRectangle(float x, float y, float height, float width, StyleInfo si, string url, string tooltip) { }
/// <summary>
/// Draw a pie
/// </summary>
/// <returns></returns>
internal virtual protected void AddPie(float x, float y, float height, float width, StyleInfo si, string url, string tooltip) { }
/// <summary>
/// Draw a curve
/// </summary>
/// <returns></returns>
internal virtual protected void AddCurve(PointF[] pts, StyleInfo si) { }
//25072008 GJL Draw 4 bezier curves to approximate a circle
internal virtual protected void AddEllipse(float x, float y, float height, float width, StyleInfo si, string url) { }
/// <summary>
/// Page Text element at the X Y position; multiple lines handled
/// </summary>
/// <returns></returns>
internal virtual protected void AddText(PageText pt, Pages pgs) { }
#endregion
//Replaced from forum, User: Aulofee http://www.fyireporting.com/forum/viewtopic.php?t=793
public void Dispose() { }
public RenderBase(Report rep, IStreamGen sg)
{
_streamGen = sg.GetStream();
_report = rep;
}
public Report Report()
{
return _report;
}
public void Start()
{
CreateDocument();
}
public void End()
{
EndDocument(_streamGen);
return;
}
public void RunPages(Pages pgs) // this does all the work
{
foreach (Page p in pgs)
{
PageSize = new PdfPageSize((int)_report.ReportDefinition.PageWidth.ToPoints(),
(int)_report.ReportDefinition.PageHeight.ToPoints());
//Create a Page
CreatePage();
ProcessPage(pgs, p);
// after a page
AfterProcessPage();
}
return;
}
// render all the objects in a page in PDF
private void ProcessPage(Pages pgs, IEnumerable items)
{
foreach (PageItem pi in items)
{
if (pi.SI.BackgroundImage != null)
{ // put out any background image
PageImage bgImg = pi.SI.BackgroundImage;
// elements.AddImage(images, i.Name, content.objectNum, i.SI, i.ImgFormat,
// pi.X, pi.Y, pi.W, pi.H, i.ImageData,i.SamplesW, i.SamplesH, null);
//Duc Phan modified 10 Dec, 2007 to support on background image
float imW = Measurement.PointsFromPixels(bgImg.SamplesW, pgs.G.DpiX);
float imH = Measurement.PointsFromPixels(bgImg.SamplesH, pgs.G.DpiY);
int repeatX = 0;
int repeatY = 0;
float itemW = pi.W - (pi.SI.PaddingLeft + pi.SI.PaddingRight);
float itemH = pi.H - (pi.SI.PaddingTop + pi.SI.PaddingBottom);
switch (bgImg.Repeat)
{
case ImageRepeat.Repeat:
repeatX = (int)Math.Floor(itemW / imW);
repeatY = (int)Math.Floor(itemH / imH);
break;
case ImageRepeat.RepeatX:
repeatX = (int)Math.Floor(itemW / imW);
repeatY = 1;
break;
case ImageRepeat.RepeatY:
repeatY = (int)Math.Floor(itemH / imH);
repeatX = 1;
break;
case ImageRepeat.NoRepeat:
default:
repeatX = repeatY = 1;
break;
}
//make sure the image is drawn at least 1 times
repeatX = Math.Max(repeatX, 1);
repeatY = Math.Max(repeatY, 1);
float currX = pi.X + pi.SI.PaddingLeft;
float currY = pi.Y + pi.SI.PaddingTop;
float startX = currX;
float startY = currY;
for (int i = 0; i < repeatX; i++)
{
for (int j = 0; j < repeatY; j++)
{
currX = startX + i * imW;
currY = startY + j * imH;
AddImage( bgImg.Name,bgImg.SI, bgImg.ImgFormat,
currX, currY, imW, imH, RectangleF.Empty, bgImg.ImageData, bgImg.SamplesW, bgImg.SamplesH, null, pi.Tooltip);
}
}
}
if (pi is PageTextHtml)
{
PageTextHtml pth = pi as PageTextHtml;
pth.Build(pgs.G);
ProcessPage(pgs, pth);
continue;
}
if (pi is PageText)
{
PageText pt = pi as PageText;
AddText(pt,pgs);
if (pt.Bookmark != null)
{
AddBookmark(pt);
}
continue;
}
if (pi is PageLine)
{
PageLine pl = pi as PageLine;
AddLine(pl.X, pl.Y, pl.X2, pl.Y2, pl.SI);
continue;
}
if (pi is PageEllipse)
{
PageEllipse pe = pi as PageEllipse;
AddEllipse(pe.X, pe.Y, pe.H, pe.W, pe.SI, pe.HyperLink);
continue;
}
if (pi is PageImage)
{
PageImage i = pi as PageImage;
//Duc Phan added 20 Dec, 2007 to support sized image
RectangleF r2 = new RectangleF(i.X + i.SI.PaddingLeft, i.Y + i.SI.PaddingTop, i.W - i.SI.PaddingLeft - i.SI.PaddingRight, i.H - i.SI.PaddingTop - i.SI.PaddingBottom);
RectangleF adjustedRect; // work rectangle
RectangleF clipRect = RectangleF.Empty;
switch (i.Sizing)
{
case ImageSizingEnum.AutoSize:
adjustedRect = new RectangleF(r2.Left, r2.Top,
r2.Width, r2.Height);
break;
case ImageSizingEnum.Clip:
adjustedRect = new RectangleF(r2.Left, r2.Top,
Measurement.PointsFromPixels(i.SamplesW, pgs.G.DpiX), Measurement.PointsFromPixels(i.SamplesH, pgs.G.DpiY));
clipRect = new RectangleF(r2.Left, r2.Top,
r2.Width, r2.Height);
break;
case ImageSizingEnum.FitProportional:
float height;
float width;
float ratioIm = (float)i.SamplesH / i.SamplesW;
float ratioR = r2.Height / r2.Width;
height = r2.Height;
width = r2.Width;
if (ratioIm > ratioR)
{ // this means the rectangle width must be corrected
width = height * (1 / ratioIm);
}
else if (ratioIm < ratioR)
{ // this means the rectangle height must be corrected
height = width * ratioIm;
}
adjustedRect = new RectangleF(r2.X, r2.Y, width, height);
break;
case ImageSizingEnum.Fit:
default:
adjustedRect = r2;
break;
}
if (i.ImgFormat == System.Drawing.Imaging.ImageFormat.Wmf || i.ImgFormat == System.Drawing.Imaging.ImageFormat.Emf)
{
//We dont want to add it - its already been broken down into page items;
}
else
{
AddImage(i.Name, i.SI, i.ImgFormat,
adjustedRect.X, adjustedRect.Y, adjustedRect.Width, adjustedRect.Height, clipRect, i.ImageData, i.SamplesW, i.SamplesH, i.HyperLink, i.Tooltip);
}
continue;
}
if (pi is PageRectangle)
{
PageRectangle pr = pi as PageRectangle;
AddRectangle(pr.X, pr.Y, pr.H, pr.W, pi.SI, pi.HyperLink, pi.Tooltip);
continue;
}
if (pi is PagePie)
{ // TODO
PagePie pp = pi as PagePie;
//
AddPie(pp.X, pp.Y, pp.H, pp.W, pi.SI, pi.HyperLink, pi.Tooltip);
continue;
}
if (pi is PagePolygon)
{
PagePolygon ppo = pi as PagePolygon;
AddPolygon(ppo.Points, pi.SI, pi.HyperLink);
continue;
}
if (pi is PageCurve)
{
PageCurve pc = pi as PageCurve;
AddCurve(pc.Points, pi.SI);
continue;
}
}
}
#region protected utils
internal protected bool IsTableCell(Textbox tb)
{
Type tp = tb.Parent.Parent.GetType();
return (tp == typeof(TableCell) ||
tp == typeof(Corner) ||
tp == typeof(DynamicColumns) ||
tp == typeof(DynamicRows) ||
tp == typeof(StaticRow) ||
tp == typeof(StaticColumn) ||
tp == typeof(Subtotal) ||
tp == typeof(MatrixCell));
}
internal protected bool IsNumeric(string str, CultureInfo culture = null, NumberStyles style = NumberStyles.Number)
{
double numOut;
if (culture == null) culture = CultureInfo.InvariantCulture;
return Double.TryParse(str, style, culture, out numOut) && !String.IsNullOrWhiteSpace(str);
}
internal protected void AddLine(float x, float y, float x2, float y2, StyleInfo si)
{
AddLine(x, y, x2, y2, si.BWidthTop, si.BColorTop, si.BStyleTop);
}
#endregion
#region IPresent implementations
public virtual bool IsPagingNeeded()
{
return true;
}
// Body: main container for the report
public virtual void BodyStart(Body b)
{
}
public virtual void BodyEnd(Body b)
{
}
public virtual void PageHeaderStart(PageHeader ph)
{
}
public virtual void PageHeaderEnd(PageHeader ph)
{
}
public virtual void PageFooterStart(PageFooter pf)
{
}
public virtual void PageFooterEnd(PageFooter pf)
{
}
public virtual void Textbox(Textbox tb, string t, Row row)
{
}
public virtual void DataRegionNoRows(DataRegion d, string noRowsMsg)
{
}
// Lists
public virtual bool ListStart(List l, Row r)
{
return true;
}
public virtual void ListEnd(List l, Row r)
{
}
public virtual void ListEntryBegin(List l, Row r)
{
}
public virtual void ListEntryEnd(List l, Row r)
{
}
// Tables // Report item table
public virtual bool TableStart(Table t, Row row)
{
return true;
}
public virtual void TableEnd(Table t, Row row)
{
}
public virtual void TableBodyStart(Table t, Row row)
{
}
public virtual void TableBodyEnd(Table t, Row row)
{
}
public virtual void TableFooterStart(Footer f, Row row)
{
}
public virtual void TableFooterEnd(Footer f, Row row)
{
}
public virtual void TableHeaderStart(Header h, Row row)
{
}
public virtual void TableHeaderEnd(Header h, Row row)
{
}
public virtual void TableRowStart(TableRow tr, Row row)
{
}
public virtual void TableRowEnd(TableRow tr, Row row)
{
}
public virtual void TableCellStart(TableCell t, Row row)
{
return;
}
public virtual void TableCellEnd(TableCell t, Row row)
{
return;
}
public virtual bool MatrixStart(Matrix m, MatrixCellEntry[,] matrix, Row r, int headerRows, int maxRows, int maxCols) // called first
{
return true;
}
public virtual void MatrixColumns(Matrix m, MatrixColumns mc) // called just after MatrixStart
{
}
public virtual void MatrixCellStart(Matrix m, ReportItem ri, int row, int column, Row r, float h, float w, int colSpan)
{
}
public virtual void MatrixCellEnd(Matrix m, ReportItem ri, int row, int column, Row r)
{
}
public virtual void MatrixRowStart(Matrix m, int row, Row r)
{
}
public virtual void MatrixRowEnd(Matrix m, int row, Row r)
{
}
public virtual void MatrixEnd(Matrix m, Row r) // called last
{
}
public virtual void Chart(Chart c, Row r, ChartBase cb)
{
}
public virtual void Image(fyiReporting.RDL.Image i, Row r, string mimeType, Stream ior)
{
}
public virtual void Line(Line l, Row r)
{
return;
}
public virtual bool RectangleStart(fyiReporting.RDL.Rectangle rect, Row r)
{
return true;
}
public virtual void RectangleEnd(fyiReporting.RDL.Rectangle rect, Row r)
{
}
public virtual void Subreport(Subreport s, Row r)
{
}
public virtual void GroupingStart(Grouping g) // called at start of grouping
{
}
public virtual void GroupingInstanceStart(Grouping g) // called at start for each grouping instance
{
}
public virtual void GroupingInstanceEnd(Grouping g) // called at start for each grouping instance
{
}
public virtual void GroupingEnd(Grouping g) // called at end of grouping
{
}
#endregion
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY 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.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A storage manager plugin
/// First published in XenServer 4.0.
/// </summary>
public partial class SM : XenObject<SM>
{
#region Constructors
public SM()
{
}
public SM(string uuid,
string name_label,
string name_description,
string type,
string vendor,
string copyright,
string version,
string required_api_version,
Dictionary<string, string> configuration,
string[] capabilities,
Dictionary<string, long> features,
Dictionary<string, string> other_config,
string driver_filename,
string[] required_cluster_stack)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.type = type;
this.vendor = vendor;
this.copyright = copyright;
this.version = version;
this.required_api_version = required_api_version;
this.configuration = configuration;
this.capabilities = capabilities;
this.features = features;
this.other_config = other_config;
this.driver_filename = driver_filename;
this.required_cluster_stack = required_cluster_stack;
}
/// <summary>
/// Creates a new SM from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public SM(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new SM from a Proxy_SM.
/// </summary>
/// <param name="proxy"></param>
public SM(Proxy_SM proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given SM.
/// </summary>
public override void UpdateFrom(SM update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
type = update.type;
vendor = update.vendor;
copyright = update.copyright;
version = update.version;
required_api_version = update.required_api_version;
configuration = update.configuration;
capabilities = update.capabilities;
features = update.features;
other_config = update.other_config;
driver_filename = update.driver_filename;
required_cluster_stack = update.required_cluster_stack;
}
internal void UpdateFrom(Proxy_SM proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
type = proxy.type == null ? null : proxy.type;
vendor = proxy.vendor == null ? null : proxy.vendor;
copyright = proxy.copyright == null ? null : proxy.copyright;
version = proxy.version == null ? null : proxy.version;
required_api_version = proxy.required_api_version == null ? null : proxy.required_api_version;
configuration = proxy.configuration == null ? null : Maps.convert_from_proxy_string_string(proxy.configuration);
capabilities = proxy.capabilities == null ? new string[] {} : (string [])proxy.capabilities;
features = proxy.features == null ? null : Maps.convert_from_proxy_string_long(proxy.features);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
driver_filename = proxy.driver_filename == null ? null : proxy.driver_filename;
required_cluster_stack = proxy.required_cluster_stack == null ? new string[] {} : (string [])proxy.required_cluster_stack;
}
public Proxy_SM ToProxy()
{
Proxy_SM result_ = new Proxy_SM();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.type = type ?? "";
result_.vendor = vendor ?? "";
result_.copyright = copyright ?? "";
result_.version = version ?? "";
result_.required_api_version = required_api_version ?? "";
result_.configuration = Maps.convert_to_proxy_string_string(configuration);
result_.capabilities = capabilities;
result_.features = Maps.convert_to_proxy_string_long(features);
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.driver_filename = driver_filename ?? "";
result_.required_cluster_stack = required_cluster_stack;
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this SM
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("type"))
type = Marshalling.ParseString(table, "type");
if (table.ContainsKey("vendor"))
vendor = Marshalling.ParseString(table, "vendor");
if (table.ContainsKey("copyright"))
copyright = Marshalling.ParseString(table, "copyright");
if (table.ContainsKey("version"))
version = Marshalling.ParseString(table, "version");
if (table.ContainsKey("required_api_version"))
required_api_version = Marshalling.ParseString(table, "required_api_version");
if (table.ContainsKey("configuration"))
configuration = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "configuration"));
if (table.ContainsKey("capabilities"))
capabilities = Marshalling.ParseStringArray(table, "capabilities");
if (table.ContainsKey("features"))
features = Maps.convert_from_proxy_string_long(Marshalling.ParseHashTable(table, "features"));
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
if (table.ContainsKey("driver_filename"))
driver_filename = Marshalling.ParseString(table, "driver_filename");
if (table.ContainsKey("required_cluster_stack"))
required_cluster_stack = Marshalling.ParseStringArray(table, "required_cluster_stack");
}
public bool DeepEquals(SM other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._type, other._type) &&
Helper.AreEqual2(this._vendor, other._vendor) &&
Helper.AreEqual2(this._copyright, other._copyright) &&
Helper.AreEqual2(this._version, other._version) &&
Helper.AreEqual2(this._required_api_version, other._required_api_version) &&
Helper.AreEqual2(this._configuration, other._configuration) &&
Helper.AreEqual2(this._capabilities, other._capabilities) &&
Helper.AreEqual2(this._features, other._features) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._driver_filename, other._driver_filename) &&
Helper.AreEqual2(this._required_cluster_stack, other._required_cluster_stack);
}
internal static List<SM> ProxyArrayToObjectList(Proxy_SM[] input)
{
var result = new List<SM>();
foreach (var item in input)
result.Add(new SM(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, SM server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
SM.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given SM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
public static SM get_record(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_record(session.opaque_ref, _sm);
else
return new SM(session.proxy.sm_get_record(session.opaque_ref, _sm ?? "").parse());
}
/// <summary>
/// Get a reference to the SM instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<SM> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<SM>.Create(session.proxy.sm_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the SM instances with the given label.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<SM>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<SM>.Create(session.proxy.sm_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given SM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
public static string get_uuid(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_uuid(session.opaque_ref, _sm);
else
return session.proxy.sm_get_uuid(session.opaque_ref, _sm ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given SM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
public static string get_name_label(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_name_label(session.opaque_ref, _sm);
else
return session.proxy.sm_get_name_label(session.opaque_ref, _sm ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given SM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
public static string get_name_description(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_name_description(session.opaque_ref, _sm);
else
return session.proxy.sm_get_name_description(session.opaque_ref, _sm ?? "").parse();
}
/// <summary>
/// Get the type field of the given SM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
public static string get_type(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_type(session.opaque_ref, _sm);
else
return session.proxy.sm_get_type(session.opaque_ref, _sm ?? "").parse();
}
/// <summary>
/// Get the vendor field of the given SM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
public static string get_vendor(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_vendor(session.opaque_ref, _sm);
else
return session.proxy.sm_get_vendor(session.opaque_ref, _sm ?? "").parse();
}
/// <summary>
/// Get the copyright field of the given SM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
public static string get_copyright(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_copyright(session.opaque_ref, _sm);
else
return session.proxy.sm_get_copyright(session.opaque_ref, _sm ?? "").parse();
}
/// <summary>
/// Get the version field of the given SM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
public static string get_version(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_version(session.opaque_ref, _sm);
else
return session.proxy.sm_get_version(session.opaque_ref, _sm ?? "").parse();
}
/// <summary>
/// Get the required_api_version field of the given SM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
public static string get_required_api_version(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_required_api_version(session.opaque_ref, _sm);
else
return session.proxy.sm_get_required_api_version(session.opaque_ref, _sm ?? "").parse();
}
/// <summary>
/// Get the configuration field of the given SM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
public static Dictionary<string, string> get_configuration(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_configuration(session.opaque_ref, _sm);
else
return Maps.convert_from_proxy_string_string(session.proxy.sm_get_configuration(session.opaque_ref, _sm ?? "").parse());
}
/// <summary>
/// Get the capabilities field of the given SM.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 6.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
[Deprecated("XenServer 6.2")]
public static string[] get_capabilities(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_capabilities(session.opaque_ref, _sm);
else
return (string [])session.proxy.sm_get_capabilities(session.opaque_ref, _sm ?? "").parse();
}
/// <summary>
/// Get the features field of the given SM.
/// First published in XenServer 6.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
public static Dictionary<string, long> get_features(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_features(session.opaque_ref, _sm);
else
return Maps.convert_from_proxy_string_long(session.proxy.sm_get_features(session.opaque_ref, _sm ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given SM.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
public static Dictionary<string, string> get_other_config(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_other_config(session.opaque_ref, _sm);
else
return Maps.convert_from_proxy_string_string(session.proxy.sm_get_other_config(session.opaque_ref, _sm ?? "").parse());
}
/// <summary>
/// Get the driver_filename field of the given SM.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
public static string get_driver_filename(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_driver_filename(session.opaque_ref, _sm);
else
return session.proxy.sm_get_driver_filename(session.opaque_ref, _sm ?? "").parse();
}
/// <summary>
/// Get the required_cluster_stack field of the given SM.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
public static string[] get_required_cluster_stack(Session session, string _sm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_required_cluster_stack(session.opaque_ref, _sm);
else
return (string [])session.proxy.sm_get_required_cluster_stack(session.opaque_ref, _sm ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given SM.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _sm, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.sm_set_other_config(session.opaque_ref, _sm, _other_config);
else
session.proxy.sm_set_other_config(session.opaque_ref, _sm ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given SM.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _sm, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.sm_add_to_other_config(session.opaque_ref, _sm, _key, _value);
else
session.proxy.sm_add_to_other_config(session.opaque_ref, _sm ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given SM. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sm">The opaque_ref of the given sm</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _sm, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.sm_remove_from_other_config(session.opaque_ref, _sm, _key);
else
session.proxy.sm_remove_from_other_config(session.opaque_ref, _sm ?? "", _key ?? "").parse();
}
/// <summary>
/// Return a list of all the SMs known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<SM>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_all(session.opaque_ref);
else
return XenRef<SM>.Create(session.proxy.sm_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the SM Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<SM>, SM> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sm_get_all_records(session.opaque_ref);
else
return XenRef<SM>.Create<Proxy_SM>(session.proxy.sm_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// SR.type
/// </summary>
public virtual string type
{
get { return _type; }
set
{
if (!Helper.AreEqual(value, _type))
{
_type = value;
Changed = true;
NotifyPropertyChanged("type");
}
}
}
private string _type = "";
/// <summary>
/// Vendor who created this plugin
/// </summary>
public virtual string vendor
{
get { return _vendor; }
set
{
if (!Helper.AreEqual(value, _vendor))
{
_vendor = value;
Changed = true;
NotifyPropertyChanged("vendor");
}
}
}
private string _vendor = "";
/// <summary>
/// Entity which owns the copyright of this plugin
/// </summary>
public virtual string copyright
{
get { return _copyright; }
set
{
if (!Helper.AreEqual(value, _copyright))
{
_copyright = value;
Changed = true;
NotifyPropertyChanged("copyright");
}
}
}
private string _copyright = "";
/// <summary>
/// Version of the plugin
/// </summary>
public virtual string version
{
get { return _version; }
set
{
if (!Helper.AreEqual(value, _version))
{
_version = value;
Changed = true;
NotifyPropertyChanged("version");
}
}
}
private string _version = "";
/// <summary>
/// Minimum SM API version required on the server
/// </summary>
public virtual string required_api_version
{
get { return _required_api_version; }
set
{
if (!Helper.AreEqual(value, _required_api_version))
{
_required_api_version = value;
Changed = true;
NotifyPropertyChanged("required_api_version");
}
}
}
private string _required_api_version = "";
/// <summary>
/// names and descriptions of device config keys
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> configuration
{
get { return _configuration; }
set
{
if (!Helper.AreEqual(value, _configuration))
{
_configuration = value;
Changed = true;
NotifyPropertyChanged("configuration");
}
}
}
private Dictionary<string, string> _configuration = new Dictionary<string, string>() {};
/// <summary>
/// capabilities of the SM plugin
/// </summary>
public virtual string[] capabilities
{
get { return _capabilities; }
set
{
if (!Helper.AreEqual(value, _capabilities))
{
_capabilities = value;
Changed = true;
NotifyPropertyChanged("capabilities");
}
}
}
private string[] _capabilities = {};
/// <summary>
/// capabilities of the SM plugin, with capability version numbers
/// First published in XenServer 6.2.
/// </summary>
public virtual Dictionary<string, long> features
{
get { return _features; }
set
{
if (!Helper.AreEqual(value, _features))
{
_features = value;
Changed = true;
NotifyPropertyChanged("features");
}
}
}
private Dictionary<string, long> _features = new Dictionary<string, long>() {};
/// <summary>
/// additional configuration
/// First published in XenServer 4.1.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
/// <summary>
/// filename of the storage driver
/// First published in XenServer 5.0.
/// </summary>
public virtual string driver_filename
{
get { return _driver_filename; }
set
{
if (!Helper.AreEqual(value, _driver_filename))
{
_driver_filename = value;
Changed = true;
NotifyPropertyChanged("driver_filename");
}
}
}
private string _driver_filename = "";
/// <summary>
/// The storage plugin requires that one of these cluster stacks is configured and running.
/// First published in XenServer 7.0.
/// </summary>
public virtual string[] required_cluster_stack
{
get { return _required_cluster_stack; }
set
{
if (!Helper.AreEqual(value, _required_cluster_stack))
{
_required_cluster_stack = value;
Changed = true;
NotifyPropertyChanged("required_cluster_stack");
}
}
}
private string[] _required_cluster_stack = {};
}
}
| |
#region Header
/*
* JsonData.cs
* Generic type to hold JSON data (objects, arrays, and so on). This is
* the default type returned by JsonMapper.ToObject().
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
namespace LitJson
{
public class JsonData : IJsonWrapper, IEquatable<JsonData>
{
#region Fields
private IList<JsonData> inst_array;
private bool inst_boolean;
private double inst_double;
private int inst_int;
private long inst_long;
private IDictionary<string, JsonData> inst_object;
private string inst_string;
private string json;
private JsonType type;
// Used to implement the IOrderedDictionary interface
private IList<KeyValuePair<string, JsonData>> object_list;
#endregion
#region Properties
public int Count {
get { return EnsureCollection ().Count; }
}
public bool IsArray {
get { return type == JsonType.Array; }
}
public bool IsBoolean {
get { return type == JsonType.Boolean; }
}
public bool IsDouble {
get { return type == JsonType.Double; }
}
public bool IsInt {
get { return type == JsonType.Int; }
}
public bool IsLong {
get { return type == JsonType.Long; }
}
public bool IsObject {
get { return type == JsonType.Object; }
}
public bool IsString {
get { return type == JsonType.String; }
}
#endregion
#region ICollection Properties
int ICollection.Count {
get {
return Count;
}
}
bool ICollection.IsSynchronized {
get {
return EnsureCollection ().IsSynchronized;
}
}
object ICollection.SyncRoot {
get {
return EnsureCollection ().SyncRoot;
}
}
#endregion
#region IDictionary Properties
bool IDictionary.IsFixedSize {
get {
return EnsureDictionary ().IsFixedSize;
}
}
bool IDictionary.IsReadOnly {
get {
return EnsureDictionary ().IsReadOnly;
}
}
ICollection IDictionary.Keys {
get {
EnsureDictionary ();
IList<string> keys = new List<string> ();
foreach (KeyValuePair<string, JsonData> entry in
object_list) {
keys.Add (entry.Key);
}
return (ICollection) keys;
}
}
ICollection IDictionary.Values {
get {
EnsureDictionary ();
IList<JsonData> values = new List<JsonData> ();
foreach (KeyValuePair<string, JsonData> entry in
object_list) {
values.Add (entry.Value);
}
return (ICollection) values;
}
}
#endregion
#region IJsonWrapper Properties
bool IJsonWrapper.IsArray {
get { return IsArray; }
}
bool IJsonWrapper.IsBoolean {
get { return IsBoolean; }
}
bool IJsonWrapper.IsDouble {
get { return IsDouble; }
}
bool IJsonWrapper.IsInt {
get { return IsInt; }
}
bool IJsonWrapper.IsLong {
get { return IsLong; }
}
bool IJsonWrapper.IsObject {
get { return IsObject; }
}
bool IJsonWrapper.IsString {
get { return IsString; }
}
#endregion
#region IList Properties
bool IList.IsFixedSize {
get {
return EnsureList ().IsFixedSize;
}
}
bool IList.IsReadOnly {
get {
return EnsureList ().IsReadOnly;
}
}
#endregion
#region IDictionary Indexer
object IDictionary.this[object key] {
get {
return EnsureDictionary ()[key];
}
set {
if (! (key is String))
throw new ArgumentException (
"The key has to be a string");
JsonData data = ToJsonData (value);
this[(string) key] = data;
}
}
#endregion
#region IOrderedDictionary Indexer
object IOrderedDictionary.this[int idx] {
get {
EnsureDictionary ();
return object_list[idx].Value;
}
set {
EnsureDictionary ();
JsonData data = ToJsonData (value);
KeyValuePair<string, JsonData> old_entry = object_list[idx];
inst_object[old_entry.Key] = data;
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (old_entry.Key, data);
object_list[idx] = entry;
}
}
#endregion
#region IList Indexer
object IList.this[int index] {
get {
return EnsureList ()[index];
}
set {
EnsureList ();
JsonData data = ToJsonData (value);
this[index] = data;
}
}
#endregion
#region Public Indexers
public JsonData this[string prop_name] {
get {
EnsureDictionary ();
return inst_object[prop_name];
}
set {
EnsureDictionary ();
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (prop_name, value);
if (inst_object.ContainsKey (prop_name)) {
for (int i = 0; i < object_list.Count; i++) {
if (object_list[i].Key == prop_name) {
object_list[i] = entry;
break;
}
}
} else
object_list.Add (entry);
inst_object[prop_name] = value;
json = null;
}
}
public JsonData this[int index] {
get {
EnsureCollection ();
if (type == JsonType.Array)
return inst_array[index];
return object_list[index].Value;
}
set {
EnsureCollection ();
if (type == JsonType.Array)
inst_array[index] = value;
else {
KeyValuePair<string, JsonData> entry = object_list[index];
KeyValuePair<string, JsonData> new_entry =
new KeyValuePair<string, JsonData> (entry.Key, value);
object_list[index] = new_entry;
inst_object[entry.Key] = value;
}
json = null;
}
}
#endregion
#region Constructors
public JsonData ()
{
}
public JsonData (bool boolean)
{
type = JsonType.Boolean;
inst_boolean = boolean;
}
public JsonData (double number)
{
type = JsonType.Double;
inst_double = number;
}
public JsonData (int number)
{
type = JsonType.Int;
inst_int = number;
}
public JsonData (long number)
{
type = JsonType.Long;
inst_long = number;
}
public JsonData (object obj)
{
if (obj is Boolean) {
type = JsonType.Boolean;
inst_boolean = (bool) obj;
return;
}
if (obj is Double) {
type = JsonType.Double;
inst_double = (double) obj;
return;
}
if (obj is Int32) {
type = JsonType.Int;
inst_int = (int) obj;
return;
}
if (obj is Int64) {
type = JsonType.Long;
inst_long = (long) obj;
return;
}
if (obj is String) {
type = JsonType.String;
inst_string = (string) obj;
return;
}
throw new ArgumentException (
"Unable to wrap the given object with JsonData");
}
public JsonData (string str)
{
type = JsonType.String;
inst_string = str;
}
#endregion
#region Implicit Conversions
public static implicit operator JsonData (Boolean data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Double data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Int32 data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Int64 data)
{
return new JsonData (data);
}
public static implicit operator JsonData (String data)
{
return new JsonData (data);
}
#endregion
#region Explicit Conversions
public static explicit operator Boolean (JsonData data)
{
if (data.type != JsonType.Boolean)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a double");
return data.inst_boolean;
}
public static explicit operator Double (JsonData data)
{
if (data.type != JsonType.Double)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a double");
return data.inst_double;
}
public static explicit operator Int32 (JsonData data)
{
if (data.type != JsonType.Int)
throw new InvalidCastException (
"Instance of JsonData doesn't hold an int");
return data.inst_int;
}
public static explicit operator Int64 (JsonData data)
{
if (data.type != JsonType.Long)
throw new InvalidCastException (
"Instance of JsonData doesn't hold an int");
return data.inst_long;
}
public static explicit operator String (JsonData data)
{
if (data.type != JsonType.String)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a string");
return data.inst_string;
}
#endregion
#region ICollection Methods
void ICollection.CopyTo (Array array, int index)
{
EnsureCollection ().CopyTo (array, index);
}
#endregion
#region IDictionary Methods
void IDictionary.Add (object key, object value)
{
JsonData data = ToJsonData (value);
EnsureDictionary ().Add (key, data);
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> ((string) key, data);
object_list.Add (entry);
json = null;
}
void IDictionary.Clear ()
{
EnsureDictionary ().Clear ();
object_list.Clear ();
json = null;
}
bool IDictionary.Contains (object key)
{
return EnsureDictionary ().Contains (key);
}
IDictionaryEnumerator IDictionary.GetEnumerator ()
{
return ((IOrderedDictionary) this).GetEnumerator ();
}
void IDictionary.Remove (object key)
{
EnsureDictionary ().Remove (key);
for (int i = 0; i < object_list.Count; i++) {
if (object_list[i].Key == (string) key) {
object_list.RemoveAt (i);
break;
}
}
json = null;
}
#endregion
#region IEnumerable Methods
IEnumerator IEnumerable.GetEnumerator ()
{
return EnsureCollection ().GetEnumerator ();
}
#endregion
#region IJsonWrapper Methods
bool IJsonWrapper.GetBoolean ()
{
if (type != JsonType.Boolean)
throw new InvalidOperationException (
"JsonData instance doesn't hold a boolean");
return inst_boolean;
}
double IJsonWrapper.GetDouble ()
{
if (type != JsonType.Double)
throw new InvalidOperationException (
"JsonData instance doesn't hold a double");
return inst_double;
}
int IJsonWrapper.GetInt ()
{
if (type != JsonType.Int)
throw new InvalidOperationException (
"JsonData instance doesn't hold an int");
return inst_int;
}
long IJsonWrapper.GetLong ()
{
if (type != JsonType.Long)
throw new InvalidOperationException (
"JsonData instance doesn't hold a long");
return inst_long;
}
string IJsonWrapper.GetString ()
{
if (type != JsonType.String)
throw new InvalidOperationException (
"JsonData instance doesn't hold a string");
return inst_string;
}
void IJsonWrapper.SetBoolean (bool val)
{
type = JsonType.Boolean;
inst_boolean = val;
json = null;
}
void IJsonWrapper.SetDouble (double val)
{
type = JsonType.Double;
inst_double = val;
json = null;
}
void IJsonWrapper.SetInt (int val)
{
type = JsonType.Int;
inst_int = val;
json = null;
}
void IJsonWrapper.SetLong (long val)
{
type = JsonType.Long;
inst_long = val;
json = null;
}
void IJsonWrapper.SetString (string val)
{
type = JsonType.String;
inst_string = val;
json = null;
}
string IJsonWrapper.ToJson ()
{
return ToJson ();
}
void IJsonWrapper.ToJson (JsonWriter writer)
{
ToJson (writer);
}
#endregion
#region IList Methods
int IList.Add (object value)
{
return Add (value);
}
void IList.Clear ()
{
EnsureList ().Clear ();
json = null;
}
bool IList.Contains (object value)
{
return EnsureList ().Contains (value);
}
int IList.IndexOf (object value)
{
return EnsureList ().IndexOf (value);
}
void IList.Insert (int index, object value)
{
EnsureList ().Insert (index, value);
json = null;
}
void IList.Remove (object value)
{
EnsureList ().Remove (value);
json = null;
}
void IList.RemoveAt (int index)
{
EnsureList ().RemoveAt (index);
json = null;
}
#endregion
#region IOrderedDictionary Methods
IDictionaryEnumerator IOrderedDictionary.GetEnumerator ()
{
EnsureDictionary ();
return new OrderedDictionaryEnumerator (
object_list.GetEnumerator ());
}
void IOrderedDictionary.Insert (int idx, object key, object value)
{
string property = (string) key;
JsonData data = ToJsonData (value);
this[property] = data;
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (property, data);
object_list.Insert (idx, entry);
}
void IOrderedDictionary.RemoveAt (int idx)
{
EnsureDictionary ();
inst_object.Remove (object_list[idx].Key);
object_list.RemoveAt (idx);
}
#endregion
#region Private Methods
private ICollection EnsureCollection ()
{
if (type == JsonType.Array)
return (ICollection) inst_array;
if (type == JsonType.Object)
return (ICollection) inst_object;
throw new InvalidOperationException (
"The JsonData instance has to be initialized first");
}
private IDictionary EnsureDictionary ()
{
if (type == JsonType.Object)
return (IDictionary) inst_object;
if (type != JsonType.None)
throw new InvalidOperationException (
"Instance of JsonData is not a dictionary");
type = JsonType.Object;
inst_object = new Dictionary<string, JsonData> ();
object_list = new List<KeyValuePair<string, JsonData>> ();
return (IDictionary) inst_object;
}
private IList EnsureList ()
{
if (type == JsonType.Array)
return (IList) inst_array;
if (type != JsonType.None)
throw new InvalidOperationException (
"Instance of JsonData is not a list");
type = JsonType.Array;
inst_array = new List<JsonData> ();
return (IList) inst_array;
}
private JsonData ToJsonData (object obj)
{
if (obj == null)
return null;
if (obj is JsonData)
return (JsonData) obj;
return new JsonData (obj);
}
private static void WriteJson (IJsonWrapper obj, JsonWriter writer)
{
if (obj.IsString) {
writer.Write (obj.GetString ());
return;
}
if (obj.IsBoolean) {
writer.Write (obj.GetBoolean ());
return;
}
if (obj.IsDouble) {
writer.Write (obj.GetDouble ());
return;
}
if (obj.IsInt) {
writer.Write (obj.GetInt ());
return;
}
if (obj.IsLong) {
writer.Write (obj.GetLong ());
return;
}
if (obj.IsArray) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteJson ((JsonData) elem, writer);
writer.WriteArrayEnd ();
return;
}
if (obj.IsObject) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in ((IDictionary) obj)) {
writer.WritePropertyName ((string) entry.Key);
WriteJson ((JsonData) entry.Value, writer);
}
writer.WriteObjectEnd ();
return;
}
}
#endregion
public int Add (object value)
{
JsonData data = ToJsonData (value);
json = null;
return EnsureList ().Add (data);
}
public void Clear ()
{
if (IsObject) {
((IDictionary) this).Clear ();
return;
}
if (IsArray) {
((IList) this).Clear ();
return;
}
}
public bool Equals (JsonData x)
{
if (x == null)
return false;
if (x.type != this.type)
return false;
switch (this.type) {
case JsonType.None:
return true;
case JsonType.Object:
return this.inst_object.Equals (x.inst_object);
case JsonType.Array:
return this.inst_array.Equals (x.inst_array);
case JsonType.String:
return this.inst_string.Equals (x.inst_string);
case JsonType.Int:
return this.inst_int.Equals (x.inst_int);
case JsonType.Long:
return this.inst_long.Equals (x.inst_long);
case JsonType.Double:
return this.inst_double.Equals (x.inst_double);
case JsonType.Boolean:
return this.inst_boolean.Equals (x.inst_boolean);
}
return false;
}
public JsonType GetJsonType ()
{
return type;
}
public void SetJsonType (JsonType type)
{
if (this.type == type)
return;
switch (type) {
case JsonType.None:
break;
case JsonType.Object:
inst_object = new Dictionary<string, JsonData> ();
object_list = new List<KeyValuePair<string, JsonData>> ();
break;
case JsonType.Array:
inst_array = new List<JsonData> ();
break;
case JsonType.String:
inst_string = default (String);
break;
case JsonType.Int:
inst_int = default (Int32);
break;
case JsonType.Long:
inst_long = default (Int64);
break;
case JsonType.Double:
inst_double = default (Double);
break;
case JsonType.Boolean:
inst_boolean = default (Boolean);
break;
}
this.type = type;
}
public string ToJson ()
{
if (json != null)
return json;
StringWriter sw = new StringWriter ();
JsonWriter writer = new JsonWriter (sw);
writer.Validate = false;
WriteJson (this, writer);
json = sw.ToString ();
return json;
}
public void ToJson (JsonWriter writer)
{
bool old_validate = writer.Validate;
writer.Validate = false;
WriteJson (this, writer);
writer.Validate = old_validate;
}
public override string ToString ()
{
switch (type) {
case JsonType.Array:
return "JsonData array";
case JsonType.Boolean:
return inst_boolean.ToString ();
case JsonType.Double:
return inst_double.ToString ();
case JsonType.Int:
return inst_int.ToString ();
case JsonType.Long:
return inst_long.ToString ();
case JsonType.Object:
return "JsonData object";
case JsonType.String:
return inst_string;
}
return "Uninitialized JsonData";
}
}
internal class OrderedDictionaryEnumerator : IDictionaryEnumerator
{
IEnumerator<KeyValuePair<string, JsonData>> list_enumerator;
public object Current {
get { return Entry; }
}
public DictionaryEntry Entry {
get {
KeyValuePair<string, JsonData> curr = list_enumerator.Current;
return new DictionaryEntry (curr.Key, curr.Value);
}
}
public object Key {
get { return list_enumerator.Current.Key; }
}
public object Value {
get { return list_enumerator.Current.Value; }
}
public OrderedDictionaryEnumerator (
IEnumerator<KeyValuePair<string, JsonData>> enumerator)
{
list_enumerator = enumerator;
}
public bool MoveNext ()
{
return list_enumerator.MoveNext ();
}
public void Reset ()
{
list_enumerator.Reset ();
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
namespace Anima2D
{
public class InspectorEditor : WindowEditorTool
{
public SpriteMeshCache spriteMeshCache;
protected override string GetHeader() { return "Inspector"; }
public InspectorEditor()
{
windowRect = new Rect(0f, 0f, 250f, 75);
}
Vector2 GetWindowSize()
{
Vector2 size = Vector2.one;
if(spriteMeshCache.mode == SpriteMeshEditorWindow.Mode.Mesh)
{
if(spriteMeshCache.isBound && spriteMeshCache.selection.Count > 0)
{
size = new Vector2(250f,95f);
}else if(spriteMeshCache.selectedBindPose)
{
size = new Vector2(175f,75f);
}else{
size = new Vector2(175f,75f);
}
}else if(spriteMeshCache.mode == SpriteMeshEditorWindow.Mode.Blendshapes)
{
if(spriteMeshCache.selectedBlendshape)
{
size = new Vector2(200f,45f);
}
}
return size;
}
public override void OnWindowGUI(Rect viewRect)
{
windowRect.size = GetWindowSize();
windowRect.position = new Vector2(5f, viewRect.height - windowRect.height - 5f);
base.OnWindowGUI(viewRect);
}
protected override void DoWindow(int windowId)
{
EditorGUILayout.BeginVertical();
if(spriteMeshCache.mode == SpriteMeshEditorWindow.Mode.Mesh)
{
if(spriteMeshCache.isBound && spriteMeshCache.selection.Count > 0)
{
DoVerticesInspector();
}else if(spriteMeshCache.selectedBindPose)
{
DoBindPoseInspector();
}else{
DoSpriteMeshInspector();
}
}else if(spriteMeshCache.mode == SpriteMeshEditorWindow.Mode.Blendshapes)
{
if(spriteMeshCache.selectedBlendshape)
{
DoBlendshapeInspector();
}
}
EditorGUILayout.EndVertical();
EditorGUIUtility.labelWidth = -1;
}
void DoSpriteMeshInspector()
{
if(spriteMeshCache.spriteMesh)
{
EditorGUI.BeginDisabledGroup(true);
EditorGUIUtility.labelWidth = 55f;
EditorGUILayout.ObjectField("Sprite",spriteMeshCache.spriteMesh.sprite,typeof(UnityEngine.Object),false);
EditorGUI.EndDisabledGroup();
EditorGUIUtility.labelWidth = 15f;
EditorGUI.BeginChangeCheck();
Vector2 pivotPoint = EditorGUILayout.Vector2Field("Pivot",spriteMeshCache.pivotPoint);
if(EditorGUI.EndChangeCheck())
{
spriteMeshCache.RegisterUndo("set pivot");
spriteMeshCache.SetPivotPoint(pivotPoint);
}
}
}
void DoBindPoseInspector()
{
EditorGUIUtility.labelWidth = 55f;
EditorGUIUtility.fieldWidth = 55f;
EditorGUI.BeginChangeCheck();
string name = EditorGUILayout.TextField("Name",spriteMeshCache.selectedBindPose.name);
if(EditorGUI.EndChangeCheck())
{
if(string.IsNullOrEmpty(name))
{
name = "New bone";
}
spriteMeshCache.selectedBindPose.name = name;
spriteMeshCache.RegisterUndo("set name");
if(!string.IsNullOrEmpty(spriteMeshCache.selectedBindPose.path))
{
int index = spriteMeshCache.selectedBindPose.path.LastIndexOf("/");
if(index < 0)
{
index = 0;
}else{
index++;
}
foreach(BindInfo bindInfo in spriteMeshCache.bindPoses)
{
if(!string.IsNullOrEmpty(bindInfo.path) && index < bindInfo.path.Length)
{
string pathPrefix = bindInfo.path;
string pathSuffix = "";
if(bindInfo.path.Contains('/'))
{
pathPrefix = bindInfo.path.Substring(0,index);
string tail = bindInfo.path.Substring(index);
int index2 = tail.IndexOf("/");
if(index2 > 0)
{
pathSuffix = tail.Substring(index2);
}
bindInfo.path = pathPrefix + name + pathSuffix;
}else{
bindInfo.path = bindInfo.name;
}
}
}
}
spriteMeshCache.isDirty = true;
}
EditorGUI.BeginChangeCheck();
int zOrder = EditorGUILayout.IntField("Z-Order",spriteMeshCache.selectedBindPose.zOrder);
if(EditorGUI.EndChangeCheck())
{
spriteMeshCache.RegisterUndo("set z-order");
spriteMeshCache.selectedBindPose.zOrder = zOrder;
spriteMeshCache.isDirty = true;
}
EditorGUI.BeginChangeCheck();
Color color = EditorGUILayout.ColorField("Color",spriteMeshCache.selectedBindPose.color);
if(EditorGUI.EndChangeCheck())
{
spriteMeshCache.RegisterUndo("set color");
spriteMeshCache.selectedBindPose.color = color;
spriteMeshCache.isDirty = true;
}
}
bool IsMixedBoneIndex(int weightIndex, out int boneIndex)
{
boneIndex = -1;
float weight = 0f;
spriteMeshCache.GetBoneWeight(spriteMeshCache.nodes[spriteMeshCache.selection.First()]).GetWeight(weightIndex, out boneIndex, out weight);
List<Node> selectedNodes = spriteMeshCache.selectedNodes;
foreach(Node node in selectedNodes)
{
int l_boneIndex = -1;
spriteMeshCache.GetBoneWeight(node).GetWeight(weightIndex, out l_boneIndex, out weight);
if(l_boneIndex != boneIndex)
{
return true;
}
}
return false;
}
void DoVerticesInspector()
{
if(spriteMeshCache.selection.Count > 0)
{
string[] names = spriteMeshCache.GetBoneNames("Unassigned");
BoneWeight boneWeight = BoneWeight.Create();
EditorGUI.BeginChangeCheck();
bool mixedBoneIndex0 = false;
bool mixedBoneIndex1 = false;
bool mixedBoneIndex2 = false;
bool mixedBoneIndex3 = false;
bool changedIndex0 = false;
bool changedIndex1 = false;
bool changedIndex2 = false;
bool changedIndex3 = false;
bool mixedWeight = false;
if(spriteMeshCache.multiselection)
{
mixedWeight = true;
int boneIndex = -1;
mixedBoneIndex0 = IsMixedBoneIndex(0,out boneIndex);
if(!mixedBoneIndex0) boneWeight.boneIndex0 = boneIndex;
mixedBoneIndex1 = IsMixedBoneIndex(1,out boneIndex);
if(!mixedBoneIndex1) boneWeight.boneIndex1 = boneIndex;
mixedBoneIndex2 = IsMixedBoneIndex(2,out boneIndex);
if(!mixedBoneIndex2) boneWeight.boneIndex2 = boneIndex;
mixedBoneIndex3 = IsMixedBoneIndex(3,out boneIndex);
if(!mixedBoneIndex3) boneWeight.boneIndex3 = boneIndex;
}else{
boneWeight = spriteMeshCache.GetBoneWeight(spriteMeshCache.selectedNode);
}
EditorGUI.BeginChangeCheck();
EditorGUI.BeginChangeCheck();
boneWeight = EditorGUIExtra.Weight(boneWeight,0,names,mixedBoneIndex0,mixedWeight);
changedIndex0 = EditorGUI.EndChangeCheck();
EditorGUI.BeginChangeCheck();
boneWeight = EditorGUIExtra.Weight(boneWeight,1,names,mixedBoneIndex1,mixedWeight);
changedIndex1 = EditorGUI.EndChangeCheck();
EditorGUI.BeginChangeCheck();
boneWeight = EditorGUIExtra.Weight(boneWeight,2,names,mixedBoneIndex2,mixedWeight);
changedIndex2 = EditorGUI.EndChangeCheck();
EditorGUI.BeginChangeCheck();
boneWeight = EditorGUIExtra.Weight(boneWeight,3,names,mixedBoneIndex3,mixedWeight);
changedIndex3 = EditorGUI.EndChangeCheck();
if(EditorGUI.EndChangeCheck())
{
spriteMeshCache.RegisterUndo("modify weights");
if(spriteMeshCache.multiselection)
{
List<Node> selectedNodes = spriteMeshCache.selectedNodes;
foreach(Node node in selectedNodes)
{
BoneWeight l_boneWeight = spriteMeshCache.GetBoneWeight(node);
if(!mixedBoneIndex0 || changedIndex0) l_boneWeight.SetWeight(0,boneWeight.boneIndex0,l_boneWeight.weight0);
if(!mixedBoneIndex1 || changedIndex1) l_boneWeight.SetWeight(1,boneWeight.boneIndex1,l_boneWeight.weight1);
if(!mixedBoneIndex2 || changedIndex2) l_boneWeight.SetWeight(2,boneWeight.boneIndex2,l_boneWeight.weight2);
if(!mixedBoneIndex3 || changedIndex3) l_boneWeight.SetWeight(3,boneWeight.boneIndex3,l_boneWeight.weight3);
spriteMeshCache.SetBoneWeight(node,l_boneWeight);
}
}else{
spriteMeshCache.SetBoneWeight(spriteMeshCache.selectedNode,boneWeight);
}
}
EditorGUI.showMixedValue = false;
}
}
void DoBlendshapeInspector()
{
EditorGUIUtility.labelWidth = 65f;
EditorGUIUtility.fieldWidth = 55f;
string name = spriteMeshCache.selectedBlendshape.name;
EditorGUI.BeginChangeCheck();
name = EditorGUILayout.TextField("Name",name);
if(EditorGUI.EndChangeCheck())
{
spriteMeshCache.RegisterUndo("change name");
spriteMeshCache.selectedBlendshape.name = name;
}
}
}
}
| |
// 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.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
#if !FEATURE_SERIALIZATION_UAPAOT
namespace System.Xml.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Xml;
using System.Xml.Serialization.Configuration;
using System.Reflection;
using System.Reflection.Emit;
using System.IO;
using System.Security;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Xml.Extensions;
internal class CodeGenerator
{
internal static BindingFlags InstancePublicBindingFlags = BindingFlags.Instance | BindingFlags.Public;
internal static BindingFlags InstanceBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
internal static BindingFlags StaticBindingFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
internal static MethodAttributes PublicMethodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig;
internal static MethodAttributes PublicOverrideMethodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig;
internal static MethodAttributes ProtectedOverrideMethodAttributes = MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.HideBySig;
internal static MethodAttributes PrivateMethodAttributes = MethodAttributes.Private | MethodAttributes.HideBySig;
private TypeBuilder _typeBuilder;
private MethodBuilder _methodBuilder;
private ILGenerator _ilGen;
private Dictionary<string, ArgBuilder> _argList;
private LocalScope _currentScope;
// Stores a queue of free locals available in the context of the method, keyed by
// type and name of the local
private Dictionary<Tuple<Type, string>, Queue<LocalBuilder>> _freeLocals;
private Stack _blockStack;
private Label _methodEndLabel;
internal CodeGenerator(TypeBuilder typeBuilder)
{
System.Diagnostics.Debug.Assert(typeBuilder != null);
_typeBuilder = typeBuilder;
}
internal static bool IsNullableGenericType(Type type)
{
return type.Name == "Nullable`1";
}
internal static void AssertHasInterface(Type type, Type iType)
{
#if DEBUG
Debug.Assert(iType.IsInterface);
foreach (Type iFace in type.GetInterfaces())
{
if (iFace == iType)
return;
}
Debug.Fail("Interface not found");
#endif
}
internal void BeginMethod(Type returnType, string methodName, Type[] argTypes, string[] argNames, MethodAttributes methodAttributes)
{
_methodBuilder = _typeBuilder.DefineMethod(methodName, methodAttributes, returnType, argTypes);
_ilGen = _methodBuilder.GetILGenerator();
InitILGeneration(argTypes, argNames, (_methodBuilder.Attributes & MethodAttributes.Static) == MethodAttributes.Static);
}
internal void BeginMethod(Type returnType, MethodBuilderInfo methodBuilderInfo, Type[] argTypes, string[] argNames, MethodAttributes methodAttributes)
{
#if DEBUG
methodBuilderInfo.Validate(returnType, argTypes, methodAttributes);
#endif
_methodBuilder = methodBuilderInfo.MethodBuilder;
_ilGen = _methodBuilder.GetILGenerator();
InitILGeneration(argTypes, argNames, (_methodBuilder.Attributes & MethodAttributes.Static) == MethodAttributes.Static);
}
private void InitILGeneration(Type[] argTypes, string[] argNames, bool isStatic)
{
_methodEndLabel = _ilGen.DefineLabel();
this.retLabel = _ilGen.DefineLabel();
_blockStack = new Stack();
_whileStack = new Stack();
_currentScope = new LocalScope();
_freeLocals = new Dictionary<Tuple<Type, string>, Queue<LocalBuilder>>();
_argList = new Dictionary<string, ArgBuilder>();
// this ptr is arg 0 for non static, assuming ref type (not value type)
if (!isStatic)
_argList.Add("this", new ArgBuilder("this", 0, _typeBuilder.BaseType));
for (int i = 0; i < argTypes.Length; i++)
{
ArgBuilder arg = new ArgBuilder(argNames[i], _argList.Count, argTypes[i]);
_argList.Add(arg.Name, arg);
_methodBuilder.DefineParameter(arg.Index, ParameterAttributes.None, arg.Name);
}
}
internal MethodBuilder EndMethod()
{
MarkLabel(_methodEndLabel);
Ret();
MethodBuilder retVal = null;
retVal = _methodBuilder;
_methodBuilder = null;
_ilGen = null;
_freeLocals = null;
_blockStack = null;
_whileStack = null;
_argList = null;
_currentScope = null;
retLocal = null;
return retVal;
}
internal MethodBuilder MethodBuilder
{
get { return _methodBuilder; }
}
internal ArgBuilder GetArg(string name)
{
System.Diagnostics.Debug.Assert(_argList != null && _argList.ContainsKey(name));
return (ArgBuilder)_argList[name];
}
internal LocalBuilder GetLocal(string name)
{
System.Diagnostics.Debug.Assert(_currentScope != null && _currentScope.ContainsKey(name));
return _currentScope[name];
}
internal LocalBuilder retLocal;
internal Label retLabel;
internal LocalBuilder ReturnLocal
{
get
{
if (retLocal == null)
retLocal = DeclareLocal(_methodBuilder.ReturnType, "_ret");
return retLocal;
}
}
internal Label ReturnLabel
{
get { return retLabel; }
}
private Dictionary<Type, LocalBuilder> _tmpLocals = new Dictionary<Type, LocalBuilder>();
internal LocalBuilder GetTempLocal(Type type)
{
LocalBuilder localTmp;
if (!_tmpLocals.TryGetValue(type, out localTmp))
{
localTmp = DeclareLocal(type, "_tmp" + _tmpLocals.Count);
_tmpLocals.Add(type, localTmp);
}
return localTmp;
}
internal Type GetVariableType(object var)
{
if (var is ArgBuilder)
return ((ArgBuilder)var).ArgType;
else if (var is LocalBuilder)
return ((LocalBuilder)var).LocalType;
else
return var.GetType();
}
internal object GetVariable(string name)
{
object var;
if (TryGetVariable(name, out var))
return var;
System.Diagnostics.Debug.Fail("Variable not found");
return null;
}
internal bool TryGetVariable(string name, out object variable)
{
LocalBuilder loc;
if (_currentScope != null && _currentScope.TryGetValue(name, out loc))
{
variable = loc;
return true;
}
ArgBuilder arg;
if (_argList != null && _argList.TryGetValue(name, out arg))
{
variable = arg;
return true;
}
int val;
if (int.TryParse(name, out val))
{
variable = val;
return true;
}
variable = null;
return false;
}
internal void EnterScope()
{
LocalScope newScope = new LocalScope(_currentScope);
_currentScope = newScope;
}
internal void ExitScope()
{
Debug.Assert(_currentScope.parent != null);
_currentScope.AddToFreeLocals(_freeLocals);
_currentScope = _currentScope.parent;
}
private bool TryDequeueLocal(Type type, string name, out LocalBuilder local)
{
// This method can only be called between BeginMethod and EndMethod (i.e.
// while we are emitting code for a method
Debug.Assert(_freeLocals != null);
Queue<LocalBuilder> freeLocalQueue;
Tuple<Type, string> key = new Tuple<Type, string>(type, name);
if (_freeLocals.TryGetValue(key, out freeLocalQueue))
{
local = freeLocalQueue.Dequeue();
// If the queue is empty, remove this key from the dictionary
// of free locals
if (freeLocalQueue.Count == 0)
{
_freeLocals.Remove(key);
}
return true;
}
local = null;
return false;
}
internal LocalBuilder DeclareLocal(Type type, string name)
{
Debug.Assert(!_currentScope.ContainsKey(name));
LocalBuilder local;
if (!TryDequeueLocal(type, name, out local))
{
local = _ilGen.DeclareLocal(type, false);
}
_currentScope[name] = local;
return local;
}
internal LocalBuilder DeclareOrGetLocal(Type type, string name)
{
LocalBuilder local;
if (!_currentScope.TryGetValue(name, out local))
local = DeclareLocal(type, name);
else
Debug.Assert(local.LocalType == type);
return local;
}
internal object For(LocalBuilder local, object start, object end)
{
ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end);
if (forState.Index != null)
{
Load(start);
Stloc(forState.Index);
Br(forState.TestLabel);
}
MarkLabel(forState.BeginLabel);
_blockStack.Push(forState);
return forState;
}
internal void EndFor()
{
object stackTop = _blockStack.Pop();
ForState forState = stackTop as ForState;
Debug.Assert(forState != null);
if (forState.Index != null)
{
Ldloc(forState.Index);
Ldc(1);
Add();
Stloc(forState.Index);
MarkLabel(forState.TestLabel);
Ldloc(forState.Index);
Load(forState.End);
Type varType = GetVariableType(forState.End);
if (varType.IsArray)
{
Ldlen();
}
else
{
#if DEBUG
CodeGenerator.AssertHasInterface(varType, typeof(ICollection));
#endif
MethodInfo ICollection_get_Count = typeof(ICollection).GetMethod(
"get_Count",
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
Call(ICollection_get_Count);
}
Blt(forState.BeginLabel);
}
else
Br(forState.BeginLabel);
}
internal void If()
{
InternalIf(false);
}
internal void IfNot()
{
InternalIf(true);
}
private static OpCode[] s_branchCodes = new OpCode[] {
OpCodes.Bge,
OpCodes.Bne_Un,
OpCodes.Bgt,
OpCodes.Ble,
OpCodes.Beq,
OpCodes.Blt,
};
private OpCode GetBranchCode(Cmp cmp)
{
return s_branchCodes[(int)cmp];
}
internal void If(Cmp cmpOp)
{
IfState ifState = new IfState();
ifState.EndIf = DefineLabel();
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void If(object value1, Cmp cmpOp, object value2)
{
Load(value1);
Load(value2);
If(cmpOp);
}
internal void Else()
{
IfState ifState = PopIfState();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
ifState.ElseBegin = ifState.EndIf;
_blockStack.Push(ifState);
}
internal void EndIf()
{
IfState ifState = PopIfState();
if (!ifState.ElseBegin.Equals(ifState.EndIf))
MarkLabel(ifState.ElseBegin);
MarkLabel(ifState.EndIf);
}
private Stack _leaveLabels = new Stack();
internal void BeginExceptionBlock()
{
_leaveLabels.Push(DefineLabel());
_ilGen.BeginExceptionBlock();
}
internal void BeginCatchBlock(Type exception)
{
_ilGen.BeginCatchBlock(exception);
}
internal void EndExceptionBlock()
{
_ilGen.EndExceptionBlock();
_ilGen.MarkLabel((Label)_leaveLabels.Pop());
}
internal void Leave()
{
_ilGen.Emit(OpCodes.Leave, (Label)_leaveLabels.Peek());
}
internal void Call(MethodInfo methodInfo)
{
Debug.Assert(methodInfo != null);
if (methodInfo.IsVirtual && !methodInfo.DeclaringType.IsValueType)
_ilGen.Emit(OpCodes.Callvirt, methodInfo);
else
_ilGen.Emit(OpCodes.Call, methodInfo);
}
internal void Call(ConstructorInfo ctor)
{
Debug.Assert(ctor != null);
_ilGen.Emit(OpCodes.Call, ctor);
}
internal void New(ConstructorInfo constructorInfo)
{
Debug.Assert(constructorInfo != null);
_ilGen.Emit(OpCodes.Newobj, constructorInfo);
}
internal void InitObj(Type valueType)
{
_ilGen.Emit(OpCodes.Initobj, valueType);
}
internal void NewArray(Type elementType, object len)
{
Load(len);
_ilGen.Emit(OpCodes.Newarr, elementType);
}
internal void LoadArrayElement(object obj, object arrayIndex)
{
Type objType = GetVariableType(obj).GetElementType();
Load(obj);
Load(arrayIndex);
if (IsStruct(objType))
{
Ldelema(objType);
Ldobj(objType);
}
else
Ldelem(objType);
}
internal void StoreArrayElement(object obj, object arrayIndex, object value)
{
Type arrayType = GetVariableType(obj);
if (arrayType == typeof(Array))
{
Load(obj);
Call(typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) }));
}
else
{
Type objType = arrayType.GetElementType();
Load(obj);
Load(arrayIndex);
if (IsStruct(objType))
Ldelema(objType);
Load(value);
ConvertValue(GetVariableType(value), objType);
if (IsStruct(objType))
Stobj(objType);
else
Stelem(objType);
}
}
private static bool IsStruct(Type objType)
{
return objType.IsValueType && !objType.IsPrimitive;
}
internal Type LoadMember(object obj, MemberInfo memberInfo)
{
if (GetVariableType(obj).IsValueType)
LoadAddress(obj);
else
Load(obj);
return LoadMember(memberInfo);
}
private static MethodInfo GetPropertyMethodFromBaseType(PropertyInfo propertyInfo, bool isGetter)
{
// we only invoke this when the propertyInfo does not have a GET or SET method on it
Type currentType = propertyInfo.DeclaringType.BaseType;
PropertyInfo currentProperty;
string propertyName = propertyInfo.Name;
MethodInfo result = null;
while (currentType != null)
{
currentProperty = currentType.GetProperty(propertyName);
if (currentProperty != null)
{
if (isGetter)
{
result = currentProperty.GetMethod;
}
else
{
result = currentProperty.SetMethod;
}
if (result != null)
{
// we found the GetMethod/SetMethod on the type closest to the current declaring type
break;
}
}
// keep looking at the base type like compiler does
currentType = currentType.BaseType;
}
return result;
}
internal Type LoadMember(MemberInfo memberInfo)
{
Type memberType = null;
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
memberType = fieldInfo.FieldType;
if (fieldInfo.IsStatic)
{
_ilGen.Emit(OpCodes.Ldsfld, fieldInfo);
}
else
{
_ilGen.Emit(OpCodes.Ldfld, fieldInfo);
}
}
else
{
System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo);
PropertyInfo property = (PropertyInfo)memberInfo;
memberType = property.PropertyType;
if (property != null)
{
MethodInfo getMethod = property.GetMethod;
if (getMethod == null)
{
getMethod = GetPropertyMethodFromBaseType(property, true);
}
System.Diagnostics.Debug.Assert(getMethod != null);
Call(getMethod);
}
}
return memberType;
}
internal Type LoadMemberAddress(MemberInfo memberInfo)
{
Type memberType = null;
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
memberType = fieldInfo.FieldType;
if (fieldInfo.IsStatic)
{
_ilGen.Emit(OpCodes.Ldsflda, fieldInfo);
}
else
{
_ilGen.Emit(OpCodes.Ldflda, fieldInfo);
}
}
else
{
System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo);
PropertyInfo property = (PropertyInfo)memberInfo;
memberType = property.PropertyType;
if (property != null)
{
MethodInfo getMethod = property.GetMethod;
if (getMethod == null)
{
getMethod = GetPropertyMethodFromBaseType(property, true);
}
System.Diagnostics.Debug.Assert(getMethod != null);
Call(getMethod);
LocalBuilder tmpLoc = GetTempLocal(memberType);
Stloc(tmpLoc);
Ldloca(tmpLoc);
}
}
return memberType;
}
internal void StoreMember(MemberInfo memberInfo)
{
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
if (fieldInfo.IsStatic)
{
_ilGen.Emit(OpCodes.Stsfld, fieldInfo);
}
else
{
_ilGen.Emit(OpCodes.Stfld, fieldInfo);
}
}
else
{
System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo);
PropertyInfo property = (PropertyInfo)memberInfo;
if (property != null)
{
MethodInfo setMethod = property.SetMethod;
if (setMethod == null)
{
setMethod = GetPropertyMethodFromBaseType(property, false);
}
System.Diagnostics.Debug.Assert(setMethod != null);
Call(setMethod);
}
}
}
internal void Load(object obj)
{
if (obj == null)
_ilGen.Emit(OpCodes.Ldnull);
else if (obj is ArgBuilder)
Ldarg((ArgBuilder)obj);
else if (obj is LocalBuilder)
Ldloc((LocalBuilder)obj);
else
Ldc(obj);
}
internal void LoadAddress(object obj)
{
if (obj is ArgBuilder)
LdargAddress((ArgBuilder)obj);
else if (obj is LocalBuilder)
LdlocAddress((LocalBuilder)obj);
else
Load(obj);
}
internal void ConvertAddress(Type source, Type target)
{
InternalConvert(source, target, true);
}
internal void ConvertValue(Type source, Type target)
{
InternalConvert(source, target, false);
}
internal void Castclass(Type target)
{
_ilGen.Emit(OpCodes.Castclass, target);
}
internal void Box(Type type)
{
_ilGen.Emit(OpCodes.Box, type);
}
internal void Unbox(Type type)
{
_ilGen.Emit(OpCodes.Unbox, type);
}
private static OpCode[] s_ldindOpCodes = new OpCode[] {
OpCodes.Nop,//Empty = 0,
OpCodes.Nop,//Object = 1,
OpCodes.Nop,//DBNull = 2,
OpCodes.Ldind_I1,//Boolean = 3,
OpCodes.Ldind_I2,//Char = 4,
OpCodes.Ldind_I1,//SByte = 5,
OpCodes.Ldind_U1,//Byte = 6,
OpCodes.Ldind_I2,//Int16 = 7,
OpCodes.Ldind_U2,//UInt16 = 8,
OpCodes.Ldind_I4,//Int32 = 9,
OpCodes.Ldind_U4,//UInt32 = 10,
OpCodes.Ldind_I8,//Int64 = 11,
OpCodes.Ldind_I8,//UInt64 = 12,
OpCodes.Ldind_R4,//Single = 13,
OpCodes.Ldind_R8,//Double = 14,
OpCodes.Nop,//Decimal = 15,
OpCodes.Nop,//DateTime = 16,
OpCodes.Nop,//17
OpCodes.Ldind_Ref,//String = 18,
};
private OpCode GetLdindOpCode(TypeCode typeCode)
{
return s_ldindOpCodes[(int)typeCode];
}
internal void Ldobj(Type type)
{
OpCode opCode = GetLdindOpCode(type.GetTypeCode());
if (!opCode.Equals(OpCodes.Nop))
{
_ilGen.Emit(opCode);
}
else
{
_ilGen.Emit(OpCodes.Ldobj, type);
}
}
internal void Stobj(Type type)
{
_ilGen.Emit(OpCodes.Stobj, type);
}
internal void Ceq()
{
_ilGen.Emit(OpCodes.Ceq);
}
internal void Clt()
{
_ilGen.Emit(OpCodes.Clt);
}
internal void Cne()
{
Ceq();
Ldc(0);
Ceq();
}
internal void Ble(Label label)
{
_ilGen.Emit(OpCodes.Ble, label);
}
internal void Throw()
{
_ilGen.Emit(OpCodes.Throw);
}
internal void Ldtoken(Type t)
{
_ilGen.Emit(OpCodes.Ldtoken, t);
}
internal void Ldc(object o)
{
Type valueType = o.GetType();
if (o is Type)
{
Ldtoken((Type)o);
Call(typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(RuntimeTypeHandle) }));
}
else if (valueType.IsEnum)
{
Ldc(Convert.ChangeType(o, Enum.GetUnderlyingType(valueType), null));
}
else
{
switch (valueType.GetTypeCode())
{
case TypeCode.Boolean:
Ldc((bool)o);
break;
case TypeCode.Char:
Debug.Fail("Char is not a valid schema primitive and should be treated as int in DataContract");
throw new NotSupportedException(SR.XmlInvalidCharSchemaPrimitive);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
Ldc(Convert.ToInt32(o, CultureInfo.InvariantCulture));
break;
case TypeCode.Int32:
Ldc((int)o);
break;
case TypeCode.UInt32:
Ldc((int)(uint)o);
break;
case TypeCode.UInt64:
Ldc((long)(ulong)o);
break;
case TypeCode.Int64:
Ldc((long)o);
break;
case TypeCode.Single:
Ldc((float)o);
break;
case TypeCode.Double:
Ldc((double)o);
break;
case TypeCode.String:
Ldstr((string)o);
break;
case TypeCode.Decimal:
ConstructorInfo Decimal_ctor = typeof(Decimal).GetConstructor(
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) }
);
int[] bits = decimal.GetBits((decimal)o);
Ldc(bits[0]); // digit
Ldc(bits[1]); // digit
Ldc(bits[2]); // digit
Ldc((bits[3] & 0x80000000) == 0x80000000); // sign
Ldc((byte)((bits[3] >> 16) & 0xFF)); // decimal location
New(Decimal_ctor);
break;
case TypeCode.DateTime:
ConstructorInfo DateTime_ctor = typeof(DateTime).GetConstructor(
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(long) }
);
Ldc(((DateTime)o).Ticks); // ticks
New(DateTime_ctor);
break;
case TypeCode.Object:
case TypeCode.Empty:
case TypeCode.DBNull:
default:
if (valueType == typeof(TimeSpan))
{
ConstructorInfo TimeSpan_ctor = typeof(TimeSpan).GetConstructor(
CodeGenerator.InstanceBindingFlags,
null,
new Type[] { typeof(long) },
null
);
Ldc(((TimeSpan)o).Ticks); // ticks
New(TimeSpan_ctor);
break;
}
else
{
throw new NotSupportedException(SR.Format(SR.UnknownConstantType, valueType.AssemblyQualifiedName));
}
}
}
}
internal void Ldc(bool boolVar)
{
if (boolVar)
{
_ilGen.Emit(OpCodes.Ldc_I4_1);
}
else
{
_ilGen.Emit(OpCodes.Ldc_I4_0);
}
}
internal void Ldc(int intVar)
{
switch (intVar)
{
case -1:
_ilGen.Emit(OpCodes.Ldc_I4_M1);
break;
case 0:
_ilGen.Emit(OpCodes.Ldc_I4_0);
break;
case 1:
_ilGen.Emit(OpCodes.Ldc_I4_1);
break;
case 2:
_ilGen.Emit(OpCodes.Ldc_I4_2);
break;
case 3:
_ilGen.Emit(OpCodes.Ldc_I4_3);
break;
case 4:
_ilGen.Emit(OpCodes.Ldc_I4_4);
break;
case 5:
_ilGen.Emit(OpCodes.Ldc_I4_5);
break;
case 6:
_ilGen.Emit(OpCodes.Ldc_I4_6);
break;
case 7:
_ilGen.Emit(OpCodes.Ldc_I4_7);
break;
case 8:
_ilGen.Emit(OpCodes.Ldc_I4_8);
break;
default:
_ilGen.Emit(OpCodes.Ldc_I4, intVar);
break;
}
}
internal void Ldc(long l)
{
_ilGen.Emit(OpCodes.Ldc_I8, l);
}
internal void Ldc(float f)
{
_ilGen.Emit(OpCodes.Ldc_R4, f);
}
internal void Ldc(double d)
{
_ilGen.Emit(OpCodes.Ldc_R8, d);
}
internal void Ldstr(string strVar)
{
if (strVar == null)
_ilGen.Emit(OpCodes.Ldnull);
else
_ilGen.Emit(OpCodes.Ldstr, strVar);
}
internal void LdlocAddress(LocalBuilder localBuilder)
{
if (localBuilder.LocalType.IsValueType)
Ldloca(localBuilder);
else
Ldloc(localBuilder);
}
internal void Ldloc(LocalBuilder localBuilder)
{
_ilGen.Emit(OpCodes.Ldloc, localBuilder);
}
internal void Ldloc(string name)
{
Debug.Assert(_currentScope.ContainsKey(name));
LocalBuilder local = _currentScope[name];
Ldloc(local);
}
internal void Stloc(Type type, string name)
{
LocalBuilder local = null;
if (!_currentScope.TryGetValue(name, out local))
{
local = DeclareLocal(type, name);
}
Debug.Assert(local.LocalType == type);
Stloc(local);
}
internal void Stloc(LocalBuilder local)
{
_ilGen.Emit(OpCodes.Stloc, local);
}
internal void Ldloc(Type type, string name)
{
Debug.Assert(_currentScope.ContainsKey(name));
LocalBuilder local = _currentScope[name];
Debug.Assert(local.LocalType == type);
Ldloc(local);
}
internal void Ldloca(LocalBuilder localBuilder)
{
_ilGen.Emit(OpCodes.Ldloca, localBuilder);
}
internal void LdargAddress(ArgBuilder argBuilder)
{
if (argBuilder.ArgType.IsValueType)
Ldarga(argBuilder);
else
Ldarg(argBuilder);
}
internal void Ldarg(string arg)
{
Ldarg(GetArg(arg));
}
internal void Ldarg(ArgBuilder arg)
{
Ldarg(arg.Index);
}
internal void Ldarg(int slot)
{
switch (slot)
{
case 0:
_ilGen.Emit(OpCodes.Ldarg_0);
break;
case 1:
_ilGen.Emit(OpCodes.Ldarg_1);
break;
case 2:
_ilGen.Emit(OpCodes.Ldarg_2);
break;
case 3:
_ilGen.Emit(OpCodes.Ldarg_3);
break;
default:
if (slot <= 255)
_ilGen.Emit(OpCodes.Ldarg_S, slot);
else
_ilGen.Emit(OpCodes.Ldarg, slot);
break;
}
}
internal void Ldarga(ArgBuilder argBuilder)
{
Ldarga(argBuilder.Index);
}
internal void Ldarga(int slot)
{
if (slot <= 255)
_ilGen.Emit(OpCodes.Ldarga_S, slot);
else
_ilGen.Emit(OpCodes.Ldarga, slot);
}
internal void Ldlen()
{
_ilGen.Emit(OpCodes.Ldlen);
_ilGen.Emit(OpCodes.Conv_I4);
}
private static OpCode[] s_ldelemOpCodes = new OpCode[] {
OpCodes.Nop,//Empty = 0,
OpCodes.Ldelem_Ref,//Object = 1,
OpCodes.Ldelem_Ref,//DBNull = 2,
OpCodes.Ldelem_I1,//Boolean = 3,
OpCodes.Ldelem_I2,//Char = 4,
OpCodes.Ldelem_I1,//SByte = 5,
OpCodes.Ldelem_U1,//Byte = 6,
OpCodes.Ldelem_I2,//Int16 = 7,
OpCodes.Ldelem_U2,//UInt16 = 8,
OpCodes.Ldelem_I4,//Int32 = 9,
OpCodes.Ldelem_U4,//UInt32 = 10,
OpCodes.Ldelem_I8,//Int64 = 11,
OpCodes.Ldelem_I8,//UInt64 = 12,
OpCodes.Ldelem_R4,//Single = 13,
OpCodes.Ldelem_R8,//Double = 14,
OpCodes.Nop,//Decimal = 15,
OpCodes.Nop,//DateTime = 16,
OpCodes.Nop,//17
OpCodes.Ldelem_Ref,//String = 18,
};
private OpCode GetLdelemOpCode(TypeCode typeCode)
{
return s_ldelemOpCodes[(int)typeCode];
}
internal void Ldelem(Type arrayElementType)
{
if (arrayElementType.IsEnum)
{
Ldelem(Enum.GetUnderlyingType(arrayElementType));
}
else
{
OpCode opCode = GetLdelemOpCode(arrayElementType.GetTypeCode());
Debug.Assert(!opCode.Equals(OpCodes.Nop));
if (opCode.Equals(OpCodes.Nop))
throw new InvalidOperationException(SR.Format(SR.ArrayTypeIsNotSupported, arrayElementType.AssemblyQualifiedName));
_ilGen.Emit(opCode);
}
}
internal void Ldelema(Type arrayElementType)
{
OpCode opCode = OpCodes.Ldelema;
_ilGen.Emit(opCode, arrayElementType);
}
private static OpCode[] s_stelemOpCodes = new OpCode[] {
OpCodes.Nop,//Empty = 0,
OpCodes.Stelem_Ref,//Object = 1,
OpCodes.Stelem_Ref,//DBNull = 2,
OpCodes.Stelem_I1,//Boolean = 3,
OpCodes.Stelem_I2,//Char = 4,
OpCodes.Stelem_I1,//SByte = 5,
OpCodes.Stelem_I1,//Byte = 6,
OpCodes.Stelem_I2,//Int16 = 7,
OpCodes.Stelem_I2,//UInt16 = 8,
OpCodes.Stelem_I4,//Int32 = 9,
OpCodes.Stelem_I4,//UInt32 = 10,
OpCodes.Stelem_I8,//Int64 = 11,
OpCodes.Stelem_I8,//UInt64 = 12,
OpCodes.Stelem_R4,//Single = 13,
OpCodes.Stelem_R8,//Double = 14,
OpCodes.Nop,//Decimal = 15,
OpCodes.Nop,//DateTime = 16,
OpCodes.Nop,//17
OpCodes.Stelem_Ref,//String = 18,
};
private OpCode GetStelemOpCode(TypeCode typeCode)
{
return s_stelemOpCodes[(int)typeCode];
}
internal void Stelem(Type arrayElementType)
{
if (arrayElementType.IsEnum)
Stelem(Enum.GetUnderlyingType(arrayElementType));
else
{
OpCode opCode = GetStelemOpCode(arrayElementType.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw new InvalidOperationException(SR.Format(SR.ArrayTypeIsNotSupported, arrayElementType.AssemblyQualifiedName));
_ilGen.Emit(opCode);
}
}
internal Label DefineLabel()
{
return _ilGen.DefineLabel();
}
internal void MarkLabel(Label label)
{
_ilGen.MarkLabel(label);
}
internal void Nop()
{
_ilGen.Emit(OpCodes.Nop);
}
internal void Add()
{
_ilGen.Emit(OpCodes.Add);
}
internal void Ret()
{
_ilGen.Emit(OpCodes.Ret);
}
internal void Br(Label label)
{
_ilGen.Emit(OpCodes.Br, label);
}
internal void Br_S(Label label)
{
_ilGen.Emit(OpCodes.Br_S, label);
}
internal void Blt(Label label)
{
_ilGen.Emit(OpCodes.Blt, label);
}
internal void Brfalse(Label label)
{
_ilGen.Emit(OpCodes.Brfalse, label);
}
internal void Brtrue(Label label)
{
_ilGen.Emit(OpCodes.Brtrue, label);
}
internal void Pop()
{
_ilGen.Emit(OpCodes.Pop);
}
internal void Dup()
{
_ilGen.Emit(OpCodes.Dup);
}
private void InternalIf(bool negate)
{
IfState ifState = new IfState();
ifState.EndIf = DefineLabel();
ifState.ElseBegin = DefineLabel();
if (negate)
Brtrue(ifState.ElseBegin);
else
Brfalse(ifState.ElseBegin);
_blockStack.Push(ifState);
}
private static OpCode[] s_convOpCodes = new OpCode[] {
OpCodes.Nop,//Empty = 0,
OpCodes.Nop,//Object = 1,
OpCodes.Nop,//DBNull = 2,
OpCodes.Conv_I1,//Boolean = 3,
OpCodes.Conv_I2,//Char = 4,
OpCodes.Conv_I1,//SByte = 5,
OpCodes.Conv_U1,//Byte = 6,
OpCodes.Conv_I2,//Int16 = 7,
OpCodes.Conv_U2,//UInt16 = 8,
OpCodes.Conv_I4,//Int32 = 9,
OpCodes.Conv_U4,//UInt32 = 10,
OpCodes.Conv_I8,//Int64 = 11,
OpCodes.Conv_U8,//UInt64 = 12,
OpCodes.Conv_R4,//Single = 13,
OpCodes.Conv_R8,//Double = 14,
OpCodes.Nop,//Decimal = 15,
OpCodes.Nop,//DateTime = 16,
OpCodes.Nop,//17
OpCodes.Nop,//String = 18,
};
private OpCode GetConvOpCode(TypeCode typeCode)
{
return s_convOpCodes[(int)typeCode];
}
private void InternalConvert(Type source, Type target, bool isAddress)
{
if (target == source)
return;
if (target.IsValueType)
{
if (source.IsValueType)
{
OpCode opCode = GetConvOpCode(target.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
{
throw new CodeGeneratorConversionException(source, target, isAddress, "NoConversionPossibleTo");
}
else
{
_ilGen.Emit(opCode);
}
}
else if (source.IsAssignableFrom(target))
{
Unbox(target);
if (!isAddress)
Ldobj(target);
}
else
{
throw new CodeGeneratorConversionException(source, target, isAddress, "IsNotAssignableFrom");
}
}
else if (target.IsAssignableFrom(source))
{
if (source.IsValueType)
{
if (isAddress)
Ldobj(source);
Box(source);
}
}
else if (source.IsAssignableFrom(target))
{
Castclass(target);
}
else if (target.IsInterface || source.IsInterface)
{
Castclass(target);
}
else
{
throw new CodeGeneratorConversionException(source, target, isAddress, "IsNotAssignableFrom");
}
}
private IfState PopIfState()
{
object stackTop = _blockStack.Pop();
IfState ifState = stackTop as IfState;
Debug.Assert(ifState != null);
return ifState;
}
internal static AssemblyBuilder CreateAssemblyBuilder(string name)
{
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = name;
assemblyName.Version = new Version(1, 0, 0, 0);
return AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
}
internal static ModuleBuilder CreateModuleBuilder(AssemblyBuilder assemblyBuilder, string name)
{
return assemblyBuilder.DefineDynamicModule(name);
}
internal static TypeBuilder CreateTypeBuilder(ModuleBuilder moduleBuilder, string name, TypeAttributes attributes, Type parent, Type[] interfaces)
{
// parent is nullable if no base class
return moduleBuilder.DefineType(TempAssembly.GeneratedAssemblyNamespace + "." + name,
attributes, parent, interfaces);
}
private int _initElseIfStack = -1;
private IfState _elseIfState;
internal void InitElseIf()
{
Debug.Assert(_initElseIfStack == -1);
_elseIfState = (IfState)_blockStack.Pop();
_initElseIfStack = _blockStack.Count;
Br(_elseIfState.EndIf);
MarkLabel(_elseIfState.ElseBegin);
}
private int _initIfStack = -1;
internal void InitIf()
{
Debug.Assert(_initIfStack == -1);
_initIfStack = _blockStack.Count;
}
internal void AndIf(Cmp cmpOp)
{
if (_initIfStack == _blockStack.Count)
{
_initIfStack = -1;
If(cmpOp);
return;
}
if (_initElseIfStack == _blockStack.Count)
{
_initElseIfStack = -1;
_elseIfState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(cmpOp), _elseIfState.ElseBegin);
_blockStack.Push(_elseIfState);
return;
}
Debug.Assert(_initIfStack == -1 && _initElseIfStack == -1);
IfState ifState = (IfState)_blockStack.Peek();
_ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin);
}
internal void AndIf()
{
if (_initIfStack == _blockStack.Count)
{
_initIfStack = -1;
If();
return;
}
if (_initElseIfStack == _blockStack.Count)
{
_initElseIfStack = -1;
_elseIfState.ElseBegin = DefineLabel();
Brfalse(_elseIfState.ElseBegin);
_blockStack.Push(_elseIfState);
return;
}
Debug.Assert(_initIfStack == -1 && _initElseIfStack == -1);
IfState ifState = (IfState)_blockStack.Peek();
Brfalse(ifState.ElseBegin);
}
internal void IsInst(Type type)
{
_ilGen.Emit(OpCodes.Isinst, type);
}
internal void Beq(Label label)
{
_ilGen.Emit(OpCodes.Beq, label);
}
internal void Bne(Label label)
{
_ilGen.Emit(OpCodes.Bne_Un, label);
}
internal void GotoMethodEnd()
{
//limit to only short forward (127 CIL instruction)
//Br_S(this.methodEndLabel);
Br(_methodEndLabel);
}
internal class WhileState
{
public Label StartLabel;
public Label CondLabel;
public Label EndLabel;
public WhileState(CodeGenerator ilg)
{
StartLabel = ilg.DefineLabel();
CondLabel = ilg.DefineLabel();
EndLabel = ilg.DefineLabel();
}
}
// Usage:
// WhileBegin()
// WhileBreak()
// WhileContinue()
// WhileBeginCondition()
// (bool on stack)
// WhileEndCondition()
// WhileEnd()
private Stack _whileStack;
internal void WhileBegin()
{
WhileState whileState = new WhileState(this);
Br(whileState.CondLabel);
MarkLabel(whileState.StartLabel);
_whileStack.Push(whileState);
}
internal void WhileEnd()
{
WhileState whileState = (WhileState)_whileStack.Pop();
MarkLabel(whileState.EndLabel);
}
internal void WhileContinue()
{
WhileState whileState = (WhileState)_whileStack.Peek();
Br(whileState.CondLabel);
}
internal void WhileBeginCondition()
{
WhileState whileState = (WhileState)_whileStack.Peek();
// If there are two MarkLabel ILs consecutively, Labels will converge to one label.
// This could cause the code to look different. We insert Nop here specifically
// that the While label stands out.
Nop();
MarkLabel(whileState.CondLabel);
}
internal void WhileEndCondition()
{
WhileState whileState = (WhileState)_whileStack.Peek();
Brtrue(whileState.StartLabel);
}
}
internal class ArgBuilder
{
internal string Name;
internal int Index;
internal Type ArgType;
internal ArgBuilder(string name, int index, Type argType)
{
this.Name = name;
this.Index = index;
this.ArgType = argType;
}
}
internal class ForState
{
private LocalBuilder _indexVar;
private Label _beginLabel;
private Label _testLabel;
private object _end;
internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end)
{
_indexVar = indexVar;
_beginLabel = beginLabel;
_testLabel = testLabel;
_end = end;
}
internal LocalBuilder Index
{
get
{
return _indexVar;
}
}
internal Label BeginLabel
{
get
{
return _beginLabel;
}
}
internal Label TestLabel
{
get
{
return _testLabel;
}
}
internal object End
{
get
{
return _end;
}
}
}
internal enum Cmp : int
{
LessThan = 0,
EqualTo,
LessThanOrEqualTo,
GreaterThan,
NotEqualTo,
GreaterThanOrEqualTo
}
internal class IfState
{
private Label _elseBegin;
private Label _endIf;
internal Label EndIf
{
get
{
return _endIf;
}
set
{
_endIf = value;
}
}
internal Label ElseBegin
{
get
{
return _elseBegin;
}
set
{
_elseBegin = value;
}
}
}
internal class LocalScope
{
public readonly LocalScope parent;
private readonly Dictionary<string, LocalBuilder> _locals;
// Root scope
public LocalScope()
{
_locals = new Dictionary<string, LocalBuilder>();
}
public LocalScope(LocalScope parent) : this()
{
this.parent = parent;
}
public bool ContainsKey(string key)
{
return _locals.ContainsKey(key) || (parent != null && parent.ContainsKey(key));
}
public bool TryGetValue(string key, out LocalBuilder value)
{
if (_locals.TryGetValue(key, out value))
{
return true;
}
else if (parent != null)
{
return parent.TryGetValue(key, out value);
}
else
{
value = null;
return false;
}
}
public LocalBuilder this[string key]
{
get
{
LocalBuilder value;
TryGetValue(key, out value);
return value;
}
set
{
_locals[key] = value;
}
}
public void AddToFreeLocals(Dictionary<Tuple<Type, string>, Queue<LocalBuilder>> freeLocals)
{
foreach (var item in _locals)
{
Tuple<Type, string> key = new Tuple<Type, string>(item.Value.LocalType, item.Key);
Queue<LocalBuilder> freeLocalQueue;
if (freeLocals.TryGetValue(key, out freeLocalQueue))
{
// Add to end of the queue so that it will be re-used in
// FIFO manner
freeLocalQueue.Enqueue(item.Value);
}
else
{
freeLocalQueue = new Queue<LocalBuilder>();
freeLocalQueue.Enqueue(item.Value);
freeLocals.Add(key, freeLocalQueue);
}
}
}
}
internal class MethodBuilderInfo
{
public readonly MethodBuilder MethodBuilder;
public readonly Type[] ParameterTypes;
public MethodBuilderInfo(MethodBuilder methodBuilder, Type[] parameterTypes)
{
this.MethodBuilder = methodBuilder;
this.ParameterTypes = parameterTypes;
}
public void Validate(Type returnType, Type[] parameterTypes, MethodAttributes attributes)
{
#if DEBUG
Debug.Assert(this.MethodBuilder.ReturnType == returnType);
Debug.Assert(this.MethodBuilder.Attributes == attributes);
Debug.Assert(this.ParameterTypes.Length == parameterTypes.Length);
for (int i = 0; i < parameterTypes.Length; ++i)
{
Debug.Assert(this.ParameterTypes[i] == parameterTypes[i]);
}
#endif
}
}
internal class CodeGeneratorConversionException : Exception
{
private Type _sourceType;
private Type _targetType;
private bool _isAddress;
private string _reason;
public CodeGeneratorConversionException(Type sourceType, Type targetType, bool isAddress, string reason)
: base()
{
_sourceType = sourceType;
_targetType = targetType;
_isAddress = isAddress;
_reason = reason;
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using VersionOne.SDK.APIClient;
using VersionOne.ServerConnector.Entities;
using VersionOne.ServiceHost.ConfigurationTool.DL.Exceptions;
using VersionOne.ServiceHost.ConfigurationTool.Entities;
using VersionOne.ServiceHost.Core.Configuration;
using ListValue = VersionOne.ServiceHost.ConfigurationTool.BZ.ListValue;
using VersionOneSettings = VersionOne.ServiceHost.ConfigurationTool.Entities.VersionOneSettings;
namespace VersionOne.ServiceHost.ConfigurationTool.DL
{
/// <summary>
/// VersionOne interaction handler.
/// </summary>
public class V1Connector
{
public const string TestTypeToken = "Test";
public const string DefectTypeToken = "Defect";
public const string FeatureGroupTypeToken = "Theme";
public const string StoryTypeToken = "Story";
public const string PrimaryWorkitemTypeToken = "PrimaryWorkitem";
private const string TestStatusTypeToken = "TestStatus";
private const string StoryStatusTypeToken = "StoryStatus";
private const string WorkitemPriorityToken = "WorkitemPriority";
private const string ProjectTypeToken = "Scope";
private IServices services;
public bool IsConnected { get; private set; }
private static V1Connector instance;
public static V1Connector Instance
{
get { return instance ?? (instance = new V1Connector()); }
}
private V1Connector() { }
/// <summary>
/// Validate V1 connection
/// </summary>
/// <param name="settings">settings for connection to VersionOne.</param>
/// <returns>true, if validation succeeds; false, otherwise.</returns>
public bool ValidateConnection(VersionOneSettings settings)
{
Connect(settings);
return IsConnected;
}
public bool ValidateIsAccessToken(VersionOneSettings settings)
{
if (settings.AccessToken == null)
{
return false;
}
return true;
}
/// <summary>
/// Create connection to V1 server.
/// </summary>
/// <param name="settings">Connection settings</param>
public void Connect(VersionOneSettings settings)
{
var url = settings.ApplicationUrl;
var accessToken = settings.AccessToken;
try
{
var connector = SDK.APIClient.V1Connector
.WithInstanceUrl(url)
.WithUserAgentHeader("VersionOne.Integration.JIRASync", Assembly.GetEntryAssembly().GetName().Version.ToString());
ICanSetProxyOrEndpointOrGetConnector connectorWithAuth;
connectorWithAuth = connector.WithAccessToken(accessToken);
if (settings.ProxySettings.Enabled)
connectorWithAuth.WithProxy(GetProxy(settings.ProxySettings));
services = new Services(connectorWithAuth.UseOAuthEndpoints().Build());
if (!services.LoggedIn.IsNull)
{
IsConnected = true;
ListPropertyValues = new Dictionary<string, IList<ListValue>>();
}
else
IsConnected = false;
}
catch (Exception)
{
IsConnected = false;
}
}
private ProxyProvider GetProxy(ProxyConnectionSettings proxySettings)
{
if (proxySettings == null || !proxySettings.Enabled)
{
return null;
}
var uri = new Uri(proxySettings.Uri);
return new ProxyProvider(uri, proxySettings.UserName, proxySettings.Password, proxySettings.Domain);
}
/// <summary>
/// Reset connection
/// </summary>
public void ResetConnection()
{
IsConnected = false;
}
// TODO it is known that primary workitem statuses do not have to be unique in VersionOne. In this case, the following method fails.
private IDictionary<string, string> QueryPropertyValues(string propertyName)
{
var res = new Dictionary<string, string>();
var assetType = services.Meta.GetAssetType(propertyName);
var valueDef = assetType.GetAttributeDefinition("Name");
IAttributeDefinition inactiveDef;
var query = new Query(assetType);
query.Selection.Add(valueDef);
if (assetType.TryGetAttributeDefinition("Inactive", out inactiveDef))
{
var filter = new FilterTerm(inactiveDef);
filter.Equal("False");
query.Filter = filter;
}
query.OrderBy.MajorSort(assetType.DefaultOrderBy, OrderBy.Order.Ascending);
foreach (var asset in services.Retrieve(query).Assets)
{
var name = asset.GetAttribute(valueDef).Value.ToString();
res.Add(name, asset.Oid.ToString());
}
return res;
}
/// <summary>
/// Get available test statuses.
/// </summary>
public IDictionary<string, string> GetTestStatuses()
{
return QueryPropertyValues(TestStatusTypeToken);
}
/// <summary>
/// Get primary backlog item statuses.
/// </summary>
public IDictionary<string, string> GetStoryStatuses()
{
return QueryPropertyValues(StoryStatusTypeToken);
}
/// <summary>
/// Get available workitem priorities.
/// </summary>
public IDictionary<string, string> GetWorkitemPriorities()
{
return QueryPropertyValues(WorkitemPriorityToken);
}
/// <summary>
/// Get collection of reference fields for asset type.
/// </summary>
/// <param name="assetTypeToken">AssetType token</param>
public List<string> GetReferenceFieldList(string assetTypeToken)
{
var attributeDefinitionAssetType = services.Meta.GetAssetType("AttributeDefinition");
var nameAttributeDef = attributeDefinitionAssetType.GetAttributeDefinition("Name");
var assetNameAttributeDef = attributeDefinitionAssetType.GetAttributeDefinition("Asset.AssetTypesMeAndDown.Name");
var isCustomAttributeDef = attributeDefinitionAssetType.GetAttributeDefinition("IsCustom");
var attributeTypeAttributeDef = attributeDefinitionAssetType.GetAttributeDefinition("AttributeType");
var assetTypeTerm = new FilterTerm(assetNameAttributeDef);
assetTypeTerm.Equal(assetTypeToken);
var isCustomTerm = new FilterTerm(isCustomAttributeDef);
isCustomTerm.Equal("true");
var attributeTypeTerm = new FilterTerm(attributeTypeAttributeDef);
attributeTypeTerm.Equal("Text");
var result = GetFieldList(new AndFilterTerm(assetTypeTerm, isCustomTerm, attributeTypeTerm), new List<IAttributeDefinition> { nameAttributeDef });
var fieldList = new List<string>();
result.ForEach(x => fieldList.Add(x.GetAttribute(nameAttributeDef).Value.ToString()));
return fieldList;
}
/// <summary>
/// Gets collection of custom list fields for specified asset type.
/// </summary>
/// <param name="assetTypeName">Name of the asset type</param>
/// <param name="fieldType">Field type</param>
/// <returns>collection of custom list fields</returns>
public IList<string> GetCustomFields(string assetTypeName, FieldType fieldType)
{
var attrType = services.Meta.GetAssetType("AttributeDefinition");
var assetType = services.Meta.GetAssetType(assetTypeName);
var isCustomAttributeDef = attrType.GetAttributeDefinition("IsCustom");
var nameAttrDef = attrType.GetAttributeDefinition("Name");
var termType = new FilterTerm(attrType.GetAttributeDefinition("Asset.AssetTypesMeAndDown.Name"));
termType.Equal(assetTypeName);
IAttributeDefinition inactiveDef;
FilterTerm termState = null;
if (assetType.TryGetAttributeDefinition("Inactive", out inactiveDef))
{
termState = new FilterTerm(inactiveDef);
termState.Equal("False");
}
var fieldTypeName = string.Empty;
var attributeTypeName = string.Empty;
switch (fieldType)
{
case FieldType.List:
fieldTypeName = "OneToManyRelationDefinition";
attributeTypeName = "Relation";
break;
case FieldType.Numeric:
fieldTypeName = "SimpleAttributeDefinition";
attributeTypeName = "Numeric";
break;
case FieldType.Text:
fieldTypeName = "SimpleAttributeDefinition";
attributeTypeName = "Text";
break;
}
var assetTypeTerm = new FilterTerm(attrType.GetAttributeDefinition("AssetType"));
assetTypeTerm.Equal(fieldTypeName);
var attributeTypeTerm = new FilterTerm(attrType.GetAttributeDefinition("AttributeType"));
attributeTypeTerm.Equal(attributeTypeName);
var isCustomTerm = new FilterTerm(isCustomAttributeDef);
isCustomTerm.Equal("true");
var result = GetFieldList(new AndFilterTerm(termState, termType, assetTypeTerm, isCustomTerm, attributeTypeTerm),
new List<IAttributeDefinition> { nameAttrDef });
var fieldList = new List<string>();
result.ForEach(x => fieldList.Add(x.GetAttribute(nameAttrDef).Value.ToString()));
return fieldList;
}
private AssetList GetFieldList(IFilterTerm filter, IEnumerable<IAttributeDefinition> selection)
{
var attributeDefinitionAssetType = services.Meta.GetAssetType("AttributeDefinition");
var query = new Query(attributeDefinitionAssetType);
foreach (var attribute in selection)
{
query.Selection.Add(attribute);
}
query.Filter = filter;
return services.Retrieve(query).Assets;
}
/// <summary>
/// Get Source values from VersionOne server
/// </summary>
public List<string> GetSourceList()
{
var assetType = services.Meta.GetAssetType("StorySource");
var nameDef = assetType.GetAttributeDefinition("Name");
IAttributeDefinition inactiveDef;
var query = new Query(assetType);
query.Selection.Add(nameDef);
if (assetType.TryGetAttributeDefinition("Inactive", out inactiveDef))
{
var filter = new FilterTerm(inactiveDef);
filter.Equal("False");
query.Filter = filter;
}
query.OrderBy.MajorSort(assetType.DefaultOrderBy, OrderBy.Order.Ascending);
return services.Retrieve(query).Assets.Select(asset => asset.GetAttribute(nameDef).Value.ToString()).ToList();
}
public List<ProjectWrapper> GetProjectList()
{
var projectType = services.Meta.GetAssetType(ProjectTypeToken);
var scopeQuery = new Query(projectType, projectType.GetAttributeDefinition("Parent"));
var stateTerm = new FilterTerm(projectType.GetAttributeDefinition("AssetState"));
stateTerm.NotEqual(AssetState.Closed);
scopeQuery.Filter = stateTerm;
var nameDef = projectType.GetAttributeDefinition("Name");
scopeQuery.Selection.Add(nameDef);
scopeQuery.OrderBy.MajorSort(projectType.DefaultOrderBy, OrderBy.Order.Ascending);
var result = services.Retrieve(scopeQuery);
var roots = new List<ProjectWrapper>(result.Assets.Count);
foreach (Asset asset in result.Assets)
{
roots.AddRange(GetProjectWrapperList(asset, nameDef, 0));
}
return roots;
}
private IEnumerable<ProjectWrapper> GetProjectWrapperList(Asset asset, IAttributeDefinition attrName, int depth)
{
var list = new List<ProjectWrapper> { new ProjectWrapper(asset, asset.GetAttribute(attrName).Value.ToString(), depth) };
foreach (var child in asset.Children)
{
list.AddRange(GetProjectWrapperList(child, attrName, depth + 1));
}
return list;
}
public virtual IEnumerable<string> GetPrimaryWorkitemTypes()
{
return new[] { "Story", "Defect" };
}
public string GetTypeByFieldName(string fieldSystemName, string assetTypeName)
{
IAssetType assetType;
try
{
assetType = services.Meta.GetAssetType(assetTypeName);
}
catch (MetaException ex)
{
throw new AssetTypeException(string.Format("{0} is unknown asset type.", assetTypeName), ex);
}
IAttributeDefinition attrDef;
try
{
attrDef = assetType.GetAttributeDefinition(fieldSystemName);
}
catch (MetaException ex)
{
throw new FieldNameException(string.Format("{0} is unknown field name for {1}", fieldSystemName, assetTypeName), ex);
}
return attrDef.RelatedAsset == null ? null : attrDef.RelatedAsset.Token;
}
public IDictionary<string, IList<ListValue>> ListPropertyValues { get; private set; }
/// <summary>
/// Gets values for specified asset type name.
/// </summary>
/// <param name="typeName">Asset type name.</param>
/// <returns>List of values for the asset type.</returns>
public IList<ListValue> GetValuesForType(string typeName)
{
if (ListPropertyValues == null)
{
ListPropertyValues = new Dictionary<string, IList<ListValue>>();
}
if (!ListPropertyValues.ContainsKey(typeName))
{
ListPropertyValues.Add(typeName, QueryPropertyOidValues(typeName));
}
return ListPropertyValues[typeName];
}
private IList<ListValue> QueryPropertyOidValues(string propertyName)
{
var res = new List<ListValue>();
IAttributeDefinition nameDef;
var query = GetPropertyValuesQuery(propertyName, out nameDef);
foreach (var asset in services.Retrieve(query).Assets)
{
var name = asset.GetAttribute(nameDef).Value.ToString();
res.Add(new ListValue(name, asset.Oid.Momentless.Token));
}
return res;
}
private Query GetPropertyValuesQuery(string propertyName, out IAttributeDefinition nameDef)
{
IAssetType assetType;
try
{
assetType = services.Meta.GetAssetType(propertyName);
}
catch (MetaException ex)
{
throw new AssetTypeException(string.Format("{0} is unknown asset type.", propertyName), ex);
}
nameDef = assetType.GetAttributeDefinition("Name");
IAttributeDefinition inactiveDef;
var query = new Query(assetType);
query.Selection.Add(nameDef);
if (assetType.TryGetAttributeDefinition("Inactive", out inactiveDef))
{
var filter = new FilterTerm(inactiveDef);
filter.Equal("False");
query.Filter = filter;
}
query.OrderBy.MajorSort(assetType.DefaultOrderBy, OrderBy.Order.Ascending);
return query;
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
namespace System.Net
{
// LazyAsyncResult - Base class for all IAsyncResult classes that want to take advantage of
// lazily-allocated event handles.
internal class LazyAsyncResult : IAsyncResult
{
private const int HighBit = unchecked((int)0x80000000);
private const int ForceAsyncCount = 50;
// This is to avoid user mistakes when they queue another async op from a callback the completes sync.
[ThreadStatic]
private static ThreadContext t_threadContext;
private static ThreadContext CurrentThreadContext
{
get
{
ThreadContext threadContext = t_threadContext;
if (threadContext == null)
{
threadContext = new ThreadContext();
t_threadContext = threadContext;
}
return threadContext;
}
}
private class ThreadContext
{
internal int _nestedIOCount;
}
#if DEBUG
internal object _debugAsyncChain = null; // Optionally used to track chains of async calls.
private bool _protectState; // Used by ContextAwareResult to prevent some calls.
#endif
private object _asyncObject; // Caller's async object.
private object _asyncState; // Caller's state object.
private AsyncCallback _asyncCallback; // Caller's callback method.
private object _result; // Final IO result to be returned byt the End*() method.
private int _errorCode; // Win32 error code for Win32 IO async calls (that want to throw).
private int _intCompleted; // Sign bit indicates synchronous completion if set.
// Remaining bits count the number of InvokeCallbak() calls.
private bool _endCalled; // True if the user called the End*() method.
private bool _userEvent; // True if the event has been (or is about to be) handed to the user
private object _event; // Lazy allocated event to be returned in the IAsyncResult for the client to wait on.
internal LazyAsyncResult(object myObject, object myState, AsyncCallback myCallBack)
{
_asyncObject = myObject;
_asyncState = myState;
_asyncCallback = myCallBack;
_result = DBNull.Value;
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
}
// Interface method to return the original async object.
internal object AsyncObject
{
get
{
return _asyncObject;
}
}
// Interface method to return the caller's state object.
public object AsyncState
{
get
{
return _asyncState;
}
}
protected AsyncCallback AsyncCallback
{
get
{
return _asyncCallback;
}
set
{
_asyncCallback = value;
}
}
// Interface property to return a WaitHandle that can be waited on for I/O completion.
//
// This property implements lazy event creation.
//
// If this is used, the event cannot be disposed because it is under the control of the
// application. Internal should use InternalWaitForCompletion instead - never AsyncWaitHandle.
public WaitHandle AsyncWaitHandle
{
get
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
#if DEBUG
// Can't be called when state is protected.
if (_protectState)
{
throw new InvalidOperationException("get_AsyncWaitHandle called in protected state");
}
#endif
ManualResetEvent asyncEvent;
// Indicates that the user has seen the event; it can't be disposed.
_userEvent = true;
// The user has access to this object. Lock-in CompletedSynchronously.
if (_intCompleted == 0)
{
Interlocked.CompareExchange(ref _intCompleted, HighBit, 0);
}
// Because InternalWaitForCompletion() tries to dispose this event, it's
// possible for _event to become null immediately after being set, but only if
// IsCompleted has become true. Therefore it's possible for this property
// to give different (set) events to different callers when IsCompleted is true.
asyncEvent = (ManualResetEvent)_event;
while (asyncEvent == null)
{
LazilyCreateEvent(out asyncEvent);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, asyncEvent);
return asyncEvent;
}
}
// Returns true if this call created the event.
// May return with a null handle. That means it thought it got one, but it was disposed in the mean time.
private bool LazilyCreateEvent(out ManualResetEvent waitHandle)
{
waitHandle = new ManualResetEvent(false);
try
{
if (Interlocked.CompareExchange(ref _event, waitHandle, null) == null)
{
if (InternalPeekCompleted)
{
waitHandle.Set();
}
return true;
}
else
{
waitHandle.Dispose();
waitHandle = (ManualResetEvent)_event;
// There's a chance here that _event became null. But the only way is if another thread completed
// in InternalWaitForCompletion and disposed it. If we're in InternalWaitForCompletion, we now know
// IsCompleted is set, so we can avoid the wait when waitHandle comes back null. AsyncWaitHandle
// will try again in this case.
return false;
}
}
catch
{
// This should be very rare, but doing this will reduce the chance of deadlock.
_event = null;
if (waitHandle != null)
{
waitHandle.Dispose();
}
throw;
}
}
// This allows ContextAwareResult to not let anyone trigger the CompletedSynchronously tripwire while the context is being captured.
[Conditional("DEBUG")]
protected void DebugProtectState(bool protect)
{
#if DEBUG
_protectState = protect;
#endif
}
// Interface property, returning synchronous completion status.
public bool CompletedSynchronously
{
get
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
#if DEBUG
// Can't be called when state is protected.
if (_protectState)
{
throw new InvalidOperationException("get_CompletedSynchronously called in protected state");
}
#endif
// If this returns greater than zero, it means it was incremented by InvokeCallback before anyone ever saw it.
int result = _intCompleted;
if (result == 0)
{
result = Interlocked.CompareExchange(ref _intCompleted, HighBit, 0);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, result > 0);
return result > 0;
}
}
// Interface property, returning completion status.
public bool IsCompleted
{
get
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
#if DEBUG
// Can't be called when state is protected.
if (_protectState)
{
throw new InvalidOperationException("get_IsCompleted called in protected state");
}
#endif
// Verify low bits to see if it's been incremented. If it hasn't, set the high bit
// to show that it's been looked at.
int result = _intCompleted;
if (result == 0)
{
result = Interlocked.CompareExchange(ref _intCompleted, HighBit, 0);
}
return (result & ~HighBit) != 0;
}
}
// Use to see if something's completed without fixing CompletedSynchronously.
internal bool InternalPeekCompleted
{
get
{
return (_intCompleted & ~HighBit) != 0;
}
}
// Internal property for setting the IO result.
internal object Result
{
get
{
return _result == DBNull.Value ? null : _result;
}
set
{
// Ideally this should never be called, since setting
// the result object really makes sense when the IO completes.
//
// But if the result was set here (as a preemptive error or for some other reason),
// then the "result" parameter passed to InvokeCallback() will be ignored.
// It's an error to call after the result has been completed or with DBNull.
if (value == DBNull.Value)
{
NetEventSource.Fail(this, "Result can't be set to DBNull - it's a special internal value.");
}
if (InternalPeekCompleted)
{
NetEventSource.Fail(this, "Called on completed result.");
}
_result = value;
}
}
internal bool EndCalled
{
get
{
return _endCalled;
}
set
{
_endCalled = value;
}
}
// Internal property for setting the Win32 IO async error code.
internal int ErrorCode
{
get
{
return _errorCode;
}
set
{
_errorCode = value;
}
}
// A method for completing the IO with a result and invoking the user's callback.
// Used by derived classes to pass context into an overridden Complete(). Useful
// for determining the 'winning' thread in case several may simultaneously call
// the equivalent of InvokeCallback().
protected void ProtectedInvokeCallback(object result, IntPtr userToken)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, result, userToken);
// Critical to disallow DBNull here - it could result in a stuck spinlock in WaitForCompletion.
if (result == DBNull.Value)
{
throw new ArgumentNullException(nameof(result));
}
#if DEBUG
// Always safe to ask for the state now.
_protectState = false;
#endif
if ((_intCompleted & ~HighBit) == 0 && (Interlocked.Increment(ref _intCompleted) & ~HighBit) == 1)
{
// DBNull.Value is used to guarantee that the first caller wins,
// even if the result was set to null.
if (_result == DBNull.Value)
{
_result = result;
}
ManualResetEvent asyncEvent = (ManualResetEvent)_event;
if (asyncEvent != null)
{
try
{
asyncEvent.Set();
}
catch (ObjectDisposedException)
{
// Simply ignore this exception - There is apparently a rare race condition
// where the event is disposed before the completion method is called.
}
}
Complete(userToken);
}
}
// Completes the IO with a result and invoking the user's callback.
internal void InvokeCallback(object result)
{
ProtectedInvokeCallback(result, IntPtr.Zero);
}
// Completes the IO without a result and invoking the user's callback.
internal void InvokeCallback()
{
ProtectedInvokeCallback(null, IntPtr.Zero);
}
// NOTE: THIS METHOD MUST NOT BE CALLED DIRECTLY.
//
// This method does the callback's job and is guaranteed to be called exactly once.
// A derived overriding method must call the base class somewhere or the completion is lost.
protected virtual void Complete(IntPtr userToken)
{
bool offloaded = false;
ThreadContext threadContext = CurrentThreadContext;
try
{
++threadContext._nestedIOCount;
if (_asyncCallback != null)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Invoking callback");
if (threadContext._nestedIOCount >= ForceAsyncCount)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "*** OFFLOADED the user callback ****");
Task.Factory.StartNew(
s => WorkerThreadComplete(s),
this,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
offloaded = true;
}
else
{
_asyncCallback(this);
}
}
else
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "No callback to invoke");
}
}
finally
{
--threadContext._nestedIOCount;
// Never call this method unless interlocked _intCompleted check has succeeded (like in this case).
if (!offloaded)
{
Cleanup();
}
}
}
// Only called by the above method.
private static void WorkerThreadComplete(object state)
{
Debug.Assert(state is LazyAsyncResult);
LazyAsyncResult thisPtr = (LazyAsyncResult)state;
try
{
thisPtr._asyncCallback(thisPtr);
}
finally
{
thisPtr.Cleanup();
}
}
// Custom instance cleanup method.
//
// Derived types override this method to release unmanaged resources associated with an IO request.
protected virtual void Cleanup()
{
}
internal object InternalWaitForCompletion()
{
return WaitForCompletion(true);
}
private object WaitForCompletion(bool snap)
{
ManualResetEvent waitHandle = null;
bool createdByMe = false;
bool complete = snap ? IsCompleted : InternalPeekCompleted;
if (!complete)
{
// Not done yet, so wait:
waitHandle = (ManualResetEvent)_event;
if (waitHandle == null)
{
createdByMe = LazilyCreateEvent(out waitHandle);
}
}
if (waitHandle != null)
{
try
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Waiting for completion event {waitHandle}");
waitHandle.WaitOne(Timeout.Infinite);
}
catch (ObjectDisposedException)
{
// This can occur if this method is called from two different threads.
// This possibility is the trade-off for not locking.
}
finally
{
// We also want to dispose the event although we can't unless we did wait on it here.
if (createdByMe && !_userEvent)
{
// Does _userEvent need to be volatile (or _event set via Interlocked) in order
// to avoid giving a user a disposed event?
ManualResetEvent oldEvent = (ManualResetEvent)_event;
_event = null;
if (!_userEvent)
{
oldEvent.Dispose();
}
}
}
}
// A race condition exists because InvokeCallback sets _intCompleted before _result (so that _result
// can benefit from the synchronization of _intCompleted). That means you can get here before _result got
// set (although rarely - once every eight hours of stress). Handle that case with a spin-lock.
SpinWait sw = new SpinWait();
while (_result == DBNull.Value)
{
sw.SpinOnce();
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, _result);
return _result;
}
// A general interface that is called to release unmanaged resources associated with the class.
// It completes the result but doesn't do any of the notifications.
internal void InternalCleanup()
{
if ((_intCompleted & ~HighBit) == 0 && (Interlocked.Increment(ref _intCompleted) & ~HighBit) == 1)
{
// Set no result so that just in case there are waiters, they don't hang in the spin lock.
_result = null;
Cleanup();
}
}
}
}
| |
/*
This file is licensed 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.Xml;
using NUnit.Framework;
using Org.XmlUnit;
using Org.XmlUnit.Builder;
using Org.XmlUnit.Diff;
namespace Org.XmlUnit.Placeholder {
[TestFixture]
public class PlaceholderDifferenceEvaluatorTest {
[Test]
public void Regression_NoPlaceholder_Equal() {
string control = "<elem1><elem11>123</elem11></elem1>";
string test = "<elem1><elem11>123</elem11></elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate)
.Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void Regression_NoPlaceholder_Different() {
string control = "<elem1><elem11>123</elem11></elem1>";
string test = "<elem1><elem11>abc</elem11></elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate)
.Build();
Assert.IsTrue(diff.HasDifferences());
int count = 0;
foreach (Difference difference in diff.Differences) {
count++;
Assert.AreEqual(ComparisonResult.DIFFERENT, difference.Result);
}
Assert.AreEqual(1, count);
}
[Test]
public void Regression_NoPlaceholder_Different_EmptyExpectedElement() {
string control = "<elem1><elem11/></elem1>";
string test = "<elem1><elem11>abc</elem11></elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate)
.Build();
Assert.IsTrue(diff.HasDifferences());
int count = 0;
foreach (Difference difference in diff.Differences) {
count++;
Assert.AreEqual(ComparisonResult.DIFFERENT, difference.Result);
Comparison comparison = difference.Comparison;
if (count == 1) {
string xpath = "/elem1[1]/elem11[1]";
Assert.AreEqual(ComparisonType.CHILD_NODELIST_LENGTH, comparison.Type);
Assert.AreEqual(xpath, comparison.ControlDetails.XPath);
Assert.AreEqual(0, comparison.ControlDetails.Value);
Assert.AreEqual(xpath, comparison.TestDetails.XPath);
Assert.AreEqual(1, comparison.TestDetails.Value);
} else {
Assert.AreEqual(ComparisonType.CHILD_LOOKUP, comparison.Type);
Assert.AreEqual(null, comparison.ControlDetails.XPath);
Assert.AreEqual(null, comparison.ControlDetails.Value);
Assert.AreEqual("/elem1[1]/elem11[1]/text()[1]", comparison.TestDetails.XPath);
Assert.AreEqual(new XmlQualifiedName("#text"), comparison.TestDetails.Value);
}
}
Assert.AreEqual(2, count);
}
[Test]
public void HasIgnorePlaceholder_Equal_NoWhitespaceInPlaceholder() {
string control = "<elem1><elem11>${xmlunit.ignore}</elem11></elem1>";
string test = "<elem1><elem11>abc</elem11></elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate)
.Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void HasIgnorePlaceholder_Equal_NoWhitespaceInPlaceholder_CDATA_Control() {
string control = "<elem1><elem11><![CDATA[${xmlunit.ignore}]]></elem11></elem1>";
string test = "<elem1><elem11>abc</elem11></elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(DifferenceEvaluators.Chain(
DifferenceEvaluators.Default, new PlaceholderDifferenceEvaluator().Evaluate))
.Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void HasIgnorePlaceholder_Equal_NoWhitespaceInPlaceholder_CDATA_TEST() {
string control = "<elem1><elem11>${xmlunit.ignore}</elem11></elem1>";
string test = "<elem1><elem11><![CDATA[abc]]></elem11></elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(DifferenceEvaluators.Chain(
DifferenceEvaluators.Default, new PlaceholderDifferenceEvaluator().Evaluate))
.Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void HasIgnorePlaceholder_CustomDelimiters_Equal_NoWhitespaceInPlaceholder() {
string control = "<elem1><elem11>#{xmlunit.ignore}</elem11></elem1>";
string test = "<elem1><elem11>abc</elem11></elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator("#\\{", null).Evaluate)
.Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void HasIgnorePlaceholder_Equal_StartAndEndWhitespacesInPlaceholder() {
string control = "<elem1><elem11>${ xmlunit.ignore }</elem11></elem1>";
string test = "<elem1><elem11>abc</elem11></elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate)
.Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void HasIgnorePlaceholder_Equal_EmptyActualElement() {
string control = "<elem1><elem11>${xmlunit.ignore}</elem11></elem1>";
string test = "<elem1><elem11/></elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate)
.Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void HasIgnorePlaceholder_Exception_ExclusivelyOccupy() {
string control = "<elem1><elem11> ${xmlunit.ignore}abc</elem11></elem1>";
string test = "<elem1><elem11>abc</elem11></elem1>";
DiffBuilder diffBuilder = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate);
Assert.Throws<XMLUnitException>(() => diffBuilder.Build(), "The placeholder must exclusively occupy the text node.");
}
[Test]
public void Regression_NoPlaceholder_Attributes_Equal() {
string control = "<elem1 attr='123'/>";
string test = "<elem1 attr='123'/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate)
.Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void Regression_NoPlaceholder_Attributes_Different() {
string control = "<elem1 attr='123'/>";
string test = "<elem1 attr='abc'/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsTrue(diff.HasDifferences());
int count = 0;
foreach (Difference difference in diff.Differences) {
count++;
Assert.AreEqual(ComparisonResult.DIFFERENT, difference.Result);
}
Assert.AreEqual(1, count);
}
[Test]
public void Regression_NoPlaceholder_Missing_Attribute() {
string control = "<elem1/>";
string test = "<elem1 attr='abc'/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate)
.Build();
Assert.IsTrue(diff.HasDifferences());
int count = 0;
foreach (Difference difference in diff.Differences) {
count++;
Assert.AreEqual(ComparisonResult.DIFFERENT, difference.Result);
Comparison comparison = difference.Comparison;
if (count == 1) {
string xpath = "/elem1[1]";
Assert.AreEqual(ComparisonType.ELEMENT_NUM_ATTRIBUTES, comparison.Type);
Assert.AreEqual(xpath, comparison.ControlDetails.XPath);
Assert.AreEqual(0, comparison.ControlDetails.Value);
Assert.AreEqual(xpath, comparison.TestDetails.XPath);
Assert.AreEqual(1, comparison.TestDetails.Value);
} else {
Assert.AreEqual(ComparisonType.ATTR_NAME_LOOKUP, comparison.Type);
Assert.AreEqual("/elem1[1]", comparison.ControlDetails.XPath);
Assert.AreEqual(null, comparison.ControlDetails.Value);
Assert.AreEqual("/elem1[1]/@attr", comparison.TestDetails.XPath);
}
}
Assert.AreEqual(2, count);
}
[Test]
public void HasIgnorePlaceholder_Attribute_Equal_NoWhitespaceInPlaceholder() {
string control = "<elem1 attr='${xmlunit.ignore}'/>";
string test = "<elem1 attr='abc'/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate)
.Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void HasIgnorePlaceholder_CustomDelimiters_Attribute_Equal_NoWhitespaceInPlaceholder() {
string control = "<elem1 attr='#{xmlunit.ignore}'/>";
string test = "<elem1 attr='abc'/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator("#\\{", null).Evaluate)
.Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void HasIgnorePlaceholder_Attribute_Equal_StartAndEndWhitespacesInPlaceholder() {
string control = "<elem1 attr='${ xmlunit.ignore }'/>";
string test = "<elem1 attr='abc'/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate)
.Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void HasIgnorePlaceholder_Attribute_Equal_MissingActualAttribute() {
string control = "<elem1 attr='${xmlunit.ignore}'/>";
string test = "<elem1/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate)
.Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void MissingAttributeWithMoreThanOneAttribute() {
string control = "<elem1 attr='${xmlunit.ignore}' a='b'/>";
string test = "<elem1 a='b'/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate)
.Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void MissingAttributeWithMoreThanOneIgnore() {
string control = "<elem1 attr='${xmlunit.ignore}' a='${xmlunit.ignore}'/>";
string test = "<elem1/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate)
.Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void MissingAttributeWithMissingControlAttribute() {
string control = "<elem1 attr='${xmlunit.ignore}' a='${xmlunit.ignore}'/>";
string test = "<elem1 b='a'/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate)
.Build();
Assert.IsTrue(diff.HasDifferences());
}
[Test]
public void HasIgnorePlaceholder_Attribute_Exception_ExclusivelyOccupy() {
string control = "<elem1 attr='${xmlunit.ignore}abc'/>";
string test = "<elem1 attr='abc'/>";
DiffBuilder diffBuilder = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate);
Assert.Throws<XMLUnitException>(() => diffBuilder.Build(), "The placeholder must exclusively occupy the text node.");
}
[Test]
public void HasIsNumberPlaceholder_Attribute_NotNumber() {
string control = "<elem1 attr='${xmlunit.isNumber}'/>";
string test = "<elem1 attr='abc'/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsTrue(diff.HasDifferences());
}
[Test]
public void HasIsNumberPlaceholder_Attribute_IsNumber() {
string control = "<elem1 attr='${xmlunit.isNumber}'/>";
string test = "<elem1 attr='123'/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void HasIsNumberPlaceholder_Element_NotNumber() {
string control = "<elem1>${xmlunit.isNumber}</elem1>";
string test = "<elem1>abc</elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsTrue(diff.HasDifferences());
}
[Test]
public void HasIsNumberPlaceholder_Element_IsNumber() {
string control = "<elem1>${xmlunit.isNumber}</elem1>";
string test = "<elem1>123</elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void HasMatchesRegexPlaceholder_Attribute_Matches() {
string control = "<elem1 attr='${xmlunit.matchesRegex(^\\d+$)}'>qwert</elem1>";
string test = "<elem1 attr='023'>qwert</elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void HasMatchesRegexPlaceholder_Attribute_NotMatches() {
string control = "<elem1 attr='${xmlunit.matchesRegex(^\\d+$)}'>qwert</elem1>";
string test = "<elem1 attr='023asd'>qwert</elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsTrue(diff.HasDifferences());
}
[Test]
public void HasMatchesRegexPlaceholder_Element_Matches() {
string control = "<elem1>${xmlunit.matchesRegex(^\\d+$)}</elem1>";
string test = "<elem1>023</elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void HasMatchesRegexPlaceholder_Element_NotMatches() {
string control = "<elem1>${xmlunit.matchesRegex(^\\d+$)}</elem1>";
string test = "<elem1>23abc</elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsTrue(diff.HasDifferences());
}
[Test]
public void HasIsDateTimePlaceholder_Attribute_NotDateTime() {
string control = "<elem1 attr='${xmlunit.isDateTime}'/>";
string test = "<elem1 attr='abc'/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsTrue(diff.HasDifferences());
}
[Test]
public void HasIsDateTimePlaceholder_Attribute_IsDateTime() {
string control = "<elem1 attr='${xmlunit.isDateTime}'/>";
string test = "<elem1 attr='2020-01-01 15:00:00Z'/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void IsDateTimePlaceholder_Attribute_IsDateTime_CustomFormat() {
string control = "<elem1 attr='${xmlunit.isDateTime(dd.MM.yyyy)}'/>";
string test = "<elem1 attr='05.09.2020'/>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void HasIsDateTimePlaceholder_Element_NotDateTime() {
string control = "<elem1>${xmlunit.isDateTime}</elem1>";
string test = "<elem1>abc</elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsTrue(diff.HasDifferences());
}
[Test]
public void HasIsDateTimePlaceholder_Element_IsDateTime() {
string control = "<elem1>${xmlunit.isDateTime}</elem1>";
string test = "<elem1>2020-01-01 15:00:00Z</elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsFalse(diff.HasDifferences());
}
[Test]
public void IsDateTimePlaceholder_Element_IsDateTime_CustomFormat() {
string control = "<elem1>${xmlunit.isDateTime(dd.MM.yyyy)}</elem1>";
string test = "<elem1>09.05.2020</elem1>";
var diff = DiffBuilder.Compare(control).WithTest(test)
.WithDifferenceEvaluator(new PlaceholderDifferenceEvaluator().Evaluate).Build();
Assert.IsFalse(diff.HasDifferences());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
** Purpose: Read-only wrapper for another generic dictionary.
**
===========================================================*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Collections.ObjectModel
{
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
internal class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
{
private readonly IDictionary<TKey, TValue> m_dictionary;
[NonSerialized]
private Object m_syncRoot;
[NonSerialized]
private KeyCollection m_keys;
[NonSerialized]
private ValueCollection m_values;
public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
throw new ArgumentNullException(nameof(dictionary));
}
Contract.EndContractBlock();
m_dictionary = dictionary;
}
protected IDictionary<TKey, TValue> Dictionary
{
get { return m_dictionary; }
}
public KeyCollection Keys
{
get
{
Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (m_keys == null)
{
m_keys = new KeyCollection(m_dictionary.Keys);
}
return m_keys;
}
}
public ValueCollection Values
{
get
{
Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (m_values == null)
{
m_values = new ValueCollection(m_dictionary.Values);
}
return m_values;
}
}
#region IDictionary<TKey, TValue> Members
public bool ContainsKey(TKey key)
{
return m_dictionary.ContainsKey(key);
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
return Keys;
}
}
public bool TryGetValue(TKey key, out TValue value)
{
return m_dictionary.TryGetValue(key, out value);
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
return Values;
}
}
public TValue this[TKey key]
{
get
{
return m_dictionary[key];
}
}
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get
{
return m_dictionary[key];
}
set
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
#endregion
#region ICollection<KeyValuePair<TKey, TValue>> Members
public int Count
{
get { return m_dictionary.Count; }
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
return m_dictionary.Contains(item);
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
m_dictionary.CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return true; }
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
#endregion
#region IEnumerable<KeyValuePair<TKey, TValue>> Members
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return m_dictionary.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((IEnumerable)m_dictionary).GetEnumerator();
}
#endregion
#region IDictionary Members
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
return key is TKey;
}
void IDictionary.Add(object key, object value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void IDictionary.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
bool IDictionary.Contains(object key)
{
return IsCompatibleKey(key) && ContainsKey((TKey)key);
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
IDictionary d = m_dictionary as IDictionary;
if (d != null)
{
return d.GetEnumerator();
}
return new DictionaryEnumerator(m_dictionary);
}
bool IDictionary.IsFixedSize
{
get { return true; }
}
bool IDictionary.IsReadOnly
{
get { return true; }
}
ICollection IDictionary.Keys
{
get
{
return Keys;
}
}
void IDictionary.Remove(object key)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
ICollection IDictionary.Values
{
get
{
return Values;
}
}
object IDictionary.this[object key]
{
get
{
if (IsCompatibleKey(key))
{
return this[(TKey)key];
}
return null;
}
set
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[];
if (pairs != null)
{
m_dictionary.CopyTo(pairs, index);
}
else
{
DictionaryEntry[] dictEntryArray = array as DictionaryEntry[];
if (dictEntryArray != null)
{
foreach (var item in m_dictionary)
{
dictEntryArray[index++] = new DictionaryEntry(item.Key, item.Value);
}
}
else
{
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
try
{
foreach (var item in m_dictionary)
{
objects[index++] = new KeyValuePair<TKey, TValue>(item.Key, item.Value);
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (m_syncRoot == null)
{
ICollection c = m_dictionary as ICollection;
if (c != null)
{
m_syncRoot = c.SyncRoot;
}
else
{
System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null);
}
}
return m_syncRoot;
}
}
private struct DictionaryEnumerator : IDictionaryEnumerator
{
private readonly IDictionary<TKey, TValue> m_dictionary;
private IEnumerator<KeyValuePair<TKey, TValue>> m_enumerator;
public DictionaryEnumerator(IDictionary<TKey, TValue> dictionary)
{
m_dictionary = dictionary;
m_enumerator = m_dictionary.GetEnumerator();
}
public DictionaryEntry Entry
{
get { return new DictionaryEntry(m_enumerator.Current.Key, m_enumerator.Current.Value); }
}
public object Key
{
get { return m_enumerator.Current.Key; }
}
public object Value
{
get { return m_enumerator.Current.Value; }
}
public object Current
{
get { return Entry; }
}
public bool MoveNext()
{
return m_enumerator.MoveNext();
}
public void Reset()
{
m_enumerator.Reset();
}
}
#endregion
#region IReadOnlyDictionary members
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
{
get
{
return Keys;
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
{
get
{
return Values;
}
}
#endregion IReadOnlyDictionary members
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private readonly ICollection<TKey> m_collection;
[NonSerialized]
private Object m_syncRoot;
internal KeyCollection(ICollection<TKey> collection)
{
if (collection == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
m_collection = collection;
}
#region ICollection<T> Members
void ICollection<TKey>.Add(TKey item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void ICollection<TKey>.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
bool ICollection<TKey>.Contains(TKey item)
{
return m_collection.Contains(item);
}
public void CopyTo(TKey[] array, int arrayIndex)
{
m_collection.CopyTo(array, arrayIndex);
}
public int Count
{
get { return m_collection.Count; }
}
bool ICollection<TKey>.IsReadOnly
{
get { return true; }
}
bool ICollection<TKey>.Remove(TKey item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<TKey> GetEnumerator()
{
return m_collection.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((IEnumerable)m_collection).GetEnumerator();
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TKey>(m_collection, array, index);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (m_syncRoot == null)
{
ICollection c = m_collection as ICollection;
if (c != null)
{
m_syncRoot = c.SyncRoot;
}
else
{
System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null);
}
}
return m_syncRoot;
}
}
#endregion
}
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private readonly ICollection<TValue> m_collection;
[NonSerialized]
private Object m_syncRoot;
internal ValueCollection(ICollection<TValue> collection)
{
if (collection == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
m_collection = collection;
}
#region ICollection<T> Members
void ICollection<TValue>.Add(TValue item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void ICollection<TValue>.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
bool ICollection<TValue>.Contains(TValue item)
{
return m_collection.Contains(item);
}
public void CopyTo(TValue[] array, int arrayIndex)
{
m_collection.CopyTo(array, arrayIndex);
}
public int Count
{
get { return m_collection.Count; }
}
bool ICollection<TValue>.IsReadOnly
{
get { return true; }
}
bool ICollection<TValue>.Remove(TValue item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<TValue> GetEnumerator()
{
return m_collection.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((IEnumerable)m_collection).GetEnumerator();
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TValue>(m_collection, array, index);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (m_syncRoot == null)
{
ICollection c = m_collection as ICollection;
if (c != null)
{
m_syncRoot = c.SyncRoot;
}
else
{
System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null);
}
}
return m_syncRoot;
}
}
#endregion ICollection Members
}
}
// To share code when possible, use a non-generic class to get rid of irrelevant type parameters.
internal static class ReadOnlyDictionaryHelpers
{
#region Helper method for our KeyCollection and ValueCollection
// Abstracted away to avoid redundant implementations.
internal static void CopyToNonGenericICollectionHelper<T>(ICollection<T> collection, Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < collection.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
// Easy out if the ICollection<T> implements the non-generic ICollection
ICollection nonGenericCollection = collection as ICollection;
if (nonGenericCollection != null)
{
nonGenericCollection.CopyTo(array, index);
return;
}
T[] items = array as T[];
if (items != null)
{
collection.CopyTo(items, index);
}
else
{
//
// Catch the obvious case assignment will fail.
// We can found all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType)))
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
//
// We can't cast array of value type to object[], so we don't support
// widening of primitive types here.
//
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
try
{
foreach (var item in collection)
{
objects[index++] = item;
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
#endregion Helper method for our KeyCollection and ValueCollection
}
}
| |
using System;
using System.Runtime.Serialization;
using AutoMapper.UnitTests;
using Shouldly;
using Xunit;
namespace AutoMapper.Tests
{
public class DefaultEnumValueToString : AutoMapperSpecBase
{
Destination _destination;
class Source
{
public ConsoleColor Color { get; set; }
}
class Destination
{
public string Color { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Destination>(new Source());
}
[Fact]
public void Should_map_ok()
{
_destination.Color.ShouldBe("Black");
}
}
public class StringToNullableEnum : AutoMapperSpecBase
{
Destination _destination;
class Source
{
public string Color { get; set; }
}
class Destination
{
public ConsoleColor? Color { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Destination>(new Source { Color = "Red" });
}
[Fact]
public void Should_map_with_underlying_type()
{
_destination.Color.ShouldBe(ConsoleColor.Red);
}
}
public class NullableEnumToString : AutoMapperSpecBase
{
Destination _destination;
class Source
{
public ConsoleColor? Color { get; set; }
}
class Destination
{
public string Color { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.CreateMap<Enum, string>().ConvertUsing((Enum src) => "Test");
});
protected override void Because_of()
{
_destination = Mapper.Map<Destination>(new Source { Color = ConsoleColor.Black });
}
[Fact]
public void Should_map_with_underlying_type()
{
_destination.Color.ShouldBe("Test");
}
}
public class EnumMappingFixture
{
public EnumMappingFixture()
{
Cleanup();
}
public void Cleanup()
{
}
[Fact]
public void ShouldMapSharedEnum()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDto>());
var order = new Order
{
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var dto = mapper.Map<Order, OrderDto>(order);
dto.Status.ShouldBe(Status.InProgress);
}
[Fact]
public void ShouldMapToUnderlyingType() {
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoInt>());
var order = new Order {
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var dto = mapper.Map<Order, OrderDtoInt>(order);
dto.Status.ShouldBe(1);
}
[Fact]
public void ShouldMapToStringType() {
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoString>());
var order = new Order {
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var dto = mapper.Map<Order, OrderDtoString>(order);
dto.Status.ShouldBe("InProgress");
}
[Fact]
public void ShouldMapFromUnderlyingType() {
var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderDtoInt, Order>());
var order = new OrderDtoInt {
Status = 1
};
var mapper = config.CreateMapper();
var dto = mapper.Map<OrderDtoInt, Order>(order);
dto.Status.ShouldBe(Status.InProgress);
}
[Fact]
public void ShouldMapFromStringType() {
var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderDtoString, Order>());
var order = new OrderDtoString {
Status = "InProgress"
};
var mapper = config.CreateMapper();
var dto = mapper.Map<OrderDtoString, Order>(order);
dto.Status.ShouldBe(Status.InProgress);
}
[Fact]
public void ShouldMapEnumByMatchingNames()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>());
var order = new Order
{
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var dto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);
dto.Status.ShouldBe(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapEnumByMatchingValues()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>());
var order = new Order
{
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var dto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);
dto.Status.ShouldBe(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapSharedNullableEnum()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderWithNullableStatus, OrderDtoWithNullableStatus>());
var order = new OrderWithNullableStatus {
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var dto = mapper.Map<OrderWithNullableStatus, OrderDtoWithNullableStatus>(order);
dto.Status.ShouldBe(Status.InProgress);
}
[Fact]
public void ShouldMapNullableEnumByMatchingValues()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>());
var order = new OrderWithNullableStatus {
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var dto = mapper.Map<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>(order);
dto.Status.ShouldBe(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapNullableEnumToNullWhenSourceEnumIsNullAndDestinationWasNotNull()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AllowNullDestinationValues = true;
cfg.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>();
});
var dto = new OrderDtoWithOwnNullableStatus()
{
Status = StatusForDto.Complete
};
var order = new OrderWithNullableStatus
{
Status = null
};
var mapper = config.CreateMapper();
mapper.Map(order, dto);
dto.Status.ShouldBeNull();
}
[Fact]
public void ShouldMapNullableEnumToNullWhenSourceEnumIsNull()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>());
var order = new OrderWithNullableStatus {
Status = null
};
var mapper = config.CreateMapper();
var dto = mapper.Map<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>(order);
dto.Status.ShouldBeNull();
}
[Fact]
public void ShouldMapEnumUsingCustomResolver()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>()
.ForMember(dto => dto.Status, options => options.ResolveUsing<DtoStatusValueResolver>()));
var order = new Order
{
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var mappedDto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);
mappedDto.Status.ShouldBe(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapEnumUsingGenericEnumResolver()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>()
.ForMember(dto => dto.Status, options => options.ResolveUsing<EnumValueResolver<Status, StatusForDto>, Status>(m => m.Status)));
var order = new Order
{
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var mappedDto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);
mappedDto.Status.ShouldBe(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapEnumWithInvalidValue()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>());
var order = new Order
{
Status = 0
};
var mapper = config.CreateMapper();
var dto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);
var expected = (StatusForDto)0;
dto.Status.ShouldBe(expected);
}
public enum Status
{
InProgress = 1,
Complete = 2
}
public enum StatusForDto
{
InProgress = 1,
Complete = 2
}
public class Order
{
public Status Status { get; set; }
}
public class OrderDto
{
public Status Status { get; set; }
}
public class OrderDtoInt {
public int Status { get; set; }
}
public class OrderDtoString {
public string Status { get; set; }
}
public class OrderDtoWithOwnStatus
{
public StatusForDto Status { get; set; }
}
public class OrderWithNullableStatus
{
public Status? Status { get; set; }
}
public class OrderDtoWithNullableStatus
{
public Status? Status { get; set; }
}
public class OrderDtoWithOwnNullableStatus
{
public StatusForDto? Status { get; set; }
}
public class DtoStatusValueResolver : IValueResolver<Order, object, StatusForDto>
{
public StatusForDto Resolve(Order source, object d, StatusForDto dest, ResolutionContext context)
{
return context.Mapper.Map<StatusForDto>(source.Status);
}
}
public class EnumValueResolver<TInputEnum, TOutputEnum> : IMemberValueResolver<object, object, TInputEnum, TOutputEnum>
{
public TOutputEnum Resolve(object s, object d, TInputEnum source, TOutputEnum dest, ResolutionContext context)
{
return ((TOutputEnum)Enum.Parse(typeof(TOutputEnum), Enum.GetName(typeof(TInputEnum), source), false));
}
}
}
public class When_mapping_from_a_null_object_with_an_enum : AutoMapperSpecBase
{
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.AllowNullDestinationValues = false;
cfg.CreateMap<SourceClass, DestinationClass>();
});
public enum EnumValues
{
One, Two, Three
}
public class DestinationClass
{
public EnumValues Values { get; set; }
}
public class SourceClass
{
public EnumValues Values { get; set; }
}
[Fact]
public void Should_set_the_target_enum_to_the_default_value()
{
SourceClass sourceClass = null;
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values.ShouldBe(default(EnumValues));
}
}
public class When_mapping_to_a_nullable_flags_enum : AutoMapperSpecBase
{
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SourceClass, DestinationClass>();
});
[Flags]
public enum EnumValues
{
One, Two = 2, Three = 4
}
public class SourceClass
{
public EnumValues Values { get; set; }
}
public class DestinationClass
{
public EnumValues? Values { get; set; }
}
[Fact]
public void Should_set_the_target_enum_to_the_default_value()
{
var values = EnumValues.Two | EnumValues.Three;
var dest = Mapper.Map<SourceClass, DestinationClass>(new SourceClass { Values = values });
dest.Values.ShouldBe(values);
}
}
public class When_mapping_from_a_null_object_with_a_nullable_enum : AutoMapperSpecBase
{
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.AllowNullDestinationValues = false;
cfg.CreateMap<SourceClass, DestinationClass>();
});
public enum EnumValues
{
One, Two, Three
}
public class DestinationClass
{
public EnumValues Values { get; set; }
}
public class SourceClass
{
public EnumValues? Values { get; set; }
}
[Fact]
public void Should_set_the_target_enum_to_the_default_value()
{
SourceClass sourceClass = null;
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values.ShouldBe(default(EnumValues));
}
}
public class When_mapping_from_a_null_object_with_a_nullable_enum_as_string : AutoMapperSpecBase
{
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SourceClass, DestinationClass>();
});
public enum EnumValues
{
One, Two, Three
}
public class DestinationClass
{
public EnumValues Values1 { get; set; }
public EnumValues? Values2 { get; set; }
public EnumValues Values3 { get; set; }
}
public class SourceClass
{
public string Values1 { get; set; }
public string Values2 { get; set; }
public string Values3 { get; set; }
}
[Fact]
public void Should_set_the_target_enum_to_the_default_value()
{
var sourceClass = new SourceClass();
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values1.ShouldBe(default(EnumValues));
}
[Fact]
public void Should_set_the_target_nullable_to_null()
{
var sourceClass = new SourceClass();
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values2.ShouldBeNull();
}
[Fact]
public void Should_set_the_target_empty_to_null()
{
var sourceClass = new SourceClass
{
Values3 = ""
};
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values3.ShouldBe(default(EnumValues));
}
}
public class When_mapping_a_flags_enum : NonValidatingSpecBase
{
private DestinationFlags _result;
[Flags]
private enum SourceFlags
{
None = 0,
One = 1,
Two = 2,
Four = 4,
Eight = 8
}
[Flags]
private enum DestinationFlags
{
None = 0,
One = 1,
Two = 2,
Four = 4,
Eight = 8
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { });
protected override void Because_of()
{
_result = Mapper.Map<SourceFlags, DestinationFlags>(SourceFlags.One | SourceFlags.Four | SourceFlags.Eight);
}
[Fact]
public void Should_include_all_source_enum_values()
{
_result.ShouldBe(DestinationFlags.One | DestinationFlags.Four | DestinationFlags.Eight);
}
}
public class When_the_target_has_an_enummemberattribute_value : AutoMapperSpecBase
{
public enum EnumWithEnumMemberAttribute
{
Null,
[EnumMember(Value = "Eins")]
One
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { });
[Fact]
public void Should_return_the_enum_from_defined_enummemberattribute_value()
{
var dest = Mapper.Map<string, EnumWithEnumMemberAttribute>("Eins");
dest.ShouldBe(EnumWithEnumMemberAttribute.One);
}
[Fact]
public void Should_return_the_enum_from_undefined_enummemberattribute_value()
{
var dest = Mapper.Map<string, EnumWithEnumMemberAttribute>("Null");
dest.ShouldBe(EnumWithEnumMemberAttribute.Null);
}
[Fact]
public void Should_return_the_nullable_enum_from_defined_enummemberattribute_value()
{
var dest = Mapper.Map<string, EnumWithEnumMemberAttribute?>("Eins");
dest.ShouldBe(EnumWithEnumMemberAttribute.One);
}
[Fact]
public void Should_return_the_enum_from_undefined_enummemberattribute_value_mixedcase()
{
var dest = Mapper.Map<string, EnumWithEnumMemberAttribute>("NuLl");
dest.ShouldBe(EnumWithEnumMemberAttribute.Null);
}
[Fact]
public void Should_return_the_enum_from_defined_enummemberattribute_value_mixedcase()
{
var dest = Mapper.Map<string, EnumWithEnumMemberAttribute?>("eInS");
dest.ShouldBe(EnumWithEnumMemberAttribute.One);
}
[Fact]
public void Should_return_the_nullable_enum_from_null_value()
{
var dest = Mapper.Map<string, EnumWithEnumMemberAttribute?>(null);
dest.ShouldBe(null);
}
[Fact]
public void Should_return_the_nullable_enum_from_undefined_enummemberattribute_value()
{
var dest = Mapper.Map<string, EnumWithEnumMemberAttribute?>("Null");
dest.ShouldBe(EnumWithEnumMemberAttribute.Null);
}
}
public class When_the_source_has_an_enummemberattribute_value : AutoMapperSpecBase
{
public enum EnumWithEnumMemberAttribute
{
Null,
[EnumMember(Value = "Eins")]
One
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { });
[Fact]
public void Should_return_the_defined_enummemberattribute_value()
{
var dest = Mapper.Map<EnumWithEnumMemberAttribute, string>(EnumWithEnumMemberAttribute.One);
dest.ShouldBe("Eins");
}
[Fact]
public void Should_return_the_enum_value()
{
var dest = Mapper.Map<EnumWithEnumMemberAttribute, string>(EnumWithEnumMemberAttribute.Null);
dest.ShouldBe("Null");
}
[Fact]
public void Should_return_the_defined_enummemberattribute_value_nullable()
{
var dest = Mapper.Map<EnumWithEnumMemberAttribute?, string>(EnumWithEnumMemberAttribute.One);
dest.ShouldBe("Eins");
}
[Fact]
public void Should_return_the_enum_value_nullable()
{
var dest = Mapper.Map<EnumWithEnumMemberAttribute?, string>(EnumWithEnumMemberAttribute.Null);
dest.ShouldBe("Null");
}
[Fact]
public void Should_return_null()
{
var dest = Mapper.Map<EnumWithEnumMemberAttribute?, string>(null);
dest.ShouldBe(null);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableArrayExtensionsTest
{
private static readonly ImmutableArray<int> s_emptyDefault = default(ImmutableArray<int>);
private static readonly ImmutableArray<int> s_empty = ImmutableArray.Create<int>();
private static readonly ImmutableArray<int> s_oneElement = ImmutableArray.Create(1);
private static readonly ImmutableArray<int> s_manyElements = ImmutableArray.Create(1, 2, 3);
private static readonly ImmutableArray<GenericParameterHelper> s_oneElementRefType = ImmutableArray.Create(new GenericParameterHelper(1));
private static readonly ImmutableArray<string> s_twoElementRefTypeWithNull = ImmutableArray.Create("1", null);
private static readonly ImmutableArray<int>.Builder s_emptyBuilder = ImmutableArray.Create<int>().ToBuilder();
private static readonly ImmutableArray<int>.Builder s_oneElementBuilder = ImmutableArray.Create<int>(1).ToBuilder();
private static readonly ImmutableArray<int>.Builder s_manyElementsBuilder = ImmutableArray.Create<int>(1, 2, 3).ToBuilder();
[Fact]
public void Select()
{
Assert.Equal(new[] { 4, 5, 6 }, ImmutableArrayExtensions.Select(s_manyElements, n => n + 3));
Assert.Throws<ArgumentNullException>("selector", () => ImmutableArrayExtensions.Select<int, bool>(s_manyElements, null));
}
[Fact]
public void SelectEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Select<int, bool>(s_emptyDefault, null));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Select(s_emptyDefault, n => true));
}
[Fact]
public void SelectEmpty()
{
Assert.Throws<ArgumentNullException>("selector", () => ImmutableArrayExtensions.Select<int, bool>(s_empty, null));
Assert.False(ImmutableArrayExtensions.Select(s_empty, n => true).Any());
}
[Fact]
public void SelectMany()
{
Func<int, IEnumerable<int>> collectionSelector = i => Enumerable.Range(i, 10);
Func<int, int, int> resultSelector = (i, e) => e * 2;
foreach (var arr in new[] { s_empty, s_oneElement, s_manyElements })
{
Assert.Equal(
Enumerable.SelectMany(arr, collectionSelector, resultSelector),
ImmutableArrayExtensions.SelectMany(arr, collectionSelector, resultSelector));
}
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SelectMany<int, int, int>(s_emptyDefault, null, null));
Assert.Throws<ArgumentNullException>("collectionSelector", () =>
ImmutableArrayExtensions.SelectMany<int, int, int>(s_manyElements, null, (i, e) => e));
Assert.Throws<ArgumentNullException>("resultSelector", () =>
ImmutableArrayExtensions.SelectMany<int, int, int>(s_manyElements, i => new[] { i }, null));
}
[Fact]
public void Where()
{
Assert.Equal(new[] { 2, 3 }, ImmutableArrayExtensions.Where(s_manyElements, n => n > 1));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.Where(s_manyElements, null));
}
[Fact]
public void WhereEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Where(s_emptyDefault, null));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Where(s_emptyDefault, n => true));
}
[Fact]
public void WhereEmpty()
{
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.Where(s_empty, null));
Assert.False(ImmutableArrayExtensions.Where(s_empty, n => true).Any());
}
[Fact]
public void Any()
{
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.Any(s_oneElement, null));
Assert.True(ImmutableArrayExtensions.Any(s_oneElement));
Assert.True(ImmutableArrayExtensions.Any(s_manyElements, n => n == 2));
Assert.False(ImmutableArrayExtensions.Any(s_manyElements, n => n == 4));
Assert.True(ImmutableArrayExtensions.Any(s_oneElementBuilder));
}
[Fact]
public void AnyEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(s_emptyDefault, n => true));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(s_emptyDefault, null));
}
[Fact]
public void AnyEmpty()
{
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.Any(s_empty, null));
Assert.False(ImmutableArrayExtensions.Any(s_empty));
Assert.False(ImmutableArrayExtensions.Any(s_empty, n => true));
}
[Fact]
public void All()
{
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.All(s_oneElement, null));
Assert.False(ImmutableArrayExtensions.All(s_manyElements, n => n == 2));
Assert.True(ImmutableArrayExtensions.All(s_manyElements, n => n > 0));
}
[Fact]
public void AllEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.All(s_emptyDefault, n => true));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.All(s_emptyDefault, null));
}
[Fact]
public void AllEmpty()
{
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.All(s_empty, null));
Assert.True(ImmutableArrayExtensions.All(s_empty, n => { throw new ShouldNotBeInvokedException(); })); // predicate should never be invoked.
}
[Fact]
public void SequenceEqual()
{
Assert.Throws<ArgumentNullException>("items", () => ImmutableArrayExtensions.SequenceEqual(s_oneElement, (IEnumerable<int>)null));
foreach (IEqualityComparer<int> comparer in new[] { null, EqualityComparer<int>.Default })
{
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_manyElements, comparer));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, (IEnumerable<int>)s_manyElements.ToArray(), comparer));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, ImmutableArray.Create(s_manyElements.ToArray()), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_oneElement, comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, (IEnumerable<int>)s_oneElement.ToArray(), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, ImmutableArray.Create(s_oneElement.ToArray()), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, (IEnumerable<int>)s_manyElements.Add(1).ToArray(), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), s_manyElements.Add(2).ToArray(), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), (IEnumerable<int>)s_manyElements.Add(2).ToArray(), comparer));
}
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_manyElements, (a, b) => true));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_oneElement, (a, b) => a == b));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), s_manyElements.Add(2), (a, b) => a == b));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), s_manyElements.Add(1), (a, b) => a == b));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, ImmutableArray.Create(s_manyElements.ToArray()), (a, b) => false));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.SequenceEqual(s_oneElement, s_oneElement, (Func<int, int, bool>)null));
}
[Fact]
public void SequenceEqualEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(s_oneElement, s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(s_emptyDefault, s_empty));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(s_emptyDefault, s_emptyDefault));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.SequenceEqual(s_emptyDefault, s_emptyDefault, (Func<int, int, bool>)null));
}
[Fact]
public void SequenceEqualEmpty()
{
Assert.Throws<ArgumentNullException>("items", () => ImmutableArrayExtensions.SequenceEqual(s_empty, (IEnumerable<int>)null));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty.ToArray()));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty, (a, b) => true));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty, (a, b) => false));
}
[Fact]
public void Aggregate()
{
Assert.Throws<ArgumentNullException>("func", () => ImmutableArrayExtensions.Aggregate(s_oneElement, null));
Assert.Throws<ArgumentNullException>("func", () => ImmutableArrayExtensions.Aggregate(s_oneElement, 1, null));
Assert.Throws<ArgumentNullException>("resultSelector", () => ImmutableArrayExtensions.Aggregate<int, int, int>(s_oneElement, 1, null, null));
Assert.Throws<ArgumentNullException>("resultSelector", () => ImmutableArrayExtensions.Aggregate<int, int, int>(s_oneElement, 1, (a, b) => a + b, null));
Assert.Equal(Enumerable.Aggregate(s_manyElements, (a, b) => a * b), ImmutableArrayExtensions.Aggregate(s_manyElements, (a, b) => a * b));
Assert.Equal(Enumerable.Aggregate(s_manyElements, 5, (a, b) => a * b), ImmutableArrayExtensions.Aggregate(s_manyElements, 5, (a, b) => a * b));
Assert.Equal(Enumerable.Aggregate(s_manyElements, 5, (a, b) => a * b, a => -a), ImmutableArrayExtensions.Aggregate(s_manyElements, 5, (a, b) => a * b, a => -a));
}
[Fact]
public void AggregateEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate(s_emptyDefault, (a, b) => a + b));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate(s_emptyDefault, 1, (a, b) => a + b));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate<int, int, int>(s_emptyDefault, 1, (a, b) => a + b, a => a));
}
[Fact]
public void AggregateEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.Aggregate(s_empty, (a, b) => a + b));
Assert.Equal(1, ImmutableArrayExtensions.Aggregate(s_empty, 1, (a, b) => a + b));
Assert.Equal(1, ImmutableArrayExtensions.Aggregate<int, int, int>(s_empty, 1, (a, b) => a + b, a => a));
}
[Fact]
public void ElementAt()
{
// Basis for some assertions that follow
Assert.Throws<IndexOutOfRangeException>(() => Enumerable.ElementAt(s_empty, 0));
Assert.Throws<IndexOutOfRangeException>(() => Enumerable.ElementAt(s_manyElements, -1));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ElementAt(s_emptyDefault, 0));
Assert.Throws<IndexOutOfRangeException>(() => ImmutableArrayExtensions.ElementAt(s_empty, 0));
Assert.Throws<IndexOutOfRangeException>(() => ImmutableArrayExtensions.ElementAt(s_manyElements, -1));
Assert.Equal(1, ImmutableArrayExtensions.ElementAt(s_oneElement, 0));
Assert.Equal(3, ImmutableArrayExtensions.ElementAt(s_manyElements, 2));
}
[Fact]
public void ElementAtOrDefault()
{
Assert.Equal(Enumerable.ElementAtOrDefault(s_manyElements, -1), ImmutableArrayExtensions.ElementAtOrDefault(s_manyElements, -1));
Assert.Equal(Enumerable.ElementAtOrDefault(s_manyElements, 3), ImmutableArrayExtensions.ElementAtOrDefault(s_manyElements, 3));
Assert.Throws<InvalidOperationException>(() => Enumerable.ElementAtOrDefault(s_emptyDefault, 0));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ElementAtOrDefault(s_emptyDefault, 0));
Assert.Equal(0, ImmutableArrayExtensions.ElementAtOrDefault(s_empty, 0));
Assert.Equal(0, ImmutableArrayExtensions.ElementAtOrDefault(s_empty, 1));
Assert.Equal(1, ImmutableArrayExtensions.ElementAtOrDefault(s_oneElement, 0));
Assert.Equal(3, ImmutableArrayExtensions.ElementAtOrDefault(s_manyElements, 2));
}
[Fact]
public void First()
{
Assert.Equal(Enumerable.First(s_oneElement), ImmutableArrayExtensions.First(s_oneElement));
Assert.Equal(Enumerable.First(s_oneElement, i => true), ImmutableArrayExtensions.First(s_oneElement, i => true));
Assert.Equal(Enumerable.First(s_manyElements), ImmutableArrayExtensions.First(s_manyElements));
Assert.Equal(Enumerable.First(s_manyElements, i => true), ImmutableArrayExtensions.First(s_manyElements, i => true));
Assert.Equal(Enumerable.First(s_oneElementBuilder), ImmutableArrayExtensions.First(s_oneElementBuilder));
Assert.Equal(Enumerable.First(s_manyElementsBuilder), ImmutableArrayExtensions.First(s_manyElementsBuilder));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_manyElements, i => false));
}
[Fact]
public void FirstEmpty()
{
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty, n => true));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.First(s_empty, null));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_emptyBuilder));
}
[Fact]
public void FirstEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.First(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.First(s_emptyDefault, n => true));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.First(s_emptyDefault, null));
}
[Fact]
public void FirstOrDefault()
{
Assert.Equal(Enumerable.FirstOrDefault(s_oneElement), ImmutableArrayExtensions.FirstOrDefault(s_oneElement));
Assert.Equal(Enumerable.FirstOrDefault(s_manyElements), ImmutableArrayExtensions.FirstOrDefault(s_manyElements));
foreach (bool result in new[] { true, false })
{
Assert.Equal(Enumerable.FirstOrDefault(s_oneElement, i => result), ImmutableArrayExtensions.FirstOrDefault(s_oneElement, i => result));
Assert.Equal(Enumerable.FirstOrDefault(s_manyElements, i => result), ImmutableArrayExtensions.FirstOrDefault(s_manyElements, i => result));
}
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.FirstOrDefault(s_oneElement, null));
Assert.Equal(Enumerable.FirstOrDefault(s_oneElementBuilder), ImmutableArrayExtensions.FirstOrDefault(s_oneElementBuilder));
Assert.Equal(Enumerable.FirstOrDefault(s_manyElementsBuilder), ImmutableArrayExtensions.FirstOrDefault(s_manyElementsBuilder));
}
[Fact]
public void FirstOrDefaultEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(s_empty));
Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(s_empty, n => true));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.FirstOrDefault(s_empty, null));
Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(s_emptyBuilder));
}
[Fact]
public void FirstOrDefaultEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.FirstOrDefault(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.FirstOrDefault(s_emptyDefault, n => true));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.FirstOrDefault(s_emptyDefault, null));
}
[Fact]
public void Last()
{
Assert.Equal(Enumerable.Last(s_oneElement), ImmutableArrayExtensions.Last(s_oneElement));
Assert.Equal(Enumerable.Last(s_oneElement, i => true), ImmutableArrayExtensions.Last(s_oneElement, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_oneElement, i => false));
Assert.Equal(Enumerable.Last(s_manyElements), ImmutableArrayExtensions.Last(s_manyElements));
Assert.Equal(Enumerable.Last(s_manyElements, i => true), ImmutableArrayExtensions.Last(s_manyElements, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_manyElements, i => false));
Assert.Equal(Enumerable.Last(s_oneElementBuilder), ImmutableArrayExtensions.Last(s_oneElementBuilder));
Assert.Equal(Enumerable.Last(s_manyElementsBuilder), ImmutableArrayExtensions.Last(s_manyElementsBuilder));
}
[Fact]
public void LastEmpty()
{
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_empty, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Last(s_empty, null));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_emptyBuilder));
}
[Fact]
public void LastEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Last(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Last(s_emptyDefault, n => true));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.Last(s_emptyDefault, null));
}
[Fact]
public void LastOrDefault()
{
Assert.Equal(Enumerable.LastOrDefault(s_oneElement), ImmutableArrayExtensions.LastOrDefault(s_oneElement));
Assert.Equal(Enumerable.LastOrDefault(s_manyElements), ImmutableArrayExtensions.LastOrDefault(s_manyElements));
foreach (bool result in new[] { true, false })
{
Assert.Equal(Enumerable.LastOrDefault(s_oneElement, i => result), ImmutableArrayExtensions.LastOrDefault(s_oneElement, i => result));
Assert.Equal(Enumerable.LastOrDefault(s_manyElements, i => result), ImmutableArrayExtensions.LastOrDefault(s_manyElements, i => result));
}
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.LastOrDefault(s_oneElement, null));
Assert.Equal(Enumerable.LastOrDefault(s_oneElementBuilder), ImmutableArrayExtensions.LastOrDefault(s_oneElementBuilder));
Assert.Equal(Enumerable.LastOrDefault(s_manyElementsBuilder), ImmutableArrayExtensions.LastOrDefault(s_manyElementsBuilder));
}
[Fact]
public void LastOrDefaultEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(s_empty));
Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(s_empty, n => true));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.LastOrDefault(s_empty, null));
Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(s_emptyBuilder));
}
[Fact]
public void LastOrDefaultEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.LastOrDefault(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.LastOrDefault(s_emptyDefault, n => true));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.LastOrDefault(s_emptyDefault, null));
}
[Fact]
public void Single()
{
Assert.Equal(Enumerable.Single(s_oneElement), ImmutableArrayExtensions.Single(s_oneElement));
Assert.Equal(Enumerable.Single(s_oneElement), ImmutableArrayExtensions.Single(s_oneElement, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_manyElements));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_manyElements, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_manyElements, i => false));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_oneElement, i => false));
}
[Fact]
public void SingleEmpty()
{
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_empty, n => true));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.Single(s_empty, null));
}
[Fact]
public void SingleEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Single(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Single(s_emptyDefault, n => true));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.Single(s_emptyDefault, null));
}
[Fact]
public void SingleOrDefault()
{
Assert.Equal(Enumerable.SingleOrDefault(s_oneElement), ImmutableArrayExtensions.SingleOrDefault(s_oneElement));
Assert.Equal(Enumerable.SingleOrDefault(s_oneElement), ImmutableArrayExtensions.SingleOrDefault(s_oneElement, i => true));
Assert.Equal(Enumerable.SingleOrDefault(s_oneElement, i => false), ImmutableArrayExtensions.SingleOrDefault(s_oneElement, i => false));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.SingleOrDefault(s_manyElements));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.SingleOrDefault(s_manyElements, i => true));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.SingleOrDefault(s_oneElement, null));
}
[Fact]
public void SingleOrDefaultEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.SingleOrDefault(s_empty));
Assert.Equal(0, ImmutableArrayExtensions.SingleOrDefault(s_empty, n => true));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.SingleOrDefault(s_empty, null));
}
[Fact]
public void SingleOrDefaultEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SingleOrDefault(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SingleOrDefault(s_emptyDefault, n => true));
Assert.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.SingleOrDefault(s_emptyDefault, null));
}
[Fact]
public void ToDictionary()
{
Assert.Throws<ArgumentNullException>("keySelector", () => ImmutableArrayExtensions.ToDictionary(s_manyElements, (Func<int, int>)null));
Assert.Throws<ArgumentNullException>("keySelector", () => ImmutableArrayExtensions.ToDictionary(s_manyElements, (Func<int, int>)null, n => n));
Assert.Throws<ArgumentNullException>("keySelector", () => ImmutableArrayExtensions.ToDictionary(s_manyElements, (Func<int, int>)null, n => n, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>("elementSelector", () => ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n, (Func<int, string>)null));
Assert.Throws<ArgumentNullException>("elementSelector", () => ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n, (Func<int, string>)null, EqualityComparer<int>.Default));
var stringToString = ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n.ToString(), n => (n * 2).ToString());
Assert.Equal(stringToString.Count, s_manyElements.Length);
Assert.Equal("2", stringToString["1"]);
Assert.Equal("4", stringToString["2"]);
Assert.Equal("6", stringToString["3"]);
var stringToInt = ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n.ToString());
Assert.Equal(stringToString.Count, s_manyElements.Length);
Assert.Equal(1, stringToInt["1"]);
Assert.Equal(2, stringToInt["2"]);
Assert.Equal(3, stringToInt["3"]);
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n, n => n));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n, EqualityComparer<int>.Default));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n, n => n, EqualityComparer<int>.Default));
}
[Fact]
public void ToArray()
{
Assert.Equal(0, ImmutableArrayExtensions.ToArray(s_empty).Length);
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToArray(s_emptyDefault));
Assert.Equal(s_manyElements.ToArray(), ImmutableArrayExtensions.ToArray(s_manyElements));
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A music recording (track), usually a single song.
/// </summary>
public class MusicRecording_Core : TypeCore, ICreativeWork
{
public MusicRecording_Core()
{
this._TypeId = 178;
this._Id = "MusicRecording";
this._Schema_Org_Url = "http://schema.org/MusicRecording";
string label = "";
GetLabel(out label, "MusicRecording", typeof(MusicRecording_Core));
this._Label = label;
this._Ancestors = new int[]{266,78};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{78};
this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231,39,71,109,111};
}
/// <summary>
/// The subject matter of the content.
/// </summary>
private About_Core about;
public About_Core About
{
get
{
return about;
}
set
{
about = value;
SetPropertyInstance(about);
}
}
/// <summary>
/// Specifies the Person that is legally accountable for the CreativeWork.
/// </summary>
private AccountablePerson_Core accountablePerson;
public AccountablePerson_Core AccountablePerson
{
get
{
return accountablePerson;
}
set
{
accountablePerson = value;
SetPropertyInstance(accountablePerson);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// A secondary title of the CreativeWork.
/// </summary>
private AlternativeHeadline_Core alternativeHeadline;
public AlternativeHeadline_Core AlternativeHeadline
{
get
{
return alternativeHeadline;
}
set
{
alternativeHeadline = value;
SetPropertyInstance(alternativeHeadline);
}
}
/// <summary>
/// The media objects that encode this creative work. This property is a synonym for encodings.
/// </summary>
private AssociatedMedia_Core associatedMedia;
public AssociatedMedia_Core AssociatedMedia
{
get
{
return associatedMedia;
}
set
{
associatedMedia = value;
SetPropertyInstance(associatedMedia);
}
}
/// <summary>
/// An embedded audio object.
/// </summary>
private Audio_Core audio;
public Audio_Core Audio
{
get
{
return audio;
}
set
{
audio = value;
SetPropertyInstance(audio);
}
}
/// <summary>
/// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely.
/// </summary>
private Author_Core author;
public Author_Core Author
{
get
{
return author;
}
set
{
author = value;
SetPropertyInstance(author);
}
}
/// <summary>
/// Awards won by this person or for this creative work.
/// </summary>
private Awards_Core awards;
public Awards_Core Awards
{
get
{
return awards;
}
set
{
awards = value;
SetPropertyInstance(awards);
}
}
/// <summary>
/// The artist that performed this album or recording.
/// </summary>
private ByArtist_Core byArtist;
public ByArtist_Core ByArtist
{
get
{
return byArtist;
}
set
{
byArtist = value;
SetPropertyInstance(byArtist);
}
}
/// <summary>
/// Comments, typically from users, on this CreativeWork.
/// </summary>
private Comment_Core comment;
public Comment_Core Comment
{
get
{
return comment;
}
set
{
comment = value;
SetPropertyInstance(comment);
}
}
/// <summary>
/// The location of the content.
/// </summary>
private ContentLocation_Core contentLocation;
public ContentLocation_Core ContentLocation
{
get
{
return contentLocation;
}
set
{
contentLocation = value;
SetPropertyInstance(contentLocation);
}
}
/// <summary>
/// Official rating of a piece of content\u2014for example,'MPAA PG-13'.
/// </summary>
private ContentRating_Core contentRating;
public ContentRating_Core ContentRating
{
get
{
return contentRating;
}
set
{
contentRating = value;
SetPropertyInstance(contentRating);
}
}
/// <summary>
/// A secondary contributor to the CreativeWork.
/// </summary>
private Contributor_Core contributor;
public Contributor_Core Contributor
{
get
{
return contributor;
}
set
{
contributor = value;
SetPropertyInstance(contributor);
}
}
/// <summary>
/// The party holding the legal copyright to the CreativeWork.
/// </summary>
private CopyrightHolder_Core copyrightHolder;
public CopyrightHolder_Core CopyrightHolder
{
get
{
return copyrightHolder;
}
set
{
copyrightHolder = value;
SetPropertyInstance(copyrightHolder);
}
}
/// <summary>
/// The year during which the claimed copyright for the CreativeWork was first asserted.
/// </summary>
private CopyrightYear_Core copyrightYear;
public CopyrightYear_Core CopyrightYear
{
get
{
return copyrightYear;
}
set
{
copyrightYear = value;
SetPropertyInstance(copyrightYear);
}
}
/// <summary>
/// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork.
/// </summary>
private Creator_Core creator;
public Creator_Core Creator
{
get
{
return creator;
}
set
{
creator = value;
SetPropertyInstance(creator);
}
}
/// <summary>
/// The date on which the CreativeWork was created.
/// </summary>
private DateCreated_Core dateCreated;
public DateCreated_Core DateCreated
{
get
{
return dateCreated;
}
set
{
dateCreated = value;
SetPropertyInstance(dateCreated);
}
}
/// <summary>
/// The date on which the CreativeWork was most recently modified.
/// </summary>
private DateModified_Core dateModified;
public DateModified_Core DateModified
{
get
{
return dateModified;
}
set
{
dateModified = value;
SetPropertyInstance(dateModified);
}
}
/// <summary>
/// Date of first broadcast/publication.
/// </summary>
private DatePublished_Core datePublished;
public DatePublished_Core DatePublished
{
get
{
return datePublished;
}
set
{
datePublished = value;
SetPropertyInstance(datePublished);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// A link to the page containing the comments of the CreativeWork.
/// </summary>
private DiscussionURL_Core discussionURL;
public DiscussionURL_Core DiscussionURL
{
get
{
return discussionURL;
}
set
{
discussionURL = value;
SetPropertyInstance(discussionURL);
}
}
/// <summary>
/// The duration of the item (movie, audio recording, event, etc.) in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>.
/// </summary>
private Properties.Duration_Core duration;
public Properties.Duration_Core Duration
{
get
{
return duration;
}
set
{
duration = value;
SetPropertyInstance(duration);
}
}
/// <summary>
/// Specifies the Person who edited the CreativeWork.
/// </summary>
private Editor_Core editor;
public Editor_Core Editor
{
get
{
return editor;
}
set
{
editor = value;
SetPropertyInstance(editor);
}
}
/// <summary>
/// The media objects that encode this creative work
/// </summary>
private Encodings_Core encodings;
public Encodings_Core Encodings
{
get
{
return encodings;
}
set
{
encodings = value;
SetPropertyInstance(encodings);
}
}
/// <summary>
/// Genre of the creative work
/// </summary>
private Genre_Core genre;
public Genre_Core Genre
{
get
{
return genre;
}
set
{
genre = value;
SetPropertyInstance(genre);
}
}
/// <summary>
/// Headline of the article
/// </summary>
private Headline_Core headline;
public Headline_Core Headline
{
get
{
return headline;
}
set
{
headline = value;
SetPropertyInstance(headline);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// The album to which this recording belongs.
/// </summary>
private InAlbum_Core inAlbum;
public InAlbum_Core InAlbum
{
get
{
return inAlbum;
}
set
{
inAlbum = value;
SetPropertyInstance(inAlbum);
}
}
/// <summary>
/// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a>
/// </summary>
private InLanguage_Core inLanguage;
public InLanguage_Core InLanguage
{
get
{
return inLanguage;
}
set
{
inLanguage = value;
SetPropertyInstance(inLanguage);
}
}
/// <summary>
/// The playlist to which this recording belongs.
/// </summary>
private InPlaylist_Core inPlaylist;
public InPlaylist_Core InPlaylist
{
get
{
return inPlaylist;
}
set
{
inPlaylist = value;
SetPropertyInstance(inPlaylist);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// Indicates whether this content is family friendly.
/// </summary>
private IsFamilyFriendly_Core isFamilyFriendly;
public IsFamilyFriendly_Core IsFamilyFriendly
{
get
{
return isFamilyFriendly;
}
set
{
isFamilyFriendly = value;
SetPropertyInstance(isFamilyFriendly);
}
}
/// <summary>
/// The keywords/tags used to describe this content.
/// </summary>
private Keywords_Core keywords;
public Keywords_Core Keywords
{
get
{
return keywords;
}
set
{
keywords = value;
SetPropertyInstance(keywords);
}
}
/// <summary>
/// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept.
/// </summary>
private Mentions_Core mentions;
public Mentions_Core Mentions
{
get
{
return mentions;
}
set
{
mentions = value;
SetPropertyInstance(mentions);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.
/// </summary>
private Offers_Core offers;
public Offers_Core Offers
{
get
{
return offers;
}
set
{
offers = value;
SetPropertyInstance(offers);
}
}
/// <summary>
/// Specifies the Person or Organization that distributed the CreativeWork.
/// </summary>
private Provider_Core provider;
public Provider_Core Provider
{
get
{
return provider;
}
set
{
provider = value;
SetPropertyInstance(provider);
}
}
/// <summary>
/// The publisher of the creative work.
/// </summary>
private Publisher_Core publisher;
public Publisher_Core Publisher
{
get
{
return publisher;
}
set
{
publisher = value;
SetPropertyInstance(publisher);
}
}
/// <summary>
/// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork.
/// </summary>
private PublishingPrinciples_Core publishingPrinciples;
public PublishingPrinciples_Core PublishingPrinciples
{
get
{
return publishingPrinciples;
}
set
{
publishingPrinciples = value;
SetPropertyInstance(publishingPrinciples);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The Organization on whose behalf the creator was working.
/// </summary>
private SourceOrganization_Core sourceOrganization;
public SourceOrganization_Core SourceOrganization
{
get
{
return sourceOrganization;
}
set
{
sourceOrganization = value;
SetPropertyInstance(sourceOrganization);
}
}
/// <summary>
/// A thumbnail image relevant to the Thing.
/// </summary>
private ThumbnailURL_Core thumbnailURL;
public ThumbnailURL_Core ThumbnailURL
{
get
{
return thumbnailURL;
}
set
{
thumbnailURL = value;
SetPropertyInstance(thumbnailURL);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
/// <summary>
/// The version of the CreativeWork embodied by a specified resource.
/// </summary>
private Version_Core version;
public Version_Core Version
{
get
{
return version;
}
set
{
version = value;
SetPropertyInstance(version);
}
}
/// <summary>
/// An embedded video object.
/// </summary>
private Video_Core video;
public Video_Core Video
{
get
{
return video;
}
set
{
video = value;
SetPropertyInstance(video);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using static Actress.Tests.Option;
namespace Actress.Tests
{
/// <summary>
/// https://github.com/fsharp/fsharp/blob/master/tests/xplat/core/FsharpUnitTestProject/SharedTests/control-mailbox.fs
/// </summary>
public class MailboxProcessorTests
{
private class Message
{
}
private class Reset : Message
{
}
private class Increment : Message
{
public Increment(int value)
{
this.Value = value;
}
public int Value { get; private set; }
}
private class Fetch : Message
{
public Fetch(IReplyChannel<int?> channel)
{
this.Channel = channel;
}
public IReplyChannel<int?> Channel { get; private set; }
}
private MailboxProcessor<Message> GetSimpleMailbox()
{
return new MailboxProcessor<Message>(async inbox =>
{
int n = 0;
while (true)
{
var msg = await inbox.Receive();
await Task.Delay(100);
if (msg is Increment)
{
n = n + ((Increment) msg).Value;
}
else if (msg is Reset)
{
n = 0;
}
else if (msg is Fetch)
{
var chan = ((Fetch) msg).Channel;
chan.Reply(n);
}
}
});
}
[Fact]
public void DefaultTimeout()
{
// Given
var mailbox = GetSimpleMailbox();
// When
mailbox.Start();
Assert.Equal(Timeout.Infinite, mailbox.DefaultTimeout);
mailbox.Post(new Reset());
mailbox.Post(new Increment(1));
var result = mailbox.TryPostAndReply<int?>(chan => new Fetch(chan));
Assert.NotNull(result);
Assert.Equal(1, result.Value);
// Verify timeout when updating default timeout
// We expect this to fail because of the 100ms sleep in the mailbox
mailbox.DefaultTimeout = 10;
mailbox.Post(new Reset());
mailbox.Post(new Increment(1));
result = mailbox.TryPostAndReply<int?>(chan => new Fetch(chan));
Assert.Null(result);
}
[Fact]
public void Receive_PostAndReply()
{
// Given
var mb = MailboxProcessor.Start<IReplyChannel<int?>>(async inbox =>
{
var msg = await inbox.Receive();
msg.Reply(100);
});
// When
var result = mb.PostAndReply<int?>(channel => channel);
Assert.Equal(100, result);
}
[Fact]
public void MailboxProcessor_null()
{
// Given
var mb = new MailboxProcessor<IReplyChannel<int?>>(async inbox => { });
// When
mb.Start();
// Then
// no exceptions
}
[Fact]
public void Receive_PostAndReply2()
{
// Given
var mb = MailboxProcessor.Start<IReplyChannel<int?>>(async inbox =>
{
var msg = await inbox.Receive();
msg.Reply(100);
var msg2 = await inbox.Receive();
msg2.Reply(200);
});
// When
var result1 = mb.PostAndReply<int?>(channel => channel);
var result2 = mb.PostAndReply<int?>(channel => channel);
// Then
Assert.Equal(100, result1);
Assert.Equal(200, result2);
}
[Fact]
public void TryReceive_PostAndReply()
{
// Given
var mb = MailboxProcessor.Start<IReplyChannel<int?>>(async inbox =>
{
var msg = await inbox.TryReceive();
if (msg == null)
{
Assert.True(false);
return;
}
msg.Reply(100);
var msg2 = await inbox.TryReceive();
if (msg2 == null)
{
Assert.True(false);
return;
}
msg2.Reply(200);
});
// When
var result1 = mb.PostAndReply<int?>(channel => channel);
var result2 = mb.PostAndReply<int?>(channel => channel);
// Then
Assert.Equal(100, result1);
Assert.Equal(200, result2);
}
[Theory]
[InlineData(0)]
[InlineData(10)]
public void TryReceive_timeout(int timeout)
{
// Given
var mb = MailboxProcessor.Start<IReplyChannel<int?>>(async inbox =>
{
var replyChannel = await inbox.TryReceive();
if (replyChannel == null)
{
Assert.True(false);
return;
}
var msg2 = await inbox.TryReceive(timeout);
replyChannel.Reply(msg2 == null ? 100 : 200);
});
// When
var result1 = mb.PostAndReply<int?>(channel => channel);
// Then
Assert.Equal(100, result1);
}
[Theory]
[InlineData(10)]
public void TryReceivePostAndReply_With_Receive_timeout(int timeout)
{
// Given
var mb = MailboxProcessor.Start<IReplyChannel<int?>>(async inbox =>
{
var replyChannel = await inbox.TryReceive();
if (replyChannel == null)
{
Assert.True(false);
return;
}
try
{
var _ = await inbox.Receive(timeout);
Assert.True(false, "should have received timeout");
}
catch (TimeoutException)
{
replyChannel.Reply(200);
}
});
// When
var result1 = mb.PostAndReply<int?>(channel => channel);
// Then
Assert.Equal(200, result1);
}
[Theory]
[InlineData(10)]
public void TryReceivePostAndReply_with_Scan_timeout(int timeout)
{
// Given
var mb = MailboxProcessor.Start<IReplyChannel<int?>>(async inbox =>
{
var replyChannel = await inbox.TryReceive();
if (replyChannel == null)
{
Assert.True(false);
return;
}
try
{
var _ = await inbox.Scan(__ =>
{
Assert.True(false, "Should have timedout");
return Task.FromResult(inbox);
}, timeout);
Assert.True(false, "should have received timeout");
}
catch (TimeoutException)
{
replyChannel.Reply(200);
}
});
// When
var result1 = mb.PostAndReply<int?>(channel => channel);
// Then
Assert.Equal(200, result1);
}
[Theory]
[InlineData(10)]
public void TryReceivePostAndReply_with_TryScan_timeout(int timeout)
{
// Given
var mb = MailboxProcessor.Start<IReplyChannel<int?>>(async inbox =>
{
var replyChannel = await inbox.TryReceive();
if (replyChannel == null)
{
Assert.True(false);
return;
}
var scanRes = await inbox.TryScan(__ =>
{
Assert.True(false, "Should have timedout");
return Task.FromResult(inbox);
}, timeout);
if (scanRes == null)
{
replyChannel.Reply(200);
}
else
{
Assert.True(false, "TryScan should have failed");
}
});
// When
var result1 = mb.PostAndReply<int?>(channel => channel);
// Then
Assert.Equal(200, result1);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
[InlineData(1000)]
[InlineData(10000)]
public void PostReceive(int n)
{
// Given
var received = 0L;
var mb = MailboxProcessor.Start<Option<int>>(async inbox =>
{
for (var i = 0; i < n; i++)
{
var _ = await inbox.Receive();
Interlocked.Increment(ref received);
}
});
// When
for (var i = 0; i < n; i++)
{
mb.Post(Some(i));
}
// Then
while (received < n)
{
var numReceived = Interlocked.Read(ref received);
if (numReceived % 100 == 0)
{
Trace.WriteLine(string.Format("received = {0}", numReceived));
}
Thread.Sleep(1);
}
Assert.Equal(n, received);
}
[Theory]
[InlineData(0, 0)]
[InlineData(0, 1)]
[InlineData(0, 100)]
[InlineData(10, 0)]
[InlineData(10, 1)]
[InlineData(10, 100)]
public void PostTryReceive(int timeout, int n)
{
// Given
var received = 0L;
var mb = MailboxProcessor.Start<Option<int>>(async inbox =>
{
while (Interlocked.Read(ref received) < n)
{
var msgOpt = await inbox.TryReceive(timeout);
if (msgOpt == null)
{
var numReceived = Interlocked.Read(ref received);
if (numReceived % 100 == 0)
Trace.WriteLine(string.Format("timeout!, received = {0}", numReceived));
}
else
{
Interlocked.Increment(ref received);
}
}
});
// When
for (var i = 0; i < n; i++)
{
Thread.Sleep(1);
mb.Post(Some(i));
}
// Then
while (Interlocked.Read(ref received) < n)
{
var numReceived = Interlocked.Read(ref received);
if (numReceived%100 == 0)
Trace.WriteLine(string.Format("received = {0}", numReceived));
Thread.Sleep(1);
}
Assert.Equal(n, received);
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.LogReceiverService
{
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System;
using System.IO;
using Xunit;
#if WCF_SUPPORTED
using System.Data;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Description;
#endif
using System.Xml;
using System.Xml.Serialization;
using NLog.Layouts;
using NLog.LogReceiverService;
public class LogReceiverServiceTests : NLogTestBase
{
private const string logRecieverUrl = "http://localhost:8080/logrecievertest";
[Fact]
public void ToLogEventInfoTest()
{
var events = new NLogEvents
{
BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks,
ClientName = "foo",
LayoutNames = new StringCollection { "foo", "bar", "baz" },
Strings = new StringCollection { "logger1", "logger2", "logger3", "zzz", "message1" },
Events =
new[]
{
new NLogEvent
{
Id = 1,
LevelOrdinal = 2,
LoggerOrdinal = 0,
TimeDelta = 30000000,
MessageOrdinal = 4,
Values = "0|1|2"
},
new NLogEvent
{
Id = 2,
LevelOrdinal = 3,
LoggerOrdinal = 2,
MessageOrdinal = 4,
TimeDelta = 30050000,
Values = "0|1|3",
}
}
};
var converted = events.ToEventInfo();
Assert.Equal(2, converted.Count);
Assert.Equal("message1", converted[0].FormattedMessage);
Assert.Equal("message1", converted[1].FormattedMessage);
Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 0, DateTimeKind.Utc), converted[0].TimeStamp.ToUniversalTime());
Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 5, DateTimeKind.Utc), converted[1].TimeStamp.ToUniversalTime());
Assert.Equal("logger1", converted[0].LoggerName);
Assert.Equal("logger3", converted[1].LoggerName);
Assert.Equal(LogLevel.Info, converted[0].Level);
Assert.Equal(LogLevel.Warn, converted[1].Level);
Layout fooLayout = "${event-context:foo}";
Layout barLayout = "${event-context:bar}";
Layout bazLayout = "${event-context:baz}";
Assert.Equal("logger1", fooLayout.Render(converted[0]));
Assert.Equal("logger1", fooLayout.Render(converted[1]));
Assert.Equal("logger2", barLayout.Render(converted[0]));
Assert.Equal("logger2", barLayout.Render(converted[1]));
Assert.Equal("logger3", bazLayout.Render(converted[0]));
Assert.Equal("zzz", bazLayout.Render(converted[1]));
}
[Fact]
public void NoLayoutsTest()
{
var events = new NLogEvents
{
BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks,
ClientName = "foo",
LayoutNames = new StringCollection(),
Strings = new StringCollection { "logger1", "logger2", "logger3", "zzz", "message1" },
Events =
new[]
{
new NLogEvent
{
Id = 1,
LevelOrdinal = 2,
LoggerOrdinal = 0,
TimeDelta = 30000000,
MessageOrdinal = 4,
Values = null,
},
new NLogEvent
{
Id = 2,
LevelOrdinal = 3,
LoggerOrdinal = 2,
MessageOrdinal = 4,
TimeDelta = 30050000,
Values = null,
}
}
};
var converted = events.ToEventInfo();
Assert.Equal(2, converted.Count);
Assert.Equal("message1", converted[0].FormattedMessage);
Assert.Equal("message1", converted[1].FormattedMessage);
Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 0, DateTimeKind.Utc), converted[0].TimeStamp.ToUniversalTime());
Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 5, DateTimeKind.Utc), converted[1].TimeStamp.ToUniversalTime());
Assert.Equal("logger1", converted[0].LoggerName);
Assert.Equal("logger3", converted[1].LoggerName);
Assert.Equal(LogLevel.Info, converted[0].Level);
Assert.Equal(LogLevel.Warn, converted[1].Level);
}
/// <summary>
/// Ensures that serialization formats of DataContractSerializer and XmlSerializer are the same
/// on the same <see cref="NLogEvents"/> object.
/// </summary>
[Fact]
public void CompareSerializationFormats()
{
var events = new NLogEvents
{
BaseTimeUtc = DateTime.UtcNow.Ticks,
ClientName = "foo",
LayoutNames = new StringCollection { "foo", "bar", "baz" },
Strings = new StringCollection { "logger1", "logger2", "logger3" },
Events =
new[]
{
new NLogEvent
{
Id = 1,
LevelOrdinal = 2,
LoggerOrdinal = 0,
TimeDelta = 34,
Values = "1|2|3"
},
new NLogEvent
{
Id = 2,
LevelOrdinal = 3,
LoggerOrdinal = 2,
TimeDelta = 345,
Values = "1|2|3",
}
}
};
var serializer1 = new XmlSerializer(typeof(NLogEvents));
var sw1 = new StringWriter();
using (var writer1 = XmlWriter.Create(sw1, new XmlWriterSettings { Indent = true }))
{
var namespaces = new XmlSerializerNamespaces();
namespaces.Add("i", "http://www.w3.org/2001/XMLSchema-instance");
serializer1.Serialize(writer1, events, namespaces);
}
var serializer2 = new DataContractSerializer(typeof(NLogEvents));
var sw2 = new StringWriter();
using (var writer2 = XmlWriter.Create(sw2, new XmlWriterSettings { Indent = true }))
{
serializer2.WriteObject(writer2, events);
}
var xml1 = sw1.ToString();
var xml2 = sw2.ToString();
Assert.Equal(xml1, xml2);
}
#if WCF_SUPPORTED
#if MONO
[Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void RealTestLogReciever_two_way()
{
RealTestLogReciever(false, false);
}
#if MONO
[Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void RealTestLogReciever_one_way()
{
RealTestLogReciever(true, false);
}
[Fact(Skip = "unit test should listen to non-http for this")]
public void RealTestLogReciever_two_way_binary()
{
RealTestLogReciever(false, true);
}
[Fact(Skip = "unit test should listen to non-http for this")]
public void RealTestLogReciever_one_way_binary()
{
RealTestLogReciever(true, true);
}
private void RealTestLogReciever(bool useOneWayContract, bool binaryEncode)
{
LogManager.Configuration = CreateConfigurationFromString(string.Format(@"
<nlog throwExceptions='true'>
<targets>
<target type='LogReceiverService'
name='s1'
endpointAddress='{0}'
useOneWayContract='{1}'
useBinaryEncoding='{2}'
includeEventProperties='false'>
<!-- <parameter name='key1' layout='testparam1' type='String'/> -->
</target>
</targets>
<rules>
<logger name='logger1' minlevel='Trace' writeTo='s1' />
</rules>
</nlog>", logRecieverUrl, useOneWayContract.ToString().ToLower(), binaryEncode.ToString().ToLower()));
ExecLogRecieverAndCheck(ExecLogging1, CheckRecieved1, 2);
}
/// <summary>
/// Create WCF service, logs and listen to the events
/// </summary>
/// <param name="logFunc">function for logging the messages</param>
/// <param name="logCheckFunc">function for checking the received messsages</param>
/// <param name="messageCount">message count for wait for listen and checking</param>
public void ExecLogRecieverAndCheck(Action<Logger> logFunc, Action<List<NLogEvents>> logCheckFunc, int messageCount)
{
Uri baseAddress = new Uri(logRecieverUrl);
// Create the ServiceHost.
using (ServiceHost host = new ServiceHost(typeof(LogRecieverMock), baseAddress))
{
// Enable metadata publishing.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
#if !MONO
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
#endif
host.Description.Behaviors.Add(smb);
// Open the ServiceHost to start listening for messages. Since
// no endpoints are explicitly configured, the runtime will create
// one endpoint per base address for each service contract implemented
// by the service.
host.Open();
//wait for 2 events
var countdownEvent = new CountdownEvent(messageCount);
//reset
LogRecieverMock.recievedEvents = new List<NLogEvents>();
LogRecieverMock.CountdownEvent = countdownEvent;
var logger1 = LogManager.GetLogger("logger1");
logFunc(logger1);
countdownEvent.Wait(20000);
//we need some extra time for completion
Thread.Sleep(1000);
var recieved = LogRecieverMock.recievedEvents;
Assert.Equal(messageCount, recieved.Count);
logCheckFunc(recieved);
// Close the ServiceHost.
host.Close();
}
}
private static void CheckRecieved1(List<NLogEvents> recieved)
{
//in some case the messages aren't retrieved in the right order when invoked in the same sec.
//more important is that both are retrieved with the correct info
Assert.Equal(2, recieved.Count);
var logmessages = new HashSet<string> {recieved[0].ToEventInfo().First().Message, recieved[1].ToEventInfo().First().Message};
Assert.True(logmessages.Contains("test 1"), "message 1 is missing");
Assert.True(logmessages.Contains("test 2"), "message 2 is missing");
}
private static void ExecLogging1(Logger logger)
{
logger.Info("test 1");
//we wait 10 ms, because after a cold boot, the messages are arrived in the same moment and the order can change.
Thread.Sleep(10);
logger.Info(new InvalidConstraintException("boo"), "test 2");
}
public class LogRecieverMock : ILogReceiverServer, ILogReceiverOneWayServer
{
public static CountdownEvent CountdownEvent;
public static List<NLogEvents> recievedEvents = new List<NLogEvents>();
/// <summary>
/// Processes the log messages.
/// </summary>
/// <param name="events">The events.</param>
public void ProcessLogMessages(NLogEvents events)
{
if (CountdownEvent == null)
{
throw new Exception("test not prepared well");
}
recievedEvents.Add(events);
CountdownEvent.Signal();
}
}
#endif
}
}
| |
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Orleans.Runtime;
using System.Linq;
namespace UnitTests.Grains
{
public class ObserverManager<TObserver> : ObserverManager<IAddressable, TObserver>
{
public ObserverManager(TimeSpan expiration, ILogger log, string logPrefix) : base(expiration, log, logPrefix)
{
}
}
/// <summary>
/// Maintains a collection of observers.
/// </summary>
/// <typeparam name="TAddress">
/// The address type.
/// </typeparam>
/// <typeparam name="TObserver">
/// The observer type.
/// </typeparam>
public class ObserverManager<TAddress, TObserver> : IEnumerable<TObserver>
{
/// <summary>
/// The log prefix.
/// </summary>
private readonly string logPrefix;
/// <summary>
/// The observers.
/// </summary>
private readonly ConcurrentDictionary<TAddress, ObserverEntry> observers = new ConcurrentDictionary<TAddress, ObserverEntry>();
/// <summary>
/// The log.
/// </summary>
private readonly ILogger log;
/// <summary>
/// Initializes a new instance of the <see cref="ObserverManager{TAddress,TObserver}"/> class.
/// </summary>
/// <param name="expiration">
/// The expiration.
/// </param>
/// <param name="log">The log.</param>
/// <param name="logPrefix">The prefix to use when logging.</param>
public ObserverManager(TimeSpan expiration, ILogger log, string logPrefix)
{
this.ExpirationDuration = expiration;
this.log = log;
this.logPrefix = logPrefix;
this.GetDateTime = () => DateTime.UtcNow;
}
/// <summary>
/// Gets or sets the delegate used to get the date and time, for expiry.
/// </summary>
public Func<DateTime> GetDateTime { get; set; }
/// <summary>
/// Gets or sets the expiration time span, after which observers are lazily removed.
/// </summary>
public TimeSpan ExpirationDuration { get; set; }
/// <summary>
/// Gets the number of observers.
/// </summary>
public int Count => this.observers.Count;
/// <summary>
/// Gets a copy of the observers.
/// </summary>
public IDictionary<TAddress, TObserver> Observers
{
get
{
return this.observers.ToDictionary(_ => _.Key, _ => _.Value.Observer);
}
}
/// <summary>
/// Removes all observers.
/// </summary>
public void Clear()
{
this.observers.Clear();
}
/// <summary>
/// Ensures that the provided <paramref name="observer"/> is subscribed, renewing its subscription.
/// </summary>
/// <param name="address">
/// The subscriber's address
/// </param>
/// <param name="observer">
/// The observer.
/// </param>
/// <exception cref="Exception">A delegate callback throws an exception.</exception>
public void Subscribe(TAddress address, TObserver observer)
{
// Add or update the subscription.
var now = this.GetDateTime();
ObserverEntry entry;
if (this.observers.TryGetValue(address, out entry))
{
entry.LastSeen = now;
entry.Observer = observer;
if (this.log.IsEnabled(LogLevel.Debug))
{
this.log.LogDebug(this.logPrefix + ": Updating entry for {0}/{1}. {2} total subscribers.", address, observer, this.observers.Count);
}
}
else
{
this.observers[address] = new ObserverEntry { LastSeen = now, Observer = observer };
if (this.log.IsEnabled(LogLevel.Debug))
{
this.log.LogDebug(this.logPrefix + ": Adding entry for {0}/{1}. {2} total subscribers after add.", address, observer, this.observers.Count);
}
}
}
/// <summary>
/// Ensures that the provided <paramref name="subscriber"/> is unsubscribed.
/// </summary>
/// <param name="subscriber">
/// The observer.
/// </param>
public void Unsubscribe(TAddress subscriber)
{
ObserverEntry removed;
this.log.LogDebug(this.logPrefix + ": Removed entry for {0}. {1} total subscribers after remove.", subscriber, this.observers.Count);
this.observers.TryRemove(subscriber, out removed);
}
/// <summary>
/// Notifies all observers.
/// </summary>
/// <param name="notification">
/// The notification delegate to call on each observer.
/// </param>
/// <param name="predicate">
/// The predicate used to select observers to notify.
/// </param>
/// <returns>
/// A <see cref="Task"/> representing the work performed.
/// </returns>
public async Task Notify(Func<TObserver, Task> notification, Func<TObserver, bool> predicate = null)
{
var now = this.GetDateTime();
var defunct = default(List<TAddress>);
foreach (var observer in this.observers)
{
if (observer.Value.LastSeen + this.ExpirationDuration < now)
{
// Expired observers will be removed.
defunct = defunct ?? new List<TAddress>();
defunct.Add(observer.Key);
continue;
}
// Skip observers which don't match the provided predicate.
if (predicate != null && !predicate(observer.Value.Observer))
{
continue;
}
try
{
await notification(observer.Value.Observer);
}
catch (Exception)
{
// Failing observers are considered defunct and will be removed..
defunct = defunct ?? new List<TAddress>();
defunct.Add(observer.Key);
}
}
// Remove defunct observers.
if (defunct != default(List<TAddress>))
{
foreach (var observer in defunct)
{
ObserverEntry removed;
this.observers.TryRemove(observer, out removed);
if (this.log.IsEnabled(LogLevel.Debug))
{
this.log.LogDebug(this.logPrefix + ": Removing defunct entry for {0}. {1} total subscribers after remove.", observer, this.observers.Count);
}
}
}
}
/// <summary>
/// Notifies all observers which match the provided <paramref name="predicate"/>.
/// </summary>
/// <param name="notification">
/// The notification delegate to call on each observer.
/// </param>
/// <param name="predicate">
/// The predicate used to select observers to notify.
/// </param>
public void Notify(Action<TObserver> notification, Func<TObserver, bool> predicate = null)
{
var now = this.GetDateTime();
var defunct = default(List<TAddress>);
foreach (var observer in this.observers)
{
if (observer.Value.LastSeen + this.ExpirationDuration < now)
{
// Expired observers will be removed.
defunct = defunct ?? new List<TAddress>();
defunct.Add(observer.Key);
continue;
}
// Skip observers which don't match the provided predicate.
if (predicate != null && !predicate(observer.Value.Observer))
{
continue;
}
try
{
notification(observer.Value.Observer);
}
catch (Exception)
{
// Failing observers are considered defunct and will be removed..
defunct = defunct ?? new List<TAddress>();
defunct.Add(observer.Key);
}
}
// Remove defunct observers.
if (defunct != default(List<TAddress>))
{
foreach (var observer in defunct)
{
ObserverEntry removed;
this.observers.TryRemove(observer, out removed);
if (this.log.IsEnabled(LogLevel.Debug))
{
this.log.LogDebug(this.logPrefix + ": Removing defunct entry for {0}. {1} total subscribers after remove.", observer, this.observers.Count);
}
}
}
}
/// <summary>
/// Removed all expired observers.
/// </summary>
public void ClearExpired()
{
var now = this.GetDateTime();
var defunct = default(List<TAddress>);
foreach (var observer in this.observers)
{
if (observer.Value.LastSeen + this.ExpirationDuration < now)
{
// Expired observers will be removed.
defunct = defunct ?? new List<TAddress>();
defunct.Add(observer.Key);
}
}
// Remove defunct observers.
if (defunct != default(List<TAddress>) && defunct.Count > 0)
{
this.log.Info(this.logPrefix + ": Removing {0} defunct observers entries.", defunct.Count);
foreach (var observer in defunct)
{
ObserverEntry removed;
this.observers.TryRemove(observer, out removed);
}
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<TObserver> GetEnumerator()
{
return this.observers.Select(observer => observer.Value.Observer).GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// An observer entry.
/// </summary>
private class ObserverEntry
{
/// <summary>
/// Gets or sets the observer.
/// </summary>
public TObserver Observer { get; set; }
/// <summary>
/// Gets or sets the UTC last seen time.
/// </summary>
public DateTime LastSeen { get; set; }
}
}
}
| |
//
// Authors:
// Ben Motmans <[email protected]>
// Nicholas Terry <[email protected]>
//
// Copyright (C) 2007 Ben Motmans
// Copyright (C) 2014 Nicholas Terry
//
// 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.Net;
using System.Net.Sockets;
using System.Threading;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Net.NetworkInformation;
using Mono.Nat.Pmp.Mappers;
using Mono.Nat.Upnp.Mappers;
namespace Mono.Nat
{
public static class NatUtility
{
private static ManualResetEvent searching;
public static event EventHandler<DeviceEventArgs> DeviceFound;
public static event EventHandler<DeviceEventArgs> DeviceLost;
public static event EventHandler<UnhandledExceptionEventArgs> UnhandledException;
private static TextWriter logger;
private static List<ISearcher> controllers;
private static bool verbose;
public static TextWriter Logger
{
get { return logger; }
set { logger = value; }
}
public static bool Verbose
{
get { return verbose; }
set { verbose = value; }
}
static NatUtility()
{
searching = new ManualResetEvent(false);
controllers = new List<ISearcher>();
controllers.Add(UpnpSearcher.Instance);
controllers.Add(PmpSearcher.Instance);
controllers.ForEach(searcher =>
{
searcher.DeviceFound += (sender, args) =>
{
if (DeviceFound != null)
DeviceFound(sender, args);
};
searcher.DeviceLost += (sender, args) =>
{
if (DeviceLost != null)
DeviceLost(sender, args);
};
});
Thread t = new Thread(SearchAndListen);
t.IsBackground = true;
t.Start();
}
internal static void Log(string format, params object[] args)
{
TextWriter logger = Logger;
if (logger != null)
logger.WriteLine(format, args);
}
private static void SearchAndListen()
{
while (true)
{
searching.WaitOne();
try
{
Receive(UpnpSearcher.Instance, UpnpSearcher.sockets);
Receive(PmpSearcher.Instance, PmpSearcher.sockets);
foreach (ISearcher s in controllers)
if (s.NextSearch < DateTime.Now)
{
Log("Searching for: {0}", s.GetType().Name);
s.Search();
}
}
catch (Exception e)
{
if (UnhandledException != null)
UnhandledException(typeof(NatUtility), new UnhandledExceptionEventArgs(e, false));
}
Thread.Sleep(10);
}
}
static void Receive (ISearcher searcher, List<UdpClient> clients)
{
IPEndPoint received = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 5351);
foreach (UdpClient client in clients)
{
if (client.Available > 0)
{
IPAddress localAddress = ((IPEndPoint)client.Client.LocalEndPoint).Address;
byte[] data = client.Receive(ref received);
searcher.Handle(localAddress, data, received);
}
}
}
static void Receive(IMapper mapper, List<UdpClient> clients)
{
IPEndPoint received = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 5351);
foreach (UdpClient client in clients)
{
if (client.Available > 0)
{
IPAddress localAddress = ((IPEndPoint)client.Client.LocalEndPoint).Address;
byte[] data = client.Receive(ref received);
mapper.Handle(localAddress, data);
}
}
}
public static void StartDiscovery ()
{
searching.Set();
}
public static void StopDiscovery ()
{
searching.Reset();
}
//This is for when you know the Gateway IP and want to skip the costly search...
public static void DirectMap(IPAddress gatewayAddress, MapperType type)
{
IMapper mapper;
switch (type)
{
case MapperType.Pmp:
mapper = new PmpMapper();
break;
case MapperType.Upnp:
mapper = new UpnpMapper();
mapper.DeviceFound += (sender, args) =>
{
if (DeviceFound != null)
DeviceFound(sender, args);
};
mapper.Map(gatewayAddress);
break;
default:
throw new InvalidOperationException("Unsuported type given");
}
searching.Reset();
}
//So then why is it here? -Nick
[Obsolete ("This method serves no purpose and shouldn't be used")]
public static IPAddress[] GetLocalAddresses (bool includeIPv6)
{
List<IPAddress> addresses = new List<IPAddress> ();
IPHostEntry hostInfo = Dns.GetHostEntry (Dns.GetHostName ());
foreach (IPAddress address in hostInfo.AddressList) {
if (address.AddressFamily == AddressFamily.InterNetwork ||
(includeIPv6 && address.AddressFamily == AddressFamily.InterNetworkV6)) {
addresses.Add (address);
}
}
return addresses.ToArray ();
}
//checks if an IP address is a private address space as defined by RFC 1918
public static bool IsPrivateAddressSpace (IPAddress address)
{
byte[] ba = address.GetAddressBytes ();
switch ((int)ba[0]) {
case 10:
return true; //10.x.x.x
case 172:
return ((int)ba[1] & 16) != 0; //172.16-31.x.x
case 192:
return (int)ba[1] == 168; //192.168.x.x
default:
return false;
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using RdlEngine.Resources;
using fyiReporting.RDL;
namespace fyiReporting.RDL
{
/// <summary>
/// The Financial class holds a number of static functions relating to financial
/// calculations.
///
/// Note: many of the financial functions use the following function as their basis
/// pv*(1+rate)^nper+pmt*(1+rate*type)*((1+rate)^nper-1)/rate)+fv=0
/// if rate = 0
/// (pmt*nper)+pv+fv=0
/// </summary>
sealed internal class Financial
{
/// <summary>
/// Double declining balance depreciation (when factor = 2). Other factors may be specified.
/// </summary>
/// <param name="cost">Initial cost of asset</param>
/// <param name="salvage">Salvage value of asset at end of depreciation</param>
/// <param name="life">Number of periods over which to depreciate the asset. AKA useful life</param>
/// <param name="period">The period for which you want to know the depreciation amount.</param>
/// <returns></returns>
static public double DDB(double cost, double salvage, int life, int period)
{
return DDB(cost, salvage, life, period, 2);
}
/// <summary>
/// Double declining balance depreciation (when factor = 2). Other factors may be specified.
/// </summary>
/// <param name="cost">Initial cost of asset</param>
/// <param name="salvage">Salvage value of asset at end of depreciation</param>
/// <param name="life">Number of periods over which to depreciate the asset. AKA useful life</param>
/// <param name="period">The period for which you want to know the depreciation amount.</param>
/// <param name="factor">The rate at which the balance declines. Defaults to 2 (double declining) when omitted.</param>
/// <returns></returns>
static public double DDB(double cost, double salvage, int life, int period, double factor)
{
if (period > life || period < 1 || life < 1) // invalid arguments
return double.NaN;
double depreciation=0;
for (int i=1; i < period; i++)
{
depreciation += (cost - depreciation)*factor/life;
}
if (period == life)
return cost - salvage - depreciation; // for last year we force the depreciation so that cost - total depreciation = salvage
else
return (cost - depreciation)*factor/life;
}
/// <summary>
/// Returns the future value of an investment when using periodic, constant payments and
/// constant interest rate.
/// </summary>
/// <param name="rate">Interest rate per period</param>
/// <param name="periods">Total number of payment periods</param>
/// <param name="pmt">Amount of payment each period</param>
/// <param name="presentValue">Lump sum amount that a series of payments is worth now</param>
/// <param name="endOfPeriod">Specify true if payments are due at end of period, otherwise false</param>
/// <returns></returns>
static public double FV(double rate, int periods, double pmt, double presentValue, bool endOfPeriod)
{
int type = endOfPeriod? 0: 1;
double fv;
if (rate == 0)
fv = -(pmt*periods+presentValue);
else
{
double temp = Math.Pow(1+rate, periods);
fv = -(presentValue*temp + pmt*(1+rate*type)*((temp -1)/rate));
}
return fv;
}
/// <summary>
/// Returns the interest payment portion of a payment given a particular period.
/// </summary>
/// <param name="rate">Interest rate per period</param>
/// <param name="period">Period for which you want the interest payment.</param>
/// <param name="periods">Total number of payment periods</param>
/// <param name="presentValue">Lump sum amount that a series of payments is worth now</param>
/// <param name="futureValue">Cash balance you want to attain after last payment</param>
/// <param name="endOfPeriod">Specify true if payments are due at end of period, otherwise false</param>
/// <returns></returns>
static public double IPmt(double rate, int period, int periods, double presentValue, double futureValue, bool endOfPeriod)
{
// TODO -- routine needs more work. off when endOfPeriod is false; must be more direct way to solve
if (!endOfPeriod)
throw new Exception(Strings.Financial_Error_IPmtNotSupportPayments);
if (period < 0 || period > periods)
return double.NaN;
if (!endOfPeriod)
period--;
double pmt = -Pmt(rate, periods, presentValue, futureValue, endOfPeriod);
double prin = presentValue;
double interest=0;
for (int i=0; i < period; i++)
{
interest = rate*prin;
prin = prin - pmt + interest;
}
return -interest;
}
/// <summary>
/// Returns the number of periods for an investment.
/// </summary>
/// <param name="rate">Interest rate per period</param>
/// <param name="pmt">Amount of payment each period</param>
/// <param name="presentValue">Lump sum amount that a series of payments is worth now</param>
/// <param name="futureValue">Future value or cash balance you want after last payment</param>
/// <param name="endOfPeriod">Specify true if payments are due at end of period, otherwise false</param>
/// <returns></returns>
static public double NPer(double rate, double pmt, double presentValue, double futureValue, bool endOfPeriod)
{
if (Math.Abs(pmt) < double.Epsilon)
return double.NaN;
int type = endOfPeriod? 0: 1;
double nper;
if (rate == 0)
nper = -(presentValue + futureValue)/pmt;
else
{
double r1 = 1 + rate*type;
double pmtr1 = pmt * r1 / rate;
double y = (pmtr1 - futureValue) / (presentValue + pmtr1);
nper = Math.Log(y) / Math.Log(1 + rate);
}
return nper;
}
/// <summary>
/// Returns the periodic payment for an annuity using constant payments and
/// constant interest rate.
/// </summary>
/// <param name="rate">Interest rate per period</param>
/// <param name="periods">Total number of payment periods</param>
/// <param name="presentValue">Lump sum amount that a series of payments is worth now</param>
/// <param name="futureValue">Cash balance you want to attain after last payment</param>
/// <param name="endOfPeriod">Specify true if payments are due at end of period, otherwise false</param>
/// <returns></returns>
static public double Pmt(double rate, int periods, double presentValue, double futureValue, bool endOfPeriod)
{
if (periods < 1)
return double.NaN;
int type = endOfPeriod? 0: 1;
double pmt;
if (rate == 0)
pmt = -(presentValue + futureValue)/periods;
else
{
double temp = Math.Pow(1+rate, periods);
pmt = -(presentValue*temp + futureValue) / ((1+rate*type)*(temp-1)/rate);
}
return pmt;
}
/// <summary>
/// Returns the present value of an investment. The present value is the total
/// amount that a series of future payments is worth now.
/// </summary>
/// <param name="rate">Interest rate per period</param>
/// <param name="periods">Total number of payment periods</param>
/// <param name="pmt">Amount of payment each period</param>
/// <param name="futureValue">Cash balance you want to attain after last payment is made</param>
/// <param name="endOfPeriod">Specify true if payments are due at end of period, otherwise false</param>
/// <returns></returns>
static public double PV(double rate, int periods, double pmt, double futureValue, bool endOfPeriod)
{
int type = endOfPeriod? 0: 1;
double pv;
if (rate == 0)
pv = -(pmt*periods+futureValue);
else
{
double temp = Math.Pow(1+rate, periods);
pv = -(pmt*(1+rate*type)*((temp-1)/rate) + futureValue)/temp;
}
return pv;
}
/// <summary>
/// Returns the interest rate per period for an annuity. This routine uses an
/// iterative approach to solving for rate. If after 30 iterations the answer
/// doesn't converge to within 0.0000001 then double.NAN is returned.
/// </summary>
/// <param name="periods">Total number of payment periods</param>
/// <param name="pmt">Amount of payment each period</param>
/// <param name="presentValue">Lump sum amount that a series of payments is worth now</param>
/// <param name="futureValue">Cash balance you want to attain after last payment</param>
/// <param name="endOfPeriod">Specify true if payments are due at end of period, otherwise false</param>
/// <param name="guess">Your guess as to what the interest rate will be.</param>
/// <returns></returns>
static public double Rate(int periods, double pmt, double presentValue, double futureValue, bool endOfPeriod, double guess)
{
// TODO: should be better algorithm: linear interpolation, Newton-Raphson approximation???
int type = endOfPeriod? 0: 1;
// Set the lower bound
double gLower= guess > .1? guess-.1: 0;
double power2=.1;
while (RateGuess(periods, pmt, presentValue, futureValue, type, gLower) > 0)
{
gLower -= power2;
power2 *= 2;
}
// Set the upper bound
double gUpper= guess+.1;
power2=.1;
while (RateGuess(periods, pmt, presentValue, futureValue, type, gUpper) < 0)
{
gUpper += power2;
power2 *= 2;
}
double z;
double incr;
double newguess;
for (int i= 0; i<30; i++)
{
z = RateGuess(periods,pmt,presentValue,futureValue, type, guess);
if (z > 0)
{
gUpper = guess;
incr = (guess - gLower)/2;
newguess = guess - incr;
}
else
{
gLower = guess;
incr = (gUpper - guess)/2;
newguess = guess + incr;
}
if (incr < 0.0000001) // Is the difference within our margin of error?
return guess;
guess = newguess;
}
return double.NaN; // we didn't converge
}
static private double RateGuess(int periods, double pmt, double pv, double fv, int type, double rate)
{
// When the guess is close the result should almost be 0
if (rate == 0)
return pmt*periods + pv + fv;
double temp = Math.Pow(1+rate, periods);
return pv*temp + pmt*(1 + rate*type)*((temp - 1)/rate) + fv;
}
/// <summary>
/// SLN returns the straight line depreciation for an asset for a single period.
/// </summary>
/// <param name="cost">Initial cost of asset</param>
/// <param name="salvage">Salvage value of asset at end of depreciation</param>
/// <param name="life">Number of periods over which to depreciate the asset. AKA useful life</param>
/// <returns></returns>
static public double SLN(double cost, double salvage, double life)
{
if (life == 0)
return double.NaN;
return (cost - salvage) / life;
}
/// <summary>
/// Sum of years digits depreciation. An asset often loses more of its value early in its lifetime.
/// SYD has this behavior.
/// </summary>
/// <param name="cost">Initial cost of asset</param>
/// <param name="salvage">Salvage value of asset at end of depreciation</param>
/// <param name="life">Number of periods over which to depreciate the asset. AKA useful life</param>
/// <param name="period">The period for which you want to know the depreciation amount.</param>
/// <returns></returns>
static public double SYD(double cost, double salvage, int life, int period)
{
int sumOfPeriods;
if (life % 2 == 0) // sum = n/2 * (n+1) when even
sumOfPeriods = life/2 * (life + 1);
else // sum = (n+1)/2 * n when odd
sumOfPeriods = (life+1)/2 * life;
return ((life + 1 - period) * (cost - salvage)) / sumOfPeriods;
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.Data;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Windows.Forms;
namespace tdbadmin
{
/// <summary>
/// Summary description for ActionSelForm.
/// </summary>
public class SelForm : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Button Sel_b_ok;
private System.Windows.Forms.Button Sel_b_search;
private System.Windows.Forms.Button Sel_b_cancel;
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.ColumnHeader Sel_id;
private System.Windows.Forms.ColumnHeader Sel_bez;
private System.Windows.Forms.ColumnHeader Sel_code;
private bool itemselected;
private int selid;
public event EventHandler Accept;
private ListViewColumnSorter lvwColumnSorter;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public SelForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
itemselected = false;
selid = -1;
// Create an instance of a ListView column sorter and assign it
// to the ListView control.
lvwColumnSorter = new ListViewColumnSorter();
this.listView1.ListViewItemSorter = lvwColumnSorter;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.Sel_b_cancel = new System.Windows.Forms.Button();
this.Sel_b_search = new System.Windows.Forms.Button();
this.Sel_b_ok = new System.Windows.Forms.Button();
this.listView1 = new System.Windows.Forms.ListView();
this.Sel_id = new System.Windows.Forms.ColumnHeader();
this.Sel_bez = new System.Windows.Forms.ColumnHeader();
this.Sel_code = new System.Windows.Forms.ColumnHeader();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// groupBox2
//
this.groupBox2.Controls.Add(this.Sel_b_cancel);
this.groupBox2.Controls.Add(this.Sel_b_search);
this.groupBox2.Controls.Add(this.Sel_b_ok);
this.groupBox2.Dock = System.Windows.Forms.DockStyle.Bottom;
this.groupBox2.Location = new System.Drawing.Point(0, 333);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(568, 56);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Actions";
//
// Sel_b_cancel
//
this.Sel_b_cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Sel_b_cancel.Location = new System.Drawing.Point(216, 24);
this.Sel_b_cancel.Name = "Sel_b_cancel";
this.Sel_b_cancel.TabIndex = 2;
this.Sel_b_cancel.Text = "Cancel";
this.Sel_b_cancel.Click += new System.EventHandler(this.Sel_b_cancel_Click);
//
// Sel_b_search
//
this.Sel_b_search.Location = new System.Drawing.Point(112, 24);
this.Sel_b_search.Name = "Sel_b_search";
this.Sel_b_search.TabIndex = 1;
this.Sel_b_search.Text = "Search";
//
// Sel_b_ok
//
this.Sel_b_ok.Location = new System.Drawing.Point(8, 24);
this.Sel_b_ok.Name = "Sel_b_ok";
this.Sel_b_ok.TabIndex = 0;
this.Sel_b_ok.Text = "OK";
this.Sel_b_ok.Click += new System.EventHandler(this.Sel_b_ok_Click);
//
// listView1
//
this.listView1.AllowColumnReorder = true;
this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.Sel_id,
this.Sel_bez,
this.Sel_code});
this.listView1.Dock = System.Windows.Forms.DockStyle.Top;
this.listView1.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.listView1.ForeColor = System.Drawing.SystemColors.HotTrack;
this.listView1.FullRowSelect = true;
this.listView1.GridLines = true;
this.listView1.Location = new System.Drawing.Point(0, 0);
this.listView1.MultiSelect = false;
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(568, 312);
this.listView1.TabIndex = 2;
this.listView1.View = System.Windows.Forms.View.Details;
this.listView1.DoubleClick += new System.EventHandler(this.Sel_b_ok_Click);
this.listView1.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.listView1_ColumnClick);
this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
//
// Sel_id
//
this.Sel_id.Text = "ID";
this.Sel_id.Width = 50;
//
// Sel_bez
//
this.Sel_bez.Text = "Title";
this.Sel_bez.Width = 250;
//
// Sel_code
//
this.Sel_code.Text = "Code";
this.Sel_code.Width = 250;
//
// SelForm
//
this.AcceptButton = this.Sel_b_ok;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.Sel_b_cancel;
this.ClientSize = new System.Drawing.Size(568, 389);
this.Controls.Add(this.listView1);
this.Controls.Add(this.groupBox2);
this.MinimizeBox = false;
this.Name = "SelForm";
this.Text = "Selection";
this.groupBox2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
#region Get and Set flags and vars
public int GetID { get {return selid;}}
public ListView GetLV { get {return listView1;}}
#endregion
#region Callbacks
private void Sel_b_cancel_Click(object sender, System.EventArgs e)
{
Close();
}
private void Sel_b_ok_Click(object sender, System.EventArgs e)
{
if (!itemselected)
MessageBox.Show("please select an item first");
else
{
Accept(this, EventArgs.Empty);
this.Close();
}
}
private void listView1_SelectedIndexChanged(object sender, System.EventArgs e)
{
int k;
k = listView1.SelectedItems.Count;
if (k == 0)
itemselected = false;
else
{
itemselected = true;
foreach (ListViewItem lvi in listView1.SelectedItems)
selid = Convert.ToInt32(lvi.Text);
}
}
private void listView1_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
{
// Determine if clicked column is already the column that is being sorted.
if ( e.Column == lvwColumnSorter.SortColumn )
{
// Reverse the current sort direction for this column.
if (lvwColumnSorter.Order == SortOrder.Ascending)
{
lvwColumnSorter.Order = SortOrder.Descending;
}
else
{
lvwColumnSorter.Order = SortOrder.Ascending;
}
}
else
{
// Set the column number that is to be sorted; default to ascending.
lvwColumnSorter.SortColumn = e.Column;
lvwColumnSorter.Order = SortOrder.Ascending;
}
// Perform the sort with these new sort options.
this.listView1.Sort();
}
#endregion
}
#region List view sorter class
/// <summary>
/// This class is an implementation of the 'IComparer' interface.
/// </summary>
public class ListViewColumnSorter : IComparer
{
/// <summary>
/// Specifies the column to be sorted
/// </summary>
private int ColumnToSort;
/// <summary>
/// Specifies the order in which to sort (i.e. 'Ascending').
/// </summary>
private SortOrder OrderOfSort;
/// <summary>
/// Case insensitive comparer object
/// </summary> private NumberCaseInsensitiveComparer ObjectCompare;
private ImageTextComparer FirstObjectCompare;
private NumberCaseInsensitiveComparer ObjectCompare;
/// <summary>
/// Class constructor. Initializes various elements
/// </summary>
public ListViewColumnSorter()
{
// Initialize the column to '0'
ColumnToSort = 0;
// Initialize the sort order to 'none'
//OrderOfSort = SortOrder.None;
OrderOfSort = SortOrder.Ascending;
// Initialize my implementationof CaseInsensitiveComparer object
ObjectCompare = new NumberCaseInsensitiveComparer();
FirstObjectCompare = new ImageTextComparer();
} /// <summary>
/// This method is inherited from the IComparer interface.
/// It compares the two objects passed\
/// using a case insensitive comparison.
/// </summary>
/// <param name="x">First object to be compared</param>
/// <param name="y">Second object to be compared</param>
/// <returns>The result of the comparison. "0" if equal,
/// negative if 'x' is less than 'y' and positive
/// if 'x' is greater than 'y'</returns>
public int Compare(object x, object y)
{
int compareResult;
ListViewItem listviewX, listviewY;
// Cast the objects to be compared to ListViewItem objects
listviewX = (ListViewItem)x;
listviewY = (ListViewItem)y;
if (ColumnToSort == 0)
{
compareResult = FirstObjectCompare.Compare(x,y);
}
else
{
// Compare the two items
compareResult =
ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text,
listviewY.SubItems[ColumnToSort].Text);
}
// Calculate correct return value based on object comparison
if (OrderOfSort == SortOrder.Ascending)
{
// Ascending sort is selected,
// return normal result of compare operation
return compareResult;
}
else if (OrderOfSort == SortOrder.Descending)
{
// Descending sort is selected,
// return negative result of compare operation
return (-compareResult);
}
else
{
// Return '0' to indicate they are equal
return 0;
}
}
/// <summary>
/// Gets or sets the number of the column to which
/// to apply the sorting operation (Defaults to '0').
/// </summary>
public int SortColumn
{
set
{
ColumnToSort = value;
}
get
{
return ColumnToSort;
}
}
/// <summary>
/// Gets or sets the order of sorting to apply
/// (for example, 'Ascending' or 'Descending').
/// </summary>
public SortOrder Order
{
set
{
OrderOfSort = value;
}
get
{
return OrderOfSort;
}
}
}
public class ImageTextComparer : IComparer
{
//private CaseInsensitiveComparer ObjectCompare;
private NumberCaseInsensitiveComparer ObjectCompare;
public ImageTextComparer()
{
// Initialize the CaseInsensitiveComparer object
ObjectCompare = new NumberCaseInsensitiveComparer();
}
public int Compare(object x, object y)
{
//int compareResult;
int image1, image2;
ListViewItem listviewX, listviewY;
// Cast the objects to be compared to ListViewItem objects
listviewX = (ListViewItem)x;
image1 = listviewX.ImageIndex;
listviewY = (ListViewItem)y;
image2 = listviewY.ImageIndex;
if (image1 < image2)
{
return -1;
}
else if (image1 == image2)
{
return ObjectCompare.Compare(listviewX.Text,listviewY.Text);
}
else
{
return 1;
}
}
}
public class NumberCaseInsensitiveComparer : CaseInsensitiveComparer
{
public NumberCaseInsensitiveComparer ()
{
}
public new int Compare(object x, object y)
{
// in case x,y are strings and actually number,
// convert them to int and use the base.Compare for comparison
if ((x is System.String) && IsWholeNumber((string)x)
&& (y is System.String) && IsWholeNumber((string)y))
{
return base.Compare(System.Convert.ToInt32(x),
System.Convert.ToInt32(y));
}
else
{
return base.Compare(x,y);
}
}
private bool IsWholeNumber(string strNumber)
{ // use a regular expression to find out if string is actually a number
Regex objNotWholePattern=new Regex("[^0-9]");
return !objNotWholePattern.IsMatch(strNumber);
}
}
#endregion
}
| |
using UnityEngine;
using System.Collections.Generic;
using Ecosim.SceneData;
using Ecosim.SceneData.VegetationRules;
using Ecosim.SceneEditor.Helpers;
namespace Ecosim.SceneEditor
{
public class MapsPanel : Panel
{
public Scene scene;
public EditorCtrl ctrl;
private Vector2 scrollPos;
private GUIStyle tabNormal;
private GUIStyle tabSelected;
public Texture2D texture;
private PanelHelper helper;
private enum ETabs
{
AREAS,
HEIGHTMAP,
PARAMETERS,
VEGETATION,
SPECIES,
OBJECTS,
};
private ETabs tab;
/**
* Called when scene is set or changed in Editor
*/
public void Setup (EditorCtrl ctrl, Scene scene)
{
this.ctrl = ctrl;
this.scene = scene;
tabNormal = ctrl.listItem;
tabSelected = ctrl.listItemSelected;
}
private string imagePath = GameSettings.DesktopPath + "map.png";
public void RenderLoadTexture ()
{
GUILayout.BeginVertical (ctrl.skin.box);
{
GUILayout.Label ("Get data from image");
GUILayout.BeginHorizontal ();
{
GUILayout.Label ("Image path", GUILayout.Width (60));
imagePath = GUILayout.TextField (imagePath, GUILayout.Width (225));
if (GUILayout.Button ("Load")) { //, GUILayout.Width (45))) {
if (System.IO.File.Exists (imagePath)) {
try {
byte[] data = System.IO.File.ReadAllBytes (imagePath);
texture = new Texture2D (4, 4, TextureFormat.ARGB32, false);
texture.filterMode = FilterMode.Point;
if (!texture.LoadImage (data)) {
texture = null;
ctrl.StartOkDialog ("Invalid image. Please choose another image and try again.", null);
}
} catch (System.Exception e) {
Debug.LogException (e);
}
} else {
ctrl.StartOkDialog ("Image could not be found, please check the path and try again.", null);
}
}
//GUILayout.FlexibleSpace ();
}
GUILayout.EndHorizontal ();
if (texture != null)
{
GUILayout.BeginHorizontal ();
{
GUILayout.Label ("Size " + texture.width + " x " + texture.height, GUILayout.Width (80));
GUILayout.Label ("Horizontal offset ");
offsetXStr = GUILayout.TextField (offsetXStr, GUILayout.Width (40));
GUILayout.Label (" Vertical offset ");
offsetYStr = GUILayout.TextField (offsetYStr, GUILayout.Width (40));
int.TryParse (offsetXStr, out offsetX);
int.TryParse (offsetYStr, out offsetY);
//GUILayout.FlexibleSpace ();
}
GUILayout.EndHorizontal ();
GUILayout.Label (texture, GUILayout.Width (380), GUILayout.Height (380));
}
}
GUILayout.EndVertical ();
}
string offsetXStr = "0";
string offsetYStr = "0";
int offsetX = 0;
int offsetY = 0;
public float GetFromImage (int x, int y)
{
if (texture == null)
return 0f;
int xx = x + offsetX;
if ((xx < 0) || (xx >= texture.width))
return 0f;
int yy = y + offsetY;
if ((yy < 0) || (yy >= texture.height))
return 0f;
return texture.GetPixel (x + offsetX, y + offsetY).r;
}
bool RenderObjects (int mx, int my)
{
return false;
}
public void ResetEdit ()
{
if (helper != null) {
helper.Disable ();
helper = null;
}
}
private void StartAreas ()
{
ResetEdit ();
helper = new HandleAreas (ctrl, this, scene);
}
private void StartHeightmap ()
{
ResetEdit ();
helper = new HandleHeightmap (ctrl, this, scene);
}
private void StartParameters ()
{
ResetEdit ();
helper = new HandleParameters (ctrl, this, scene, null);
}
private void StartVegetation ()
{
ResetEdit ();
helper = new HandleVegetation (ctrl, this, scene);
}
private void StartSpecies ()
{
// TODO: Add Animals
ResetEdit ();
helper = new HandlePlants (ctrl, this, scene);
}
void StartObjects ()
{
ResetEdit ();
helper = new HandleObjects (ctrl, this, scene);
}
/**
* Called every frame when this panel is active
* It is guaranteed that setup has been called with
* a valid scene before the first call of Render.
*/
public bool Render (int mx, int my)
{
float width = 60f;
GUILayout.BeginHorizontal ();
{
if (GUILayout.Button ("Areas", (tab == ETabs.AREAS) ? tabSelected : tabNormal, GUILayout.Width (width))) {
tab = ETabs.AREAS;
StartAreas ();
}
if (GUILayout.Button ("Heightmap", (tab == ETabs.HEIGHTMAP) ? tabSelected : tabNormal, GUILayout.Width (width))) {
tab = ETabs.HEIGHTMAP;
StartHeightmap ();
}
if (GUILayout.Button ("Parameters", (tab == ETabs.PARAMETERS) ? tabSelected : tabNormal, GUILayout.Width (width))) {
tab = ETabs.PARAMETERS;
StartParameters ();
}
if (GUILayout.Button ("Vegetation", (tab == ETabs.VEGETATION) ? tabSelected : tabNormal, GUILayout.Width (width))) {
tab = ETabs.VEGETATION;
StartVegetation ();
}
if (GUILayout.Button("Species", (tab == ETabs.SPECIES) ? tabSelected : tabNormal, GUILayout.Width (width))) {
tab = ETabs.SPECIES;
StartSpecies();
}
if (GUILayout.Button ("Objects", (tab == ETabs.OBJECTS) ? tabSelected : tabNormal, GUILayout.Width (width))) {
tab = ETabs.OBJECTS;
StartObjects ();
}
GUILayout.FlexibleSpace ();
}
GUILayout.EndHorizontal ();
GUILayout.Space (4);
scrollPos = GUILayout.BeginScrollView (scrollPos, false, false);
GUILayout.BeginVertical ();
bool result = helper.Render (mx, my);
GUILayout.FlexibleSpace ();
GUILayout.EndVertical ();
GUILayout.EndScrollView ();
return result;
}
/* Called for extra edit sub-panel, will be called after Render */
public void RenderExtra (int mx, int my)
{
}
/* Called for extra side edit sub-panel, will be called after RenderExtra */
public void RenderSide (int mx, int my)
{
}
/* Returns true if a side panel is needed. Won't be called before RenderExtra has been called */
public bool NeedSidePanel ()
{
return false;
}
public bool IsAvailable ()
{
return (scene != null);
}
public void Activate ()
{
switch (tab) {
case ETabs.AREAS :
StartAreas ();
break;
case ETabs.HEIGHTMAP :
StartHeightmap ();
break;
case ETabs.PARAMETERS :
StartParameters ();
break;
case ETabs.VEGETATION :
StartVegetation ();
break;
case ETabs.SPECIES :
StartSpecies ();
break;
case ETabs.OBJECTS :
StartObjects ();
break;
}
}
public void Deactivate ()
{
ResetEdit ();
}
public void Update() {
if (helper != null) {
helper.Update();
}
}
}
}
| |
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 SofiaTransport.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>();
}
/// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and 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))
{
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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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.ActionDescriptor.ReturnType;
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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[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;
}
}
}
| |
namespace Caliburn.Testability
{
using System;
using System.Collections;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Collections.Generic;
/// <summary>
/// Represents a type that an item is bound to.
/// </summary>
public class BoundType
{
Type type;
string basePath;
readonly IDictionary<string, Type> hints;
/// <summary>
/// Initializes a new instance of the <see cref="BoundType"/> class.
/// </summary>
/// <param name="type">The type.</param>
public BoundType(Type type)
: this(type, string.Empty) { }
/// <summary>
/// Initializes a new instance of the <see cref="BoundType"/> class.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="basePath">The base path.</param>
public BoundType(Type type, string basePath)
: this (type, basePath, new Dictionary<string, Type>()) {}
/// <summary>
/// Initializes a new instance of the <see cref="BoundType"/> class.
/// Used internally to create an associated BoundType from a parent one.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="basePath">The base path.</param>
/// /// <param name="hints">Hints propagated from parent.</param>
public BoundType(Type type, string basePath, IDictionary<string, Type> hints)
{
this.type = type;
this.basePath = basePath;
this.hints = hints;
}
/// <summary>
/// Gets the type.
/// </summary>
/// <value>The type.</value>
public Type Type
{
get { return type; }
}
/// <summary>
/// Adds a hint for polymorphic type checking.
/// </summary>
/// <param name="propertyPath">The property path.</param>
/// <param name="hint">The hint.</param>
public void AddHint(string propertyPath, Type hint) {
if (hints.ContainsKey(propertyPath))
throw new Core.CaliburnException(string.Format("Hint for path '{0}' was already added", propertyPath));
//TODO: validate path part names
//TODO: validate hint congruency with reflected property type
hints.Add(propertyPath, hint);
}
/// <summary>
/// Validates the information against this type.
/// </summary>
/// <param name="element">The data bound element.</param>
/// <param name="boundProperty">The bound property.</param>
/// <param name="binding">The binding.</param>
/// <returns></returns>
public ValidatedProperty ValidateAgainst(IElement element, DependencyProperty boundProperty, Binding binding)
{
var propertyPath = binding.Path.Path;
if (PathIsBinding(propertyPath))
{
return new ValidatedProperty(
AreCompatibleTypes(element, boundProperty, type, binding),
GetFullPath(propertyPath)
);
}
if (propertyPath == "/")
{
type = DeriveTypeOfCollection(type);
basePath += "/";
return new ValidatedProperty(
null,
GetFullPath(propertyPath)
);
}
var propertyType = GetPropertyType(propertyPath);
if (propertyType == null)
{
return new ValidatedProperty(
Error.BadProperty(element, this, boundProperty, binding),
GetFullPath(propertyPath)
);
}
return new ValidatedProperty(
AreCompatibleTypes(element, boundProperty, propertyType, binding),
GetFullPath(propertyPath)
);
}
/// <summary>
/// Gets a type by association.
/// </summary>
/// <param name="propertyPath">The property path.</param>
/// <returns></returns>
public BoundType GetAssociatedType(string propertyPath)
{
if (PathIsBinding(propertyPath))
return this;
var associationType = GetPropertyType(propertyPath);
return associationType != null ? new BoundType(associationType, propertyPath, GetHintsToPropagate()) : null;
}
IDictionary<string, Type> GetHintsToPropagate() {
return hints
.Select(pair => new KeyValuePair<string, Type>(
StripLeadingPathPart(pair.Key),
pair.Value
))
.Where(pair => !string.IsNullOrEmpty(pair.Key))
.ToDictionary(pair => pair.Key, pair => pair.Value);
}
string StripLeadingPathPart(string propertyPath) {
var dotIndex = propertyPath.IndexOf('.');
if (dotIndex < 0) return null;
return propertyPath.Substring(dotIndex + 1);
}
/// <summary>
/// Gets the type of property.
/// </summary>
/// <param name="propertyPath">The property path.</param>
/// <returns></returns>
public Type GetPropertyType(string propertyPath)
{
var currentType = type;
var currentPrefixForHintLookup = string.Empty;
for (int i = 0; i < propertyPath.Length; i++)
{
if (propertyPath[i] == '[')
{
while (i < propertyPath.Length && propertyPath[i] != ']')
i++;
var info = currentType.GetProperty("Item")
?? GetInterfaceProperty("Item", currentType);
if (info == null) return null;
currentType = info.PropertyType;
currentPrefixForHintLookup += "Item.";
if (i >= propertyPath.Length) return currentType;
}
else if (propertyPath[i] == '/')
currentType = DeriveTypeOfCollection(currentType);
else
{
if (propertyPath[i] == '.') i++;
string propertyName = string.Empty;
while (i < propertyPath.Length && IsCharValidInPropertyName(propertyPath[i]))
{
propertyName += propertyPath[i];
i++;
}
Type hint;
if (hints.TryGetValue(currentPrefixForHintLookup + propertyName, out hint))
{
currentType = hint;
}
else
{
var info = currentType.GetProperty(
propertyName,
BindingFlags.DeclaredOnly | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance)
?? GetInterfaceProperty(propertyName, currentType)
?? currentType.GetProperties().Where(x => x.Name == propertyName).FirstOrDefault();
if (info == null) return null;
currentType = info.PropertyType;
}
currentPrefixForHintLookup += propertyName + ".";
if (i >= propertyPath.Length) return currentType;
i--;
}
}
return currentType;
}
static bool IsCharValidInPropertyName(char c)
{
return Char.IsLetterOrDigit(c) || c == '_';
}
/// <summary>
/// Derives the type of the collection.
/// </summary>
/// <param name="collection">The collection.</param>
/// <returns></returns>
static Type DeriveTypeOfCollection(Type collection)
{
return (from i in collection.GetInterfaces()
where typeof(IEnumerable).IsAssignableFrom(i)
&& i.IsGenericType
select i.GetGenericArguments()[0]).FirstOrDefault();
}
/// <summary>
/// Gets the interface property.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="type">The type.</param>
/// <returns></returns>
static PropertyInfo GetInterfaceProperty(string propertyName, Type type)
{
var interfaces = type.GetInterfaces();
foreach (var t in interfaces)
{
var propertyInfo = t.GetProperty(propertyName) ?? GetInterfaceProperty(propertyName, t);
if (propertyInfo != null)
return propertyInfo;
}
return null;
}
string GetFullPath(string propertyPath)
{
if (string.IsNullOrEmpty(basePath))
return propertyPath;
if (basePath.EndsWith("/") || propertyPath.StartsWith("/"))
return (basePath + propertyPath).Replace("//", "/");
return basePath + "." + propertyPath;
}
bool PathIsBinding(string propertyPath)
{
return string.IsNullOrEmpty(propertyPath) || propertyPath == ".";
}
IError AreCompatibleTypes(IElement element, DependencyProperty boundProperty, Type propertyType, Binding binding)
{
if (boundProperty == null) return null;
if (typeof(IEnumerable).IsAssignableFrom(boundProperty.PropertyType) &&
boundProperty.PropertyType != typeof(string) &&
!typeof(IEnumerable).IsAssignableFrom(propertyType))
return Error.NotEnumerable(element, this, boundProperty, binding);
return null;
}
}
}
| |
#define AWS_APM_API
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Amazon Software License (the "License").
// You may not use this file except in compliance with the
// License. A copy of the License is located at
//
// http://aws.amazon.com/asl/
//
// or in the "license" file accompanying this file. This file is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, express or implied. See the License
// for the specific language governing permissions and
// limitations under the License.
//
using System;
using Amazon.Runtime.Internal.Transform;
using Amazon.Util;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// This handler unmarshalls the HTTP response.
/// </summary>
public class Unmarshaller : PipelineHandler
{
private bool _supportsResponseLogging;
/// <summary>
/// The constructor for Unmarshaller.
/// </summary>
/// <param name="supportsResponseLogging">
/// Boolean value which indicated if the unmarshaller
/// handler supports response logging.
/// </param>
public Unmarshaller(bool supportsResponseLogging)
{
_supportsResponseLogging = supportsResponseLogging;
}
/// <summary>
/// Unmarshalls the response returned by the HttpHandler.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override void InvokeSync(IExecutionContext executionContext)
{
base.InvokeSync(executionContext);
if (executionContext.ResponseContext.HttpResponse.IsSuccessStatusCode)
{
// Unmarshall the http response.
Unmarshall(executionContext);
}
}
#if BCL45
/// <summary>
/// Unmarshalls the response returned by the HttpHandler.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
// Unmarshall the response
Unmarshall(executionContext);
return (T)executionContext.ResponseContext.Response;
}
#elif WIN_RT || WINDOWS_PHONE
/// <summary>
/// Unmarshalls the response returned by the HttpHandler.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
// Unmarshall the response
await UnmarshallAsync(executionContext).ConfigureAwait(false);
return (T)executionContext.ResponseContext.Response;
}
#elif AWS_APM_API
/// <summary>
/// Unmarshalls the response returned by the HttpHandler.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
protected override void InvokeAsyncCallback(IAsyncExecutionContext executionContext)
{
// Unmarshall the response if an exception hasn't occured
if (executionContext.ResponseContext.AsyncResult.Exception == null)
{
Unmarshall(ExecutionContext.CreateFromAsyncContext(executionContext));
}
base.InvokeAsyncCallback(executionContext);
}
#endif
/// <summary>
/// Unmarshalls the HTTP response.
/// </summary>
/// <param name="executionContext">
/// The execution context, it contains the request and response context.
/// </param>
private void Unmarshall(IExecutionContext executionContext)
{
var requestContext = executionContext.RequestContext;
var responseContext = executionContext.ResponseContext;
using (requestContext.Metrics.StartEvent(Metric.ResponseProcessingTime))
{
var unmarshaller = requestContext.Unmarshaller;
try
{
var readEntireResponse = _supportsResponseLogging;
var context = unmarshaller.CreateContext(responseContext.HttpResponse,
readEntireResponse,
responseContext.HttpResponse.ResponseBody.OpenResponse(),
requestContext.Metrics);
try
{
var response = UnmarshallResponse(context, requestContext);
responseContext.Response = response;
}
catch(Exception e)
{
// Rethrow Amazon service or client exceptions
if (e is AmazonServiceException ||
e is AmazonClientException)
{
throw;
}
// Else, there was an issue with the response body, throw AmazonUnmarshallingException
var requestId = responseContext.HttpResponse.GetHeaderValue(HeaderKeys.RequestIdHeader);
var body = context.ResponseBody;
throw new AmazonUnmarshallingException(requestId, lastKnownLocation: null, responseBody: body, innerException: e);
}
}
finally
{
if (!unmarshaller.HasStreamingProperty)
responseContext.HttpResponse.ResponseBody.Dispose();
}
}
}
#if WIN_RT || WINDOWS_PHONE
/// <summary>
/// Unmarshalls the HTTP response.
/// </summary>
/// <param name="executionContext">
/// The execution context, it contains the request and response context.
/// </param>
private async System.Threading.Tasks.Task UnmarshallAsync(IExecutionContext executionContext)
{
var requestContext = executionContext.RequestContext;
var responseContext = executionContext.ResponseContext;
using (requestContext.Metrics.StartEvent(Metric.ResponseProcessingTime))
{
var unmarshaller = requestContext.Unmarshaller;
try
{
var readEntireResponse = _supportsResponseLogging &&
(requestContext.ClientConfig.LogResponse || requestContext.ClientConfig.ReadEntireResponse
|| AWSConfigs.LoggingConfig.LogResponses != ResponseLoggingOption.Never);
var responseStream = await responseContext.HttpResponse.
ResponseBody.OpenResponseAsync().ConfigureAwait(false);
var context = unmarshaller.CreateContext(responseContext.HttpResponse,
readEntireResponse,
responseStream,
requestContext.Metrics);
var response = UnmarshallResponse(context, requestContext);
responseContext.Response = response;
}
finally
{
if (!unmarshaller.HasStreamingProperty)
responseContext.HttpResponse.ResponseBody.Dispose();
}
}
}
#endif
private AmazonWebServiceResponse UnmarshallResponse(UnmarshallerContext context,
IRequestContext requestContext)
{
var unmarshaller = requestContext.Unmarshaller;
AmazonWebServiceResponse response = null;
using (requestContext.Metrics.StartEvent(Metric.ResponseUnmarshallTime))
{
response = unmarshaller.UnmarshallResponse(context);
}
requestContext.Metrics.AddProperty(Metric.StatusCode, response.HttpStatusCode);
requestContext.Metrics.AddProperty(Metric.BytesProcessed, response.ContentLength);
if (response.ResponseMetadata != null)
{
requestContext.Metrics.AddProperty(Metric.AWSRequestID, response.ResponseMetadata.RequestId);
}
var logResponseBody = _supportsResponseLogging && (requestContext.ClientConfig.LogResponse ||
AWSConfigs.LoggingConfig.LogResponses == ResponseLoggingOption.Always);
if (logResponseBody)
{
this.Logger.DebugFormat("Received response: [{0}]", context.ResponseBody);
}
context.ValidateCRC32IfAvailable();
return response;
}
}
}
| |
// Copyright 2016 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.
using UnityEngine;
using System;
using System.Collections;
using System.IO;
using System.Runtime.InteropServices;
/// This is the main GVR audio class that communicates with the native code implementation of
/// the audio system. Native functions of the system can only be called through this class to
/// preserve the internal system functionality. Public function calls are *not* thread-safe.
public static class GvrAudio {
/// Audio system rendering quality.
public enum Quality {
Stereo = 0, /// Stereo-only rendering
Low = 1, /// Low quality binaural rendering (first-order HRTF)
High = 2 /// High quality binaural rendering (third-order HRTF)
}
/// Native audio spatializer type.
public enum SpatializerType {
Source = 0, /// 3D sound object.
Soundfield = 1 /// First-order ambisonic soundfield.
}
/// System sampling rate.
public static int SampleRate {
get { return sampleRate; }
}
private static int sampleRate = -1;
/// System number of output channels.
public static int NumChannels {
get { return numChannels; }
}
private static int numChannels = -1;
/// System number of frames per buffer.
public static int FramesPerBuffer {
get { return framesPerBuffer; }
}
private static int framesPerBuffer = -1;
/// Initializes the audio system with the current audio configuration.
/// @note This should only be called from the main Unity thread.
public static void Initialize (GvrAudioListener listener, Quality quality) {
if (!initialized) {
#if !UNITY_EDITOR && UNITY_ANDROID
SetApplicationState();
#endif
// Initialize the audio system.
AudioConfiguration config = AudioSettings.GetConfiguration();
sampleRate = config.sampleRate;
numChannels = (int)config.speakerMode;
framesPerBuffer = config.dspBufferSize;
if (numChannels != (int)AudioSpeakerMode.Stereo) {
Debug.LogError("Only 'Stereo' speaker mode is supported by GVR Audio.");
return;
}
Initialize(quality, sampleRate, numChannels, framesPerBuffer);
listenerTransform = listener.transform;
initialized = true;
} else if (listener.transform != listenerTransform) {
Debug.LogError("Only one GvrAudioListener component is allowed in the scene.");
GvrAudioListener.Destroy(listener);
}
}
/// Shuts down the audio system.
/// @note This should only be called from the main Unity thread.
public static void Shutdown (GvrAudioListener listener) {
if (initialized && listener.transform == listenerTransform) {
initialized = false;
Shutdown();
sampleRate = -1;
numChannels = -1;
framesPerBuffer = -1;
}
}
/// Updates the audio listener.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioListener (float globalGainDb, LayerMask occlusionMask,
float worldScale) {
if (initialized) {
occlusionMaskValue = occlusionMask.value;
worldScaleInverse = 1.0f / worldScale;
float globalGain = ConvertAmplitudeFromDb(globalGainDb);
Vector3 position = listenerTransform.position;
Quaternion rotation = listenerTransform.rotation;
ConvertAudioTransformFromUnity(ref position, ref rotation);
// Pass listener properties to the system.
SetListenerGain(globalGain);
SetListenerTransform(position.x, position.y, position.z, rotation.x, rotation.y, rotation.z,
rotation.w);
}
}
/// Creates a new first-order ambisonic soundfield with a unique id.
/// @note This should only be called from the main Unity thread.
public static int CreateAudioSoundfield () {
int soundfieldId = -1;
if (initialized) {
soundfieldId = CreateSoundfield(numFoaChannels);
}
return soundfieldId;
}
/// Destroys the soundfield with given |id|.
/// @note This should only be called from the main Unity thread.
public static void DestroyAudioSoundfield (int id) {
if (initialized) {
DestroySoundfield(id);
}
}
/// Updates the soundfield with given |id| and its properties.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioSoundfield (int id, Transform transform, float gainDb) {
if (initialized) {
float gain = ConvertAmplitudeFromDb(gainDb);
Vector3 position = transform.position;
Quaternion rotation = transform.rotation;
ConvertAudioTransformFromUnity(ref position, ref rotation);
// Pass the source properties to the audio system.
SetSoundfieldGain(id, gain);
SetSoundfieldRotation(id, rotation.x, rotation.y, rotation.z, rotation.w);
}
}
/// Creates a new audio source with a unique id.
/// @note This should only be called from the main Unity thread.
public static int CreateAudioSource (bool hrtfEnabled) {
int sourceId = -1;
if (initialized) {
sourceId = CreateSource(hrtfEnabled);
}
return sourceId;
}
/// Destroys the audio source with given |id|.
/// @note This should only be called from the main Unity thread.
public static void DestroyAudioSource (int id) {
if (initialized) {
DestroySource(id);
}
}
/// Updates the audio source with given |id| and its properties.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioSource (int id, Transform transform, bool bypassRoomEffects,
float gainDb, float spread, AudioRolloffMode rolloffMode,
float minDistance, float maxDistance, float alpha,
float sharpness, float occlusion) {
if (initialized) {
float gain = ConvertAmplitudeFromDb(gainDb);
Vector3 position = transform.position;
Quaternion rotation = transform.rotation;
ConvertAudioTransformFromUnity(ref position, ref rotation);
float spreadRad = Mathf.Deg2Rad * spread;
// Pass the source properties to the audio system.
SetSourceBypassRoomEffects(id, bypassRoomEffects);
SetSourceDirectivity(id, alpha, sharpness);
SetSourceGain(id, gain);
SetSourceOcclusionIntensity(id, occlusion);
if (rolloffMode != AudioRolloffMode.Custom) {
float maxDistanceScaled = worldScaleInverse * maxDistance;
float minDistanceScaled = worldScaleInverse * minDistance;
SetSourceDistanceAttenuationMethod(id, rolloffMode, minDistanceScaled, maxDistanceScaled);
}
SetSourceSpread(id, spreadRad);
SetSourceTransform(id, position.x, position.y, position.z, rotation.x, rotation.y, rotation.z,
rotation.w);
}
}
/// Creates a new room with a unique id.
/// @note This should only be called from the main Unity thread.
public static int CreateAudioRoom () {
int roomId = -1;
if (initialized) {
roomId = CreateRoom();
}
return roomId;
}
/// Destroys the room with given |id|.
/// @note This should only be called from the main Unity thread.
public static void DestroyAudioRoom (int id) {
if (initialized) {
DestroyRoom(id);
}
}
/// Updates the room effects of the environment with given |room| properties.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioRoom (int id, Transform transform,
GvrAudioRoom.SurfaceMaterial[] materials, float reflectivity,
float reverbGainDb, float reverbBrightness, float reverbTime,
Vector3 size) {
if (initialized) {
// Update room transform.
Vector3 position = transform.position;
Quaternion rotation = transform.rotation;
Vector3 scale = Vector3.Scale(size, transform.lossyScale);
scale = worldScaleInverse * new Vector3(Mathf.Abs(scale.x), Mathf.Abs(scale.y),
Mathf.Abs(scale.z));
ConvertAudioTransformFromUnity(ref position, ref rotation);
float reverbGain = ConvertAmplitudeFromDb(reverbGainDb);
SetRoomProperties(id, position.x, position.y, position.z, rotation.x, rotation.y, rotation.z,
rotation.w, scale.x, scale.y, scale.z, materials, reflectivity, reverbGain,
reverbBrightness, reverbTime);
}
}
/// Computes the occlusion intensity of a given |source| using point source detection.
/// @note This should only be called from the main Unity thread.
public static float ComputeOcclusion (Transform sourceTransform) {
float occlusion = 0.0f;
if (initialized) {
Vector3 listenerPosition = listenerTransform.position;
Vector3 sourceFromListener = sourceTransform.position - listenerPosition;
RaycastHit[] hits = Physics.RaycastAll(listenerPosition, sourceFromListener,
sourceFromListener.magnitude, occlusionMaskValue);
foreach (RaycastHit hit in hits) {
if (hit.transform != listenerTransform && hit.transform != sourceTransform) {
occlusion += 1.0f;
}
}
}
return occlusion;
}
/// Generates a set of points to draw a 2D polar pattern.
public static Vector2[] Generate2dPolarPattern (float alpha, float order, int resolution) {
Vector2[] points = new Vector2[resolution];
float interval = 2.0f * Mathf.PI / resolution;
for (int i = 0; i < resolution; ++i) {
float theta = i * interval;
// Magnitude |r| for |theta| in radians.
float r = Mathf.Pow(Mathf.Abs((1 - alpha) + alpha * Mathf.Cos(theta)), order);
points[i] = new Vector2(r * Mathf.Sin(theta), r * Mathf.Cos(theta));
}
return points;
}
/// Minimum distance threshold between |minDistance| and |maxDistance|.
public const float distanceEpsilon = 0.01f;
/// Max distance limit that can be set for volume rolloff.
public const float maxDistanceLimit = 1000000.0f;
/// Min distance limit that can be set for volume rolloff.
public const float minDistanceLimit = 990099.0f;
/// Maximum allowed gain value in decibels.
public const float maxGainDb = 24.0f;
/// Minimum allowed gain value in decibels.
public const float minGainDb = -24.0f;
/// Maximum allowed real world scale with respect to Unity.
public const float maxWorldScale = 1000.0f;
/// Minimum allowed real world scale with respect to Unity.
public const float minWorldScale = 0.001f;
/// Maximum allowed reverb brightness modifier value.
public const float maxReverbBrightness = 1.0f;
/// Minimum allowed reverb brightness modifier value.
public const float minReverbBrightness = -1.0f;
/// Maximum allowed reverb time modifier value.
public const float maxReverbTime = 3.0f;
/// Maximum allowed reflectivity multiplier of a room surface material.
public const float maxReflectivity = 2.0f;
/// Source occlusion detection rate in seconds.
public const float occlusionDetectionInterval = 0.2f;
// Number of first-order ambisonic input channels.
public const int numFoaChannels = 4;
/// Number of surfaces in a room.
public const int numRoomSurfaces = 6;
/// Converts given |db| value to its amplitude equivalent where 'dB = 20 * log10(amplitude)'.
private static float ConvertAmplitudeFromDb (float db) {
return Mathf.Pow(10.0f, 0.05f * db);
}
// Converts given |position| and |rotation| from Unity space to audio space.
private static void ConvertAudioTransformFromUnity (ref Vector3 position,
ref Quaternion rotation) {
pose.SetRightHanded(Matrix4x4.TRS(position, rotation, Vector3.one));
position = pose.Position * worldScaleInverse;
rotation = pose.Orientation;
}
// Denotes whether the system is initialized properly.
private static bool initialized = false;
// Listener transform.
private static Transform listenerTransform = null;
// Occlusion layer mask.
private static int occlusionMaskValue = -1;
// 3D pose instance to be used in transform space conversion.
private static MutablePose3D pose = new MutablePose3D();
// Inverted world scale.
private static float worldScaleInverse = 1.0f;
#if !UNITY_EDITOR && UNITY_ANDROID
private const string GvrAudioClass = "com.google.vr.audio.unity.GvrAudio";
private static void SetApplicationState() {
using (var gvrAudioClass = Gvr.Internal.BaseAndroidDevice.GetClass(GvrAudioClass)) {
Gvr.Internal.BaseAndroidDevice.CallStaticMethod(gvrAudioClass, "setUnityApplicationState");
}
}
#endif
#if UNITY_IOS
private const string pluginName = "__Internal";
#else
private const string pluginName = "audioplugingvrunity";
#endif
[DllImport(pluginName)]
private static extern void SetListenerGain (float gain);
[DllImport(pluginName)]
private static extern void SetListenerTransform (float px, float py, float pz, float qx, float qy,
float qz, float qw);
// Soundfield handlers.
[DllImport(pluginName)]
private static extern int CreateSoundfield (int numChannels);
[DllImport(pluginName)]
private static extern void DestroySoundfield (int soundfieldId);
[DllImport(pluginName)]
private static extern void SetSoundfieldGain(int soundfieldId, float gain);
[DllImport(pluginName)]
private static extern void SetSoundfieldRotation(int soundfieldId, float qx, float qy, float qz,
float qw);
// Source handlers.
[DllImport(pluginName)]
private static extern int CreateSource (bool enableHrtf);
[DllImport(pluginName)]
private static extern void DestroySource (int sourceId);
[DllImport(pluginName)]
private static extern void SetSourceBypassRoomEffects (int sourceId, bool bypassRoomEffects);
[DllImport(pluginName)]
private static extern void SetSourceDirectivity (int sourceId, float alpha, float order);
[DllImport(pluginName)]
private static extern void SetSourceDistanceAttenuationMethod (int sourceId,
AudioRolloffMode rolloffMode,
float minDistance,
float maxDistance);
[DllImport(pluginName)]
private static extern void SetSourceGain (int sourceId, float gain);
[DllImport(pluginName)]
private static extern void SetSourceOcclusionIntensity (int sourceId, float intensity);
[DllImport(pluginName)]
private static extern void SetSourceSpread (int sourceId, float spreadRad);
[DllImport(pluginName)]
private static extern void SetSourceTransform (int sourceId, float px, float py, float pz,
float qx, float qy, float qz, float qw);
// Room handlers.
[DllImport(pluginName)]
private static extern int CreateRoom ();
[DllImport(pluginName)]
private static extern void DestroyRoom (int roomId);
[DllImport(pluginName)]
private static extern void SetRoomProperties (int roomId, float px, float py, float pz, float qx,
float qy, float qz, float qw, float dx, float dy,
float dz,
GvrAudioRoom.SurfaceMaterial[] materialNames,
float reflectionScalar, float reverbGain,
float reverbBrightness, float reverbTime);
// System handlers.
[DllImport(pluginName)]
private static extern void Initialize (Quality quality, int sampleRate, int numChannels,
int framesPerBuffer);
[DllImport(pluginName)]
private static extern void Shutdown ();
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// 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.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Gl
{
/// <summary>
/// [GL] Value of GL_PERFQUERY_SINGLE_CONTEXT_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[Log(BitmaskName = "GL")]
public const int PERFQUERY_SINGLE_CONTEXT_INTEL = 0x00000000;
/// <summary>
/// [GL] Value of GL_PERFQUERY_GLOBAL_CONTEXT_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[Log(BitmaskName = "GL")]
public const int PERFQUERY_GLOBAL_CONTEXT_INTEL = 0x00000001;
/// <summary>
/// [GL] Value of GL_PERFQUERY_WAIT_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_WAIT_INTEL = 0x83FB;
/// <summary>
/// [GL] Value of GL_PERFQUERY_FLUSH_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_FLUSH_INTEL = 0x83FA;
/// <summary>
/// [GL] Value of GL_PERFQUERY_DONOT_FLUSH_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_DONOT_FLUSH_INTEL = 0x83F9;
/// <summary>
/// [GL] Value of GL_PERFQUERY_COUNTER_EVENT_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_COUNTER_EVENT_INTEL = 0x94F0;
/// <summary>
/// [GL] Value of GL_PERFQUERY_COUNTER_DURATION_NORM_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_COUNTER_DURATION_NORM_INTEL = 0x94F1;
/// <summary>
/// [GL] Value of GL_PERFQUERY_COUNTER_DURATION_RAW_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_COUNTER_DURATION_RAW_INTEL = 0x94F2;
/// <summary>
/// [GL] Value of GL_PERFQUERY_COUNTER_THROUGHPUT_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_COUNTER_THROUGHPUT_INTEL = 0x94F3;
/// <summary>
/// [GL] Value of GL_PERFQUERY_COUNTER_RAW_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_COUNTER_RAW_INTEL = 0x94F4;
/// <summary>
/// [GL] Value of GL_PERFQUERY_COUNTER_TIMESTAMP_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_COUNTER_TIMESTAMP_INTEL = 0x94F5;
/// <summary>
/// [GL] Value of GL_PERFQUERY_COUNTER_DATA_UINT32_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_COUNTER_DATA_UINT32_INTEL = 0x94F8;
/// <summary>
/// [GL] Value of GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_COUNTER_DATA_UINT64_INTEL = 0x94F9;
/// <summary>
/// [GL] Value of GL_PERFQUERY_COUNTER_DATA_FLOAT_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_COUNTER_DATA_FLOAT_INTEL = 0x94FA;
/// <summary>
/// [GL] Value of GL_PERFQUERY_COUNTER_DATA_DOUBLE_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_COUNTER_DATA_DOUBLE_INTEL = 0x94FB;
/// <summary>
/// [GL] Value of GL_PERFQUERY_COUNTER_DATA_BOOL32_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_COUNTER_DATA_BOOL32_INTEL = 0x94FC;
/// <summary>
/// [GL] Value of GL_PERFQUERY_QUERY_NAME_LENGTH_MAX_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_QUERY_NAME_LENGTH_MAX_INTEL = 0x94FD;
/// <summary>
/// [GL] Value of GL_PERFQUERY_COUNTER_NAME_LENGTH_MAX_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_COUNTER_NAME_LENGTH_MAX_INTEL = 0x94FE;
/// <summary>
/// [GL] Value of GL_PERFQUERY_COUNTER_DESC_LENGTH_MAX_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_COUNTER_DESC_LENGTH_MAX_INTEL = 0x94FF;
/// <summary>
/// [GL] Value of GL_PERFQUERY_GPA_EXTENDED_COUNTERS_INTEL symbol.
/// </summary>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public const int PERFQUERY_GPA_EXTENDED_COUNTERS_INTEL = 0x9500;
/// <summary>
/// [GL] glBeginPerfQueryINTEL: Binding for glBeginPerfQueryINTEL.
/// </summary>
/// <param name="queryHandle">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public static void BeginPerfQueryINTEL(uint queryHandle)
{
Debug.Assert(Delegates.pglBeginPerfQueryINTEL != null, "pglBeginPerfQueryINTEL not implemented");
Delegates.pglBeginPerfQueryINTEL(queryHandle);
LogCommand("glBeginPerfQueryINTEL", null, queryHandle );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glCreatePerfQueryINTEL: Binding for glCreatePerfQueryINTEL.
/// </summary>
/// <param name="queryId">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="queryHandle">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public static void CreatePerfQueryINTEL(uint queryId, uint[] queryHandle)
{
unsafe {
fixed (uint* p_queryHandle = queryHandle)
{
Debug.Assert(Delegates.pglCreatePerfQueryINTEL != null, "pglCreatePerfQueryINTEL not implemented");
Delegates.pglCreatePerfQueryINTEL(queryId, p_queryHandle);
LogCommand("glCreatePerfQueryINTEL", null, queryId, queryHandle );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glDeletePerfQueryINTEL: Binding for glDeletePerfQueryINTEL.
/// </summary>
/// <param name="queryHandle">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public static void DeletePerfQueryINTEL(uint queryHandle)
{
Debug.Assert(Delegates.pglDeletePerfQueryINTEL != null, "pglDeletePerfQueryINTEL not implemented");
Delegates.pglDeletePerfQueryINTEL(queryHandle);
LogCommand("glDeletePerfQueryINTEL", null, queryHandle );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glEndPerfQueryINTEL: Binding for glEndPerfQueryINTEL.
/// </summary>
/// <param name="queryHandle">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public static void EndPerfQueryINTEL(uint queryHandle)
{
Debug.Assert(Delegates.pglEndPerfQueryINTEL != null, "pglEndPerfQueryINTEL not implemented");
Delegates.pglEndPerfQueryINTEL(queryHandle);
LogCommand("glEndPerfQueryINTEL", null, queryHandle );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetFirstPerfQueryIdINTEL: Binding for glGetFirstPerfQueryIdINTEL.
/// </summary>
/// <param name="queryId">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public static void GetFirstPerfQueryIdINTEL([Out] uint[] queryId)
{
unsafe {
fixed (uint* p_queryId = queryId)
{
Debug.Assert(Delegates.pglGetFirstPerfQueryIdINTEL != null, "pglGetFirstPerfQueryIdINTEL not implemented");
Delegates.pglGetFirstPerfQueryIdINTEL(p_queryId);
LogCommand("glGetFirstPerfQueryIdINTEL", null, queryId );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetNextPerfQueryIdINTEL: Binding for glGetNextPerfQueryIdINTEL.
/// </summary>
/// <param name="queryId">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="nextQueryId">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public static void GetNextPerfQueryIdINTEL(uint queryId, [Out] uint[] nextQueryId)
{
unsafe {
fixed (uint* p_nextQueryId = nextQueryId)
{
Debug.Assert(Delegates.pglGetNextPerfQueryIdINTEL != null, "pglGetNextPerfQueryIdINTEL not implemented");
Delegates.pglGetNextPerfQueryIdINTEL(queryId, p_nextQueryId);
LogCommand("glGetNextPerfQueryIdINTEL", null, queryId, nextQueryId );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetPerfCounterInfoINTEL: Binding for glGetPerfCounterInfoINTEL.
/// </summary>
/// <param name="queryId">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="counterId">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="counterNameLength">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="counterName">
/// A <see cref="T:string"/>.
/// </param>
/// <param name="counterDescLength">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="counterDesc">
/// A <see cref="T:string"/>.
/// </param>
/// <param name="counterOffset">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="counterDataSize">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="counterTypeEnum">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="counterDataTypeEnum">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="rawCounterMaxValue">
/// A <see cref="T:ulong[]"/>.
/// </param>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public static void GetPerfCounterInfoINTEL(uint queryId, uint counterId, uint counterNameLength, string counterName, uint counterDescLength, string counterDesc, [Out] uint[] counterOffset, [Out] uint[] counterDataSize, [Out] uint[] counterTypeEnum, [Out] uint[] counterDataTypeEnum, [Out] ulong[] rawCounterMaxValue)
{
unsafe {
fixed (uint* p_counterOffset = counterOffset)
fixed (uint* p_counterDataSize = counterDataSize)
fixed (uint* p_counterTypeEnum = counterTypeEnum)
fixed (uint* p_counterDataTypeEnum = counterDataTypeEnum)
fixed (ulong* p_rawCounterMaxValue = rawCounterMaxValue)
{
Debug.Assert(Delegates.pglGetPerfCounterInfoINTEL != null, "pglGetPerfCounterInfoINTEL not implemented");
Delegates.pglGetPerfCounterInfoINTEL(queryId, counterId, counterNameLength, counterName, counterDescLength, counterDesc, p_counterOffset, p_counterDataSize, p_counterTypeEnum, p_counterDataTypeEnum, p_rawCounterMaxValue);
LogCommand("glGetPerfCounterInfoINTEL", null, queryId, counterId, counterNameLength, counterName, counterDescLength, counterDesc, counterOffset, counterDataSize, counterTypeEnum, counterDataTypeEnum, rawCounterMaxValue );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetPerfQueryDataINTEL: Binding for glGetPerfQueryDataINTEL.
/// </summary>
/// <param name="queryHandle">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="flags">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="dataSize">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="data">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="bytesWritten">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public static void GetPerfQueryDataINTEL(uint queryHandle, uint flags, int dataSize, IntPtr data, [Out] uint[] bytesWritten)
{
unsafe {
fixed (uint* p_bytesWritten = bytesWritten)
{
Debug.Assert(Delegates.pglGetPerfQueryDataINTEL != null, "pglGetPerfQueryDataINTEL not implemented");
Delegates.pglGetPerfQueryDataINTEL(queryHandle, flags, dataSize, data.ToPointer(), p_bytesWritten);
LogCommand("glGetPerfQueryDataINTEL", null, queryHandle, flags, dataSize, data, bytesWritten );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetPerfQueryDataINTEL: Binding for glGetPerfQueryDataINTEL.
/// </summary>
/// <param name="queryHandle">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="flags">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="dataSize">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="data">
/// A <see cref="T:object"/>.
/// </param>
/// <param name="bytesWritten">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public static void GetPerfQueryDataINTEL(uint queryHandle, uint flags, int dataSize, object data, [Out] uint[] bytesWritten)
{
GCHandle pin_data = GCHandle.Alloc(data, GCHandleType.Pinned);
try {
GetPerfQueryDataINTEL(queryHandle, flags, dataSize, pin_data.AddrOfPinnedObject(), bytesWritten);
} finally {
pin_data.Free();
}
}
/// <summary>
/// [GL] glGetPerfQueryIdByNameINTEL: Binding for glGetPerfQueryIdByNameINTEL.
/// </summary>
/// <param name="queryName">
/// A <see cref="T:string"/>.
/// </param>
/// <param name="queryId">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public static void GetPerfQueryIdByNameINTEL(string queryName, [Out] uint[] queryId)
{
unsafe {
fixed (uint* p_queryId = queryId)
{
Debug.Assert(Delegates.pglGetPerfQueryIdByNameINTEL != null, "pglGetPerfQueryIdByNameINTEL not implemented");
Delegates.pglGetPerfQueryIdByNameINTEL(queryName, p_queryId);
LogCommand("glGetPerfQueryIdByNameINTEL", null, queryName, queryId );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetPerfQueryInfoINTEL: Binding for glGetPerfQueryInfoINTEL.
/// </summary>
/// <param name="queryId">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="queryNameLength">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="queryName">
/// A <see cref="T:string"/>.
/// </param>
/// <param name="dataSize">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="noCounters">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="noInstances">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="capsMask">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
public static void GetPerfQueryInfoINTEL(uint queryId, uint queryNameLength, string queryName, [Out] uint[] dataSize, [Out] uint[] noCounters, [Out] uint[] noInstances, [Out] uint[] capsMask)
{
unsafe {
fixed (uint* p_dataSize = dataSize)
fixed (uint* p_noCounters = noCounters)
fixed (uint* p_noInstances = noInstances)
fixed (uint* p_capsMask = capsMask)
{
Debug.Assert(Delegates.pglGetPerfQueryInfoINTEL != null, "pglGetPerfQueryInfoINTEL not implemented");
Delegates.pglGetPerfQueryInfoINTEL(queryId, queryNameLength, queryName, p_dataSize, p_noCounters, p_noInstances, p_capsMask);
LogCommand("glGetPerfQueryInfoINTEL", null, queryId, queryNameLength, queryName, dataSize, noCounters, noInstances, capsMask );
}
}
DebugCheckErrors(null);
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glBeginPerfQueryINTEL(uint queryHandle);
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[ThreadStatic]
internal static glBeginPerfQueryINTEL pglBeginPerfQueryINTEL;
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glCreatePerfQueryINTEL(uint queryId, uint* queryHandle);
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[ThreadStatic]
internal static glCreatePerfQueryINTEL pglCreatePerfQueryINTEL;
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glDeletePerfQueryINTEL(uint queryHandle);
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[ThreadStatic]
internal static glDeletePerfQueryINTEL pglDeletePerfQueryINTEL;
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glEndPerfQueryINTEL(uint queryHandle);
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[ThreadStatic]
internal static glEndPerfQueryINTEL pglEndPerfQueryINTEL;
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetFirstPerfQueryIdINTEL(uint* queryId);
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[ThreadStatic]
internal static glGetFirstPerfQueryIdINTEL pglGetFirstPerfQueryIdINTEL;
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetNextPerfQueryIdINTEL(uint queryId, uint* nextQueryId);
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[ThreadStatic]
internal static glGetNextPerfQueryIdINTEL pglGetNextPerfQueryIdINTEL;
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetPerfCounterInfoINTEL(uint queryId, uint counterId, uint counterNameLength, string counterName, uint counterDescLength, string counterDesc, uint* counterOffset, uint* counterDataSize, uint* counterTypeEnum, uint* counterDataTypeEnum, ulong* rawCounterMaxValue);
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[ThreadStatic]
internal static glGetPerfCounterInfoINTEL pglGetPerfCounterInfoINTEL;
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetPerfQueryDataINTEL(uint queryHandle, uint flags, int dataSize, void* data, uint* bytesWritten);
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[ThreadStatic]
internal static glGetPerfQueryDataINTEL pglGetPerfQueryDataINTEL;
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetPerfQueryIdByNameINTEL(string queryName, uint* queryId);
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[ThreadStatic]
internal static glGetPerfQueryIdByNameINTEL pglGetPerfQueryIdByNameINTEL;
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetPerfQueryInfoINTEL(uint queryId, uint queryNameLength, string queryName, uint* dataSize, uint* noCounters, uint* noInstances, uint* capsMask);
[RequiredByFeature("GL_INTEL_performance_query", Api = "gl|glcore|gles2")]
[ThreadStatic]
internal static glGetPerfQueryInfoINTEL pglGetPerfQueryInfoINTEL;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.IO
{
/// <summary>
/// Contains extension methods for conversion between WinRT streams and managed streams.
/// This class is the public facade for the stream adapters library.
/// </summary>
public static class WindowsRuntimeStreamExtensions
{
#region Constants and static Fields
private const Int32 DefaultBufferSize = 16384; // = 0x4000 = 16 KBytes.
private static ConditionalWeakTable<Object, Stream> s_winRtToNetFxAdapterMap
= new ConditionalWeakTable<Object, Stream>();
private static ConditionalWeakTable<Stream, NetFxToWinRtStreamAdapter> s_netFxToWinRtAdapterMap
= new ConditionalWeakTable<Stream, NetFxToWinRtStreamAdapter>();
#endregion Constants and static Fields
#region Helpers
#if DEBUG
private static void AssertMapContains<TKey, TValue>(ConditionalWeakTable<TKey, TValue> map, TKey key, TValue value,
bool valueMayBeWrappedInBufferedStream)
where TKey : class
where TValue : class
{
TValue valueInMap;
Debug.Assert(key != null);
bool hasValueForKey = map.TryGetValue(key, out valueInMap);
Debug.Assert(hasValueForKey);
if (valueMayBeWrappedInBufferedStream)
{
BufferedStream bufferedValueInMap = valueInMap as BufferedStream;
Debug.Assert(Object.ReferenceEquals(value, valueInMap)
|| (bufferedValueInMap != null && Object.ReferenceEquals(value, bufferedValueInMap.UnderlyingStream)));
}
else
{
Debug.Assert(Object.ReferenceEquals(value, valueInMap));
}
}
#endif // DEBUG
private static void EnsureAdapterBufferSize(Stream adapter, Int32 requiredBufferSize, String methodName)
{
Contract.Requires(adapter != null);
Contract.Requires(!String.IsNullOrWhiteSpace(methodName));
Int32 currentBufferSize = 0;
BufferedStream bufferedAdapter = adapter as BufferedStream;
if (bufferedAdapter != null)
currentBufferSize = bufferedAdapter.BufferSize;
if (requiredBufferSize != currentBufferSize)
{
if (requiredBufferSize == 0)
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_CannotChangeBufferSizeOfWinRtStreamAdapterToZero, methodName));
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_CannotChangeBufferSizeOfWinRtStreamAdapter, methodName));
}
}
#endregion Helpers
#region WinRt-to-NetFx conversion
[CLSCompliant(false)]
public static Stream AsStreamForRead(this IInputStream windowsRuntimeStream)
{
return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStreamForRead", forceBufferSize: false);
}
[CLSCompliant(false)]
public static Stream AsStreamForRead(this IInputStream windowsRuntimeStream, Int32 bufferSize)
{
return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStreamForRead", forceBufferSize: true);
}
[CLSCompliant(false)]
public static Stream AsStreamForWrite(this IOutputStream windowsRuntimeStream)
{
return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStreamForWrite", forceBufferSize: false);
}
[CLSCompliant(false)]
public static Stream AsStreamForWrite(this IOutputStream windowsRuntimeStream, Int32 bufferSize)
{
return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStreamForWrite", forceBufferSize: true);
}
[CLSCompliant(false)]
public static Stream AsStream(this IRandomAccessStream windowsRuntimeStream)
{
return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStream", forceBufferSize: false);
}
[CLSCompliant(false)]
public static Stream AsStream(this IRandomAccessStream windowsRuntimeStream, Int32 bufferSize)
{
return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStream", forceBufferSize: true);
}
private static Stream AsStreamInternal(Object windowsRuntimeStream, Int32 bufferSize, String invokedMethodName, bool forceBufferSize)
{
if (windowsRuntimeStream == null)
throw new ArgumentNullException("windowsRuntimeStream");
if (bufferSize < 0)
throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_WinRtAdapterBufferSizeMayNotBeNegative);
Contract.Requires(!String.IsNullOrWhiteSpace(invokedMethodName));
Contract.Ensures(Contract.Result<Stream>() != null);
Contract.EndContractBlock();
// If the WinRT stream is actually a wrapped managed stream, we will unwrap it and return the original.
// In that case we do not need to put the wrapper into the map.
// We currently do capability-based adapter selection for WinRt->NetFx, but not vice versa (time constraints).
// Once we added the reverse direction, we will be able replce this entire section with just a few lines.
NetFxToWinRtStreamAdapter sAdptr = windowsRuntimeStream as NetFxToWinRtStreamAdapter;
if (sAdptr != null)
{
Stream wrappedNetFxStream = sAdptr.GetManagedStream();
if (wrappedNetFxStream == null)
throw new ObjectDisposedException("windowsRuntimeStream", SR.ObjectDisposed_CannotPerformOperation);
#if DEBUG // In Chk builds, verify that the original managed stream is correctly entered into the NetFx->WinRT map:
AssertMapContains(s_netFxToWinRtAdapterMap, wrappedNetFxStream, sAdptr,
valueMayBeWrappedInBufferedStream: false);
#endif // DEBUG
return wrappedNetFxStream;
}
// We have a real WinRT stream.
Stream adapter;
bool adapterExists = s_winRtToNetFxAdapterMap.TryGetValue(windowsRuntimeStream, out adapter);
// There is already an adapter:
if (adapterExists)
{
Debug.Assert((adapter is BufferedStream && ((BufferedStream)adapter).UnderlyingStream is WinRtToNetFxStreamAdapter)
|| (adapter is WinRtToNetFxStreamAdapter));
if (forceBufferSize)
EnsureAdapterBufferSize(adapter, bufferSize, invokedMethodName);
return adapter;
}
// We do not have an adapter for this WinRT stream yet and we need to create one.
// Do that in a thread-safe manner in a separate method such that we only have to pay for the compiler allocating
// the required closure if this code path is hit:
return AsStreamInternalFactoryHelper(windowsRuntimeStream, bufferSize, invokedMethodName, forceBufferSize);
}
// Separate method so we only pay for closure allocation if this code is executed:
private static Stream WinRtToNetFxAdapterMap_GetValue(Object winRtStream)
{
return s_winRtToNetFxAdapterMap.GetValue(winRtStream, (wrtStr) => WinRtToNetFxStreamAdapter.Create(wrtStr));
}
// Separate method so we only pay for closure allocation if this code is executed:
private static Stream WinRtToNetFxAdapterMap_GetValue(Object winRtStream, Int32 bufferSize)
{
return s_winRtToNetFxAdapterMap.GetValue(winRtStream, (wrtStr) => new BufferedStream(WinRtToNetFxStreamAdapter.Create(wrtStr), bufferSize));
}
private static Stream AsStreamInternalFactoryHelper(Object windowsRuntimeStream, Int32 bufferSize, String invokedMethodName, bool forceBufferSize)
{
Contract.Requires(windowsRuntimeStream != null);
Contract.Requires(bufferSize >= 0);
Contract.Requires(!String.IsNullOrWhiteSpace(invokedMethodName));
Contract.Ensures(Contract.Result<Stream>() != null);
Contract.EndContractBlock();
// Get the adapter for this windowsRuntimeStream again (it may have been created concurrently).
// If none exists yet, create a new one:
Stream adapter = (bufferSize == 0)
? WinRtToNetFxAdapterMap_GetValue(windowsRuntimeStream)
: WinRtToNetFxAdapterMap_GetValue(windowsRuntimeStream, bufferSize);
Debug.Assert(adapter != null);
Debug.Assert((adapter is BufferedStream && ((BufferedStream)adapter).UnderlyingStream is WinRtToNetFxStreamAdapter)
|| (adapter is WinRtToNetFxStreamAdapter));
if (forceBufferSize)
EnsureAdapterBufferSize(adapter, bufferSize, invokedMethodName);
WinRtToNetFxStreamAdapter actualAdapter = adapter as WinRtToNetFxStreamAdapter;
if (actualAdapter == null)
actualAdapter = ((BufferedStream)adapter).UnderlyingStream as WinRtToNetFxStreamAdapter;
actualAdapter.SetWonInitializationRace();
return adapter;
}
#endregion WinRt-to-NetFx conversion
#region NetFx-to-WinRt conversion
[CLSCompliant(false)]
public static IInputStream AsInputStream(this Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
if (!stream.CanRead)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotReadableToInputStream);
Contract.Ensures(Contract.Result<IInputStream>() != null);
Contract.EndContractBlock();
Object adapter = AsWindowsRuntimeStreamInternal(stream);
IInputStream winRtStream = adapter as IInputStream;
Debug.Assert(winRtStream != null);
return winRtStream;
}
[CLSCompliant(false)]
public static IOutputStream AsOutputStream(this Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
if (!stream.CanWrite)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotWritableToOutputStream);
Contract.Ensures(Contract.Result<IOutputStream>() != null);
Contract.EndContractBlock();
Object adapter = AsWindowsRuntimeStreamInternal(stream);
IOutputStream winRtStream = adapter as IOutputStream;
Debug.Assert(winRtStream != null);
return winRtStream;
}
[CLSCompliant(false)]
public static IRandomAccessStream AsRandomAccessStream(this Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
if (!stream.CanSeek)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotSeekableToRandomAccessStream);
Contract.Ensures(Contract.Result<IRandomAccessStream>() != null);
Contract.EndContractBlock();
Object adapter = AsWindowsRuntimeStreamInternal(stream);
IRandomAccessStream winRtStream = adapter as IRandomAccessStream;
Debug.Assert(winRtStream != null);
return winRtStream;
}
private static Object AsWindowsRuntimeStreamInternal(Stream stream)
{
Contract.Ensures(Contract.Result<Object>() != null);
Contract.EndContractBlock();
// Check to see if the managed stream is actually a wrapper of a WinRT stream:
// (This can be either an adapter directly, or an adapter wrapped in a BufferedStream.)
WinRtToNetFxStreamAdapter sAdptr = stream as WinRtToNetFxStreamAdapter;
if (sAdptr == null)
{
BufferedStream buffAdptr = stream as BufferedStream;
if (buffAdptr != null)
sAdptr = buffAdptr.UnderlyingStream as WinRtToNetFxStreamAdapter;
}
// If the managed stream us actually a WinRT stream, we will unwrap it and return the original.
// In that case we do not need to put the wrapper into the map.
if (sAdptr != null)
{
Object wrappedWinRtStream = sAdptr.GetWindowsRuntimeStream<Object>();
if (wrappedWinRtStream == null)
throw new ObjectDisposedException("stream", SR.ObjectDisposed_CannotPerformOperation);
#if DEBUG // In Chk builds, verify that the original WinRT stream is correctly entered into the WinRT->NetFx map:
AssertMapContains(s_winRtToNetFxAdapterMap, wrappedWinRtStream, sAdptr, valueMayBeWrappedInBufferedStream: true);
#endif // DEBUG
return wrappedWinRtStream;
}
// We have a real managed Stream.
// See if the managed stream already has an adapter:
NetFxToWinRtStreamAdapter adapter;
bool adapterExists = s_netFxToWinRtAdapterMap.TryGetValue(stream, out adapter);
// There is already an adapter:
if (adapterExists)
return adapter;
// We do not have an adapter for this managed stream yet and we need to create one.
// Do that in a thread-safe manner in a separate method such that we only have to pay for the compiler allocating
// the required closure if this code path is hit:
return AsWindowsRuntimeStreamInternalFactoryHelper(stream);
}
private static NetFxToWinRtStreamAdapter AsWindowsRuntimeStreamInternalFactoryHelper(Stream stream)
{
Contract.Requires(stream != null);
Contract.Ensures(Contract.Result<NetFxToWinRtStreamAdapter>() != null);
Contract.EndContractBlock();
// Get the adapter for managed stream again (it may have been created concurrently).
// If none exists yet, create a new one:
NetFxToWinRtStreamAdapter adapter = s_netFxToWinRtAdapterMap.GetValue(stream, (str) => NetFxToWinRtStreamAdapter.Create(str));
Debug.Assert(adapter != null);
adapter.SetWonInitializationRace();
return adapter;
}
#endregion NetFx-to-WinRt conversion
} // class WindowsRuntimeStreamExtensions
} // namespace
// WindowsRuntimeStreamExtensions.cs
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Text;
namespace SME.VHDL.Templates
{
/// <summary>
/// Base template for VHDL files.
/// </summary>
public abstract class BaseTemplate
{
/// <summary>
/// Writes the template to the VHDL file.
/// </summary>
public virtual string TransformText()
{
GenerationEnvironment = null;
Write("Template not implemented");
return GenerationEnvironment.ToString();
}
/// <summary>
/// Initializes the template.
/// </summary>
public virtual void Initialize()
{
}
/// <summary>
/// The string builder used for writing the files.
/// </summary>
private StringBuilder builder;
/// <summary>
/// The current session.
/// </summary>
private IDictionary<string, object> session;
/// <summary>
/// The collection of errors.
/// </summary>
private CompilerErrorCollection errors;
/// <summary>
/// The current indentation.
/// </summary>
private string currentIndent = string.Empty;
/// <summary>
/// Stack of indentations.
/// </summary>
private Stack<int> indents;
/// <summary>
/// Helper class with static methods.
/// </summary>
private ToStringInstanceHelper _toStringHelper = new ToStringInstanceHelper();
/// <summary>
/// Gets or sets the current session.
/// </summary>
public virtual IDictionary<string, object> Session
{
get
{
return session;
}
set
{
session = value;
}
}
/// <summary>
/// Gets or sets the current builder.
/// </summary>
public StringBuilder GenerationEnvironment
{
get
{
if ((builder == null))
{
builder = new StringBuilder();
}
return builder;
}
set
{
builder = value;
}
}
/// <summary>
/// Gets or sets the current collection of errors.
/// </summary>
protected CompilerErrorCollection Errors
{
get
{
if ((errors == null))
{
errors = new CompilerErrorCollection();
}
return errors;
}
}
/// <summary>
/// Gets the current indentation.
/// </summary>
public string CurrentIndent
{
get
{
return currentIndent;
}
}
/// <summary>
/// Gets the current stack of indentations.
/// </summary>
private Stack<int> Indents
{
get
{
if ((indents == null))
{
indents = new Stack<int>();
}
return indents;
}
}
/// <summary>
/// Gets the string helper class.
/// </summary>
public ToStringInstanceHelper ToStringHelper
{
get
{
return _toStringHelper;
}
}
/// <summary>
/// Adds the given error to the collection of errors.
/// </summary>
/// <param name="message">The given error.</param>
public void Error(string message)
{
Errors.Add(new CompilerError(null, -1, -1, null, message));
}
/// <summary>
/// Adds the given warning to the collection of warnings.
/// </summary>
/// <param name="message">The given warning.</param>
public void Warning(string message)
{
CompilerError val = new CompilerError(null, -1, -1, null, message);
val.IsWarning = true;
Errors.Add(val);
}
/// <summary>
/// Pops an indentation from the stack of indentations.
/// </summary>
public string PopIndent()
{
if ((Indents.Count == 0))
{
return string.Empty;
}
int lastPos = (currentIndent.Length - Indents.Pop());
string last = currentIndent.Substring(lastPos);
currentIndent = currentIndent.Substring(0, lastPos);
return last;
}
/// <summary>
/// Pushes the given indentation to the stack of indentations.
/// </summary>
/// <param name="indent">The given indentation.</param>
public void PushIndent(string indent)
{
Indents.Push(indent.Length);
currentIndent = (currentIndent + indent);
}
/// <summary>
/// Clears the current indentation.
/// </summary>
public void ClearIndent()
{
currentIndent = string.Empty;
Indents.Clear();
}
/// <summary>
/// Writes the given text to the builder.
/// </summary>
/// <param name="textToAppend">The text to write.</param>
public void Write(string textToAppend)
{
GenerationEnvironment.Append(textToAppend);
}
/// <summary>
/// Applies the given objects to the format string and writes it to the builder.
/// </summary>
/// <param name="format">The given format string.</param>
/// <param name="args">The given objects to apply to the format string.</param>
public void Write(string format, params object[] args)
{
GenerationEnvironment.AppendFormat(format, args);
}
/// <summary>
/// Writes the given text to the builder along with a newline.
/// </summary>
/// <param name="textToAppend">The text to write.</param>
public void WriteLine(string textToAppend)
{
GenerationEnvironment.Append(currentIndent);
GenerationEnvironment.AppendLine(textToAppend);
}
/// <summary>
/// Applies the given objects to the format string and writes it to the builder along with a newline.
/// </summary>
/// <param name="format">The given format string.</param>
/// <param name="args">The given objects to apply to the format string.</param>
public void WriteLine(string format, params object[] args)
{
GenerationEnvironment.Append(currentIndent);
GenerationEnvironment.AppendFormat(format, args);
GenerationEnvironment.AppendLine();
}
/// <summary>
/// Helper class containing static methods for manipulating strings.
/// </summary>
public class ToStringInstanceHelper
{
/// <summary>
/// The format provider for formatting strings.
/// </summary>
private System.IFormatProvider formatProvider = System.Globalization.CultureInfo.InvariantCulture;
/// <summary>
/// Gets or sets the format provider.
/// </summary>
public System.IFormatProvider FormatProvider
{
get
{
return formatProvider;
}
set
{
if ((value != null))
{
formatProvider = value;
}
}
}
/// <summary>
/// Converts the given object to a string, along with culture given by the format provider.
/// </summary>
/// <param name="objectToConvert">The object to convert.</param>
public string ToStringWithCulture(object objectToConvert)
{
if ((objectToConvert == null))
{
throw new ArgumentNullException("objectToConvert");
}
Type type = objectToConvert.GetType();
Type iConvertibleType = typeof(IConvertible);
if (iConvertibleType.IsAssignableFrom(type))
{
return ((IConvertible)(objectToConvert)).ToString(formatProvider);
}
System.Reflection.MethodInfo methInfo = type.GetMethod("ToString", new Type[] {
iConvertibleType});
if ((methInfo != null))
{
return ((string)(methInfo.Invoke(objectToConvert, new object[] {
formatProvider})));
}
return objectToConvert.ToString();
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="ParserStreamGeometryContext.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This class is used to compress a Path to BAML.
//
// At compile-time this api is called into to "flatten" graphics calls to a BinaryWriter
// At run-time this api is called into to rehydrate the flattened graphics calls
// via invoking methods on a supplied StreamGeometryContext.
//
// Via this compression - we reduce the time spent parsing at startup, we create smaller baml,
// and we reduce creation of temporary strings.
//
//---------------------------------------------------------------------------
using MS.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Security.Permissions;
using System.IO;
using MS.Utility;
#if PBTCOMPILER
using MS.Internal.Markup;
namespace MS.Internal.Markup
#else
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using MS.Internal.PresentationCore;
namespace MS.Internal.Media
#endif
{
/// <summary>
/// ParserStreamGeometryContext
/// </summary>
internal class ParserStreamGeometryContext : StreamGeometryContext
{
enum ParserGeometryContextOpCodes : byte
{
BeginFigure = 0,
LineTo = 1,
QuadraticBezierTo = 2,
BezierTo = 3,
PolyLineTo = 4,
PolyQuadraticBezierTo = 5,
PolyBezierTo = 6,
ArcTo = 7,
Closed = 8,
FillRule = 9,
}
private const byte HighNibble = 0xF0;
private const byte LowNibble = 0x0F;
private const byte SetBool1 = 0x10; // 00010000
private const byte SetBool2 = 0x20; // 00100000
private const byte SetBool3 = 0x40; // 01000000
private const byte SetBool4 = 0x80; // 10000000
#region Constructors
/// <summary>
/// This constructor exists to prevent external derivation
/// </summary>
internal ParserStreamGeometryContext(BinaryWriter bw)
{
_bw = bw;
}
#endregion Constructors
#region internal Methods
#if PRESENTATION_CORE
internal void SetFillRule(FillRule fillRule)
#else
internal void SetFillRule(bool boolFillRule)
#endif
{
#if PRESENTATION_CORE
bool boolFillRule = FillRuleToBool(fillRule);
#endif
byte packedByte = PackByte(ParserGeometryContextOpCodes.FillRule, boolFillRule, false);
_bw.Write(packedByte);
}
/// <summary>
/// BeginFigure - Start a new figure.
/// </summary>
/// <remarks>
/// Stored as [PointAndTwoBools] (see SerializepointAndTwoBools method).
/// </remarks>
public override void BeginFigure(Point startPoint, bool isFilled, bool isClosed)
{
//
// We need to update the BeginFigure block of the last figure (if
// there was one).
//
FinishFigure();
_startPoint = startPoint;
_isFilled = isFilled;
_isClosed = isClosed;
_figureStreamPosition = CurrentStreamPosition;
//
// This will be overwritten later when we start the next figure (i.e. when we're sure isClosed isn't
// going to change). We write it out now to ensure that we reserve exactly the right amount of space.
// Note that the number of bytes written is dependant on the particular value of startPoint, since
// we can compress doubles when they are in fact integral.
//
SerializePointAndTwoBools(ParserGeometryContextOpCodes.BeginFigure, startPoint, isFilled, isClosed);
}
/// <summary>
/// LineTo - append a LineTo to the current figure.
/// </summary>
/// <remarks>
/// Stored as [PointAndTwoBools] (see SerializepointAndTwoBools method).
/// </remarks>
public override void LineTo(Point point, bool isStroked, bool isSmoothJoin)
{
SerializePointAndTwoBools(ParserGeometryContextOpCodes.LineTo, point, isStroked, isSmoothJoin);
}
/// <summary>
/// QuadraticBezierTo - append a QuadraticBezierTo to the current figure.
/// </summary>
/// <remarks>
/// Stored as [PointAndTwoBools] [Number] [Number]
/// </remarks>
public override void QuadraticBezierTo(Point point1, Point point2, bool isStroked, bool isSmoothJoin)
{
SerializePointAndTwoBools(ParserGeometryContextOpCodes.QuadraticBezierTo, point1, isStroked, isSmoothJoin);
XamlSerializationHelper.WriteDouble(_bw, point2.X);
XamlSerializationHelper.WriteDouble(_bw, point2.Y);
}
/// <summary>
/// BezierTo - apply a BezierTo to the current figure.
/// </summary>
/// <remarks>
/// Stored as [PointAndTwoBools] [Number] [Number] [Number] [Number]
/// </remarks>
public override void BezierTo(Point point1, Point point2, Point point3, bool isStroked, bool isSmoothJoin)
{
SerializePointAndTwoBools(ParserGeometryContextOpCodes.BezierTo, point1, isStroked, isSmoothJoin);
XamlSerializationHelper.WriteDouble(_bw, point2.X);
XamlSerializationHelper.WriteDouble(_bw, point2.Y);
XamlSerializationHelper.WriteDouble(_bw, point3.X);
XamlSerializationHelper.WriteDouble(_bw, point3.Y);
}
/// <summary>
/// PolyLineTo - append a PolyLineTo to the current figure.
/// </summary>
/// <remarks>
/// Stored as [ListOfPointAndTwoBools] (see SerializeListOfPointsAndTwoBools method).
/// </remarks>
public override void PolyLineTo(IList<Point> points, bool isStroked, bool isSmoothJoin)
{
SerializeListOfPointsAndTwoBools(ParserGeometryContextOpCodes.PolyLineTo, points, isStroked, isSmoothJoin);
}
/// <summary>
/// PolyQuadraticBezierTo - append a PolyQuadraticBezierTo to the current figure.
/// </summary>
/// <remarks>
/// Stored as [ListOfPointAndTwoBools] (see SerializeListOfPointsAndTwoBools method).
/// </remarks>
public override void PolyQuadraticBezierTo(IList<Point> points, bool isStroked, bool isSmoothJoin)
{
SerializeListOfPointsAndTwoBools(ParserGeometryContextOpCodes.PolyQuadraticBezierTo, points, isStroked, isSmoothJoin);
}
/// <summary>
/// PolyBezierTo - append a PolyBezierTo to the current figure.
/// </summary>
/// <remarks>
/// Stored as [ListOfPointAndTwoBools] (see SerializeListOfPointsAndTwoBools method).
/// </remarks>
public override void PolyBezierTo(IList<Point> points, bool isStroked, bool isSmoothJoin)
{
SerializeListOfPointsAndTwoBools(ParserGeometryContextOpCodes.PolyBezierTo, points, isStroked, isSmoothJoin);
}
/// <summary>
/// ArcTo - append an ArcTo to the current figure.
/// </summary>
/// <remarks>
/// Stored as [PointAndTwoBools] [Packed byte for isLargeArc and sweepDirection] [Pair of Numbers for Size] [Pair of Numbers for rotation Angle]
///
/// Also note that we've special cased this method signature to avoid moving the enum for SweepDirection into PBT (will require codegen changes).
/// </remarks>
#if PBTCOMPILER
public override void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, bool sweepDirection, bool isStroked, bool isSmoothJoin)
#else
public override void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection, bool isStroked, bool isSmoothJoin)
#endif
{
SerializePointAndTwoBools(ParserGeometryContextOpCodes.ArcTo, point, isStroked, isSmoothJoin);
//
// Pack isLargeArc & sweepDirection into a single byte.
//
byte packMe = 0;
if (isLargeArc)
{
packMe = LowNibble;
}
#if PBTCOMPILER
if (sweepDirection)
#else
if (SweepToBool(sweepDirection))
#endif
{
packMe |= HighNibble;
}
_bw.Write(packMe);
//
// Write out Size & Rotation Angle.
//
XamlSerializationHelper.WriteDouble(_bw, size.Width);
XamlSerializationHelper.WriteDouble(_bw, size.Height);
XamlSerializationHelper.WriteDouble(_bw, rotationAngle);
}
internal bool FigurePending
{
get
{
return (_figureStreamPosition > -1);
}
}
internal int CurrentStreamPosition
{
get
{
return checked((int)_bw.Seek(0, SeekOrigin.Current));
}
}
internal void FinishFigure()
{
if (FigurePending)
{
int currentOffset = CurrentStreamPosition;
//
// Go back and overwrite our existing begin figure block. See comment in BeginFigure.
//
_bw.Seek(_figureStreamPosition, SeekOrigin.Begin);
SerializePointAndTwoBools(ParserGeometryContextOpCodes.BeginFigure, _startPoint, _isFilled, _isClosed);
_bw.Seek(currentOffset, SeekOrigin.Begin);
}
}
/// <summary>
/// This is the same as the Close call:
/// Closes the Context and flushes the content.
/// Afterwards the Context can not be used anymore.
/// This call does not require all Push calls to have been Popped.
/// </summary>
internal override void DisposeCore()
{
}
/// <summary>
/// SetClosedState - Sets the current closed state of the figure.
/// </summary>
internal override void SetClosedState(bool closed)
{
_isClosed = closed;
}
/// <summary>
/// Mark that the stream is Done.
/// </summary>
internal void MarkEOF()
{
//
// We need to update the BeginFigure block of the last figure (if
// there was one).
//
FinishFigure();
_bw.Write((byte) ParserGeometryContextOpCodes.Closed);
}
#if PRESENTATION_CORE
internal static void Deserialize(BinaryReader br, StreamGeometryContext sc, StreamGeometry geometry)
{
bool closed = false;
Byte currentByte;
while (!closed)
{
currentByte = br.ReadByte();
ParserGeometryContextOpCodes opCode = UnPackOpCode(currentByte);
switch(opCode)
{
case ParserGeometryContextOpCodes.FillRule :
DeserializeFillRule(br, currentByte, geometry);
break;
case ParserGeometryContextOpCodes.BeginFigure :
DeserializeBeginFigure(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.LineTo :
DeserializeLineTo(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.QuadraticBezierTo :
DeserializeQuadraticBezierTo(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.BezierTo :
DeserializeBezierTo(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.PolyLineTo :
DeserializePolyLineTo(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.PolyQuadraticBezierTo :
DeserializePolyQuadraticBezierTo(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.PolyBezierTo :
DeserializePolyBezierTo(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.ArcTo :
DeserializeArcTo(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.Closed :
closed = true;
break;
}
}
}
#endif
#endregion internal Methods
#region private Methods
//
// Deserialization Methods.
//
// These are only required at "runtime" - therefore only in PRESENTATION_CORE
//
#if PRESENTATION_CORE
private static void DeserializeFillRule(BinaryReader br, Byte firstByte, StreamGeometry geometry)
{
bool boolFillRule;
bool unused;
FillRule fillRule;
UnPackBools(firstByte, out boolFillRule, out unused);
fillRule = BoolToFillRule(boolFillRule);
geometry.FillRule = fillRule;
}
private static void DeserializeBeginFigure(BinaryReader br, Byte firstByte, StreamGeometryContext sc)
{
Point point;
bool isFilled;
bool isClosed;
DeserializePointAndTwoBools(br, firstByte, out point, out isFilled, out isClosed);
sc.BeginFigure(point, isFilled, isClosed);
}
private static void DeserializeLineTo(BinaryReader br, Byte firstByte, StreamGeometryContext sc)
{
Point point;
bool isStroked;
bool isSmoothJoin;
DeserializePointAndTwoBools(br, firstByte, out point, out isStroked, out isSmoothJoin);
sc.LineTo(point, isStroked, isSmoothJoin);
}
private static void DeserializeQuadraticBezierTo(BinaryReader br, byte firstByte, StreamGeometryContext sc)
{
Point point1;
Point point2 = new Point();
bool isStroked;
bool isSmoothJoin;
DeserializePointAndTwoBools(br, firstByte, out point1, out isStroked, out isSmoothJoin);
point2.X = XamlSerializationHelper.ReadDouble(br);
point2.Y = XamlSerializationHelper.ReadDouble(br);
sc.QuadraticBezierTo(point1, point2, isStroked, isSmoothJoin);
}
private static void DeserializeBezierTo(BinaryReader br, byte firstByte, StreamGeometryContext sc)
{
Point point1;
Point point2 = new Point();
Point point3 = new Point();
bool isStroked;
bool isSmoothJoin;
DeserializePointAndTwoBools(br, firstByte, out point1, out isStroked, out isSmoothJoin);
point2.X = XamlSerializationHelper.ReadDouble(br);
point2.Y = XamlSerializationHelper.ReadDouble(br);
point3.X = XamlSerializationHelper.ReadDouble(br);
point3.Y = XamlSerializationHelper.ReadDouble(br);
sc.BezierTo(point1, point2, point3, isStroked, isSmoothJoin);
}
private static void DeserializePolyLineTo(BinaryReader br, Byte firstByte, StreamGeometryContext sc)
{
bool isStroked;
bool isSmoothJoin;
IList<Point> points;
points = DeserializeListOfPointsAndTwoBools(br, firstByte, out isStroked, out isSmoothJoin);
sc.PolyLineTo(points, isStroked, isSmoothJoin);
}
private static void DeserializePolyQuadraticBezierTo(BinaryReader br, Byte firstByte, StreamGeometryContext sc)
{
bool isStroked;
bool isSmoothJoin;
IList<Point> points;
points = DeserializeListOfPointsAndTwoBools(br, firstByte, out isStroked, out isSmoothJoin);
sc.PolyQuadraticBezierTo(points, isStroked, isSmoothJoin);
}
private static void DeserializePolyBezierTo(BinaryReader br, Byte firstByte, StreamGeometryContext sc)
{
bool isStroked;
bool isSmoothJoin;
IList<Point> points;
points = DeserializeListOfPointsAndTwoBools(br, firstByte, out isStroked, out isSmoothJoin);
sc.PolyBezierTo(points, isStroked, isSmoothJoin);
}
private static void DeserializeArcTo(BinaryReader br, byte firstByte, StreamGeometryContext sc)
{
Point point;
Size size = new Size();
double rotationAngle;
bool isStroked;
bool isSmoothJoin;
bool isLargeArc;
SweepDirection sweepDirection;
DeserializePointAndTwoBools(br, firstByte, out point, out isStroked, out isSmoothJoin);
// Read the packed byte for isLargeArd & sweepDirection.
//
// Pack isLargeArc & sweepDirection into a signle byte.
//
byte packedByte = br.ReadByte();
isLargeArc = ((packedByte & LowNibble) != 0);
sweepDirection = BoolToSweep(((packedByte & HighNibble) != 0));
size.Width = XamlSerializationHelper.ReadDouble(br);
size.Height = XamlSerializationHelper.ReadDouble(br);
rotationAngle = XamlSerializationHelper.ReadDouble(br);
sc.ArcTo(point, size, rotationAngle, isLargeArc, sweepDirection, isStroked, isSmoothJoin);
}
//
// Private Deserialization helpers.
//
private static void UnPackBools(byte packedByte, out bool bool1, out bool bool2)
{
bool1 = (packedByte & SetBool1) != 0;
bool2 = (packedByte & SetBool2) != 0;
}
private static void UnPackBools(byte packedByte, out bool bool1, out bool bool2, out bool bool3, out bool bool4)
{
bool1 = (packedByte & SetBool1) != 0;
bool2 = (packedByte & SetBool2) != 0;
bool3 = (packedByte & SetBool3) != 0;
bool4 = (packedByte & SetBool4) != 0;
}
private static ParserGeometryContextOpCodes UnPackOpCode(byte packedByte)
{
return ((ParserGeometryContextOpCodes) (packedByte & 0x0F));
}
private static IList<Point> DeserializeListOfPointsAndTwoBools(BinaryReader br, Byte firstByte, out bool bool1, out bool bool2)
{
int count;
IList<Point> points;
Point point;
// Pack the two bools into one byte
UnPackBools(firstByte, out bool1, out bool2);
count = br.ReadInt32();
points = new List<Point>(count);
for(int i = 0; i < count; i++)
{
point = new Point(XamlSerializationHelper.ReadDouble(br),
XamlSerializationHelper.ReadDouble(br));
points.Add(point);
}
return points;
}
private static void DeserializePointAndTwoBools(BinaryReader br, Byte firstByte, out Point point, out bool bool1, out bool bool2)
{
bool isScaledIntegerX = false;
bool isScaledIntegerY = false;
UnPackBools(firstByte, out bool1, out bool2, out isScaledIntegerX, out isScaledIntegerY);
point = new Point(DeserializeDouble(br, isScaledIntegerX),
DeserializeDouble(br, isScaledIntegerY));
}
private static Double DeserializeDouble(BinaryReader br, bool isScaledInt)
{
if (isScaledInt)
{
return XamlSerializationHelper.ReadScaledInteger(br);
}
else
{
return XamlSerializationHelper.ReadDouble(br);
}
}
//
// Private serialization helpers
//
private static SweepDirection BoolToSweep(bool value)
{
if(!value)
return SweepDirection.Counterclockwise;
else
return SweepDirection.Clockwise;
}
private static bool SweepToBool(SweepDirection sweep)
{
if (sweep == SweepDirection.Counterclockwise)
return false;
else
return true;
}
private static FillRule BoolToFillRule(bool value)
{
if(!value)
return FillRule.EvenOdd;
else
return FillRule.Nonzero;
}
private static bool FillRuleToBool(FillRule fill)
{
if (fill == FillRule.EvenOdd)
return false;
else
return true;
}
#endif
//
// SerializePointAndTwoBools
//
// Binary format is :
//
// <Byte+OpCode> <Number1> <Number2>
//
// Where :
// <Byte+OpCode> := OpCode + bool1 + bool2 + isScaledIntegerX + isScaledIntegerY
// <NumberN> := <ScaledInteger> | <SerializationFloatTypeForSpecialNumbers> | <SerializationFloatType.Double+Double>
// <SerializationFloatTypeForSpecialNumbers> := <SerializationFloatType.Zero> | <SerializationFloatType.One> | <SerializationFloatType.MinusOne>
// <SerializationFloatType.Double+Double> := <SerializationFloatType.Double> <Double>
//
// By packing the flags for isScaledInteger into the first byte - we save 2 extra bytes per number for the common case.
//
// As a result - most LineTo's (and other operations) will be stored in 9 bytes.
// Some LineTo's will be 6 (or even sometimes 3)
// Max LineTo will be 19 (two doubles).
private void SerializePointAndTwoBools(ParserGeometryContextOpCodes opCode,
Point point,
bool bool1,
bool bool2)
{
int intValueX = 0;
int intValueY = 0;
bool isScaledIntegerX, isScaledIntegerY;
isScaledIntegerX = XamlSerializationHelper.CanConvertToInteger(point.X, ref intValueX);
isScaledIntegerY = XamlSerializationHelper.CanConvertToInteger(point.Y, ref intValueY);
_bw.Write(PackByte(opCode, bool1, bool2, isScaledIntegerX, isScaledIntegerY));
SerializeDouble(point.X, isScaledIntegerX, intValueX);
SerializeDouble(point.Y, isScaledIntegerY, intValueY);
}
// SerializeListOfPointsAndTwoBools
//
// Binary format is :
//
// <Byte+OpCode> <Count> <Number1> ... <NumberN>
//
// <Byte+OpCode> := OpCode + bool1 + bool2
// <Count> := int32
// <NumberN> := <SerializationFloatType.ScaledInteger+Integer> | <SerializationFloatTypeForSpecialNumbers> | <SerializationFloatType.Double+Double>
private void SerializeListOfPointsAndTwoBools(ParserGeometryContextOpCodes opCode, IList<Point> points, bool bool1, bool bool2)
{
// Pack the two bools into one byte
Byte packedByte = PackByte(opCode, bool1, bool2);
_bw.Write(packedByte);
// Write the count.
_bw.Write(points.Count);
// Write out all the Points
for(int i = 0; i < points.Count; i++)
{
XamlSerializationHelper.WriteDouble(_bw, points[i].X);
XamlSerializationHelper.WriteDouble(_bw, points[i].Y);
}
}
private void SerializeDouble(double value, bool isScaledInt, int scaledIntValue)
{
if (isScaledInt)
{
_bw.Write(scaledIntValue);
}
else
{
XamlSerializationHelper.WriteDouble(_bw, value);
}
}
private static byte PackByte(ParserGeometryContextOpCodes opCode, bool bool1, bool bool2)
{
return PackByte(opCode, bool1, bool2, false, false);
}
// PackByte
// Packs an op-code, and up to 4 booleans into a single byte.
//
// Binary format is :
// First 4 bits map directly to the op-code.
// Next 4 bits map to booleans 1 - 4.
//
// Like this:
//
// 7| 6 | 5 | 4 | 3 | 2 | 1 | 0 |
// <B4>|<B3>|<B2>|<B1><- Op Code ->
//
private static byte PackByte(ParserGeometryContextOpCodes opCode, bool bool1, bool bool2, bool bool3, bool bool4)
{
byte packedByte = (byte) opCode;
if (packedByte >= 16)
{
throw new ArgumentException(SR.Get(SRID.UnknownPathOperationType));
}
if (bool1)
{
packedByte |= SetBool1;
}
if (bool2)
{
packedByte |= SetBool2;
}
if (bool3)
{
packedByte |= SetBool3;
}
if (bool4)
{
packedByte |= SetBool4;
}
return packedByte;
}
#endregion private Methods
private BinaryWriter _bw;
Point _startPoint;
bool _isClosed;
bool _isFilled;
int _figureStreamPosition = -1;
}
}
| |
// Author: Robert Scheller, Melissa Lucash
using Landis.Core;
using Landis.SpatialModeling;
using Landis.Utilities;
using Landis.Library.BiomassCohorts;
using System;
using System.Collections.Generic;
namespace Landis.Extension.Succession.Biomass
{
/// <summary>
/// A helper class.
/// </summary>
public class HarvestReductions
{
private string prescription;
private double coarseLitterReduction;
private double fineLitterReduction;
//private double somReduction;
private double cohortWoodReduction;
private double cohortLeafReduction;
public string Name
{
get
{
return prescription;
}
set
{
if (value != null)
prescription = value;
}
}
public double CoarseLitterReduction
{
get
{
return coarseLitterReduction;
}
set
{
if (value < 0.0 || value > 1.0)
throw new InputValueException(value.ToString(), "Coarse litter reduction due to fire must be between 0 and 1.0");
coarseLitterReduction = value;
}
}
public double FineLitterReduction
{
get
{
return fineLitterReduction;
}
set
{
if (value < 0.0 || value > 1.0)
throw new InputValueException(value.ToString(), "Fine litter reduction due to fire must be between 0 and 1.0");
fineLitterReduction = value;
}
}
public double CohortWoodReduction
{
get
{
return cohortWoodReduction;
}
set
{
if (value < 0.0 || value > 1.0)
throw new InputValueException(value.ToString(), "Cohort wood reduction due to fire must be between 0 and 1.0");
cohortWoodReduction = value;
}
}
public double CohortLeafReduction
{
get
{
return cohortLeafReduction;
}
set
{
if (value < 0.0 || value > 1.0)
throw new InputValueException(value.ToString(), "Cohort wood reduction due to fire must be between 0 and 1.0");
cohortLeafReduction = value;
}
}
//public double SOMReduction
//{
// get
// {
// return somReduction;
// }
// set
// {
// if (value < 0.0 || value > 1.0)
// throw new InputValueException(value.ToString(), "Soil Organic Matter (SOM) reduction due to fire must be between 0 and 1.0");
// somReduction = value;
// }
//}
//---------------------------------------------------------------------
public HarvestReductions()
{
this.prescription = "";
this.CoarseLitterReduction = 0.0;
this.FineLitterReduction = 0.0;
this.CohortLeafReduction = 0.0;
this.CohortWoodReduction = 0.0;
//this.SOMReduction = 0.0;
}
}
public class HarvestEffects
{
public static double GetCohortWoodRemoval(ActiveSite site)
{
double woodRemoval = 1.0; // Default is 100% removal
if (SiteVars.HarvestPrescriptionName == null)
return woodRemoval;
foreach (HarvestReductions prescription in PlugIn.Parameters.HarvestReductionsTable)
{
//PlugIn.ModelCore.UI.WriteLine(" PrescriptionName={0}, Site={1}.", prescription.PrescriptionName, site);
if (ComparePrescriptionNames(prescription.Name, site))
//SiteVars.HarvestPrescriptionName[site].Trim() == prescription.Name.Trim())
{
woodRemoval = prescription.CohortWoodReduction;
}
}
return woodRemoval;
}
public static double GetCohortLeafRemoval(ActiveSite site)
{
double leafRemoval = 0.0; // Default is 0% removal
if (SiteVars.HarvestPrescriptionName == null)
return leafRemoval;
foreach (HarvestReductions prescription in PlugIn.Parameters.HarvestReductionsTable)
{
if (ComparePrescriptionNames(prescription.Name, site))
//SiteVars.HarvestPrescriptionName[site].Trim() == prescription.Name.Trim())
{
leafRemoval = prescription.CohortLeafReduction;
}
}
return leafRemoval;
}
//---------------------------------------------------------------------
/// <summary>
/// Computes fire effects on litter, coarse woody debris, duff layer.
/// </summary>
public static void ReduceLayers(Site site)
{
//PlugIn.ModelCore.UI.WriteLine(" Calculating harvest induced layer reductions...");
double litterLossMultiplier = 0.0;
double woodLossMultiplier = 0.0;
//double som_Multiplier = 0.0;
string harvestPrescriptionName = SiteVars.HarvestPrescriptionName[site];
bool found = false;
foreach (HarvestReductions prescriptionTableEntry in PlugIn.Parameters.HarvestReductionsTable)
{
if (SiteVars.HarvestPrescriptionName != null && ComparePrescriptionNames(prescriptionTableEntry.Name, site))
//prescriptionName.Trim() == prescriptionTableEntry.Name.Trim())
{
litterLossMultiplier = prescriptionTableEntry.FineLitterReduction;
woodLossMultiplier = prescriptionTableEntry.CoarseLitterReduction;
//som_Multiplier = prescription.SOMReduction;
found = true;
}
}
if (!found)
{
PlugIn.ModelCore.UI.WriteLine(" WARNING: Prescription {0} not found in the Biomass Succession Harvest Effects Table", harvestPrescriptionName);
return;
}
//PlugIn.ModelCore.UI.WriteLine(" LitterLoss={0:0.00}, woodLoss={1:0.00}, SOM_loss={2:0.00}, SITE={3}", litterLossMultiplier, woodLossMultiplier, som_Multiplier, site);
// litter first
SiteVars.Litter[site].ReduceMass(litterLossMultiplier);
// Surface dead wood
SiteVars.WoodyDebris[site].ReduceMass(woodLossMultiplier);
}
public static bool ComparePrescriptionNames(string prescriptionTableName, Site site)
{
string harvestPrescriptionName = SiteVars.HarvestPrescriptionName[site].Trim();
string tablePrescriptionName = prescriptionTableName.Trim();
if (harvestPrescriptionName == tablePrescriptionName)
return true;
else if (tablePrescriptionName.EndsWith("*"))
{
if (harvestPrescriptionName.Contains(tablePrescriptionName.TrimEnd()))
return true;
else
return false;
}
else
return false;
}
}
}
| |
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 Fonlow.TraceHub.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;
}
}
}
| |
namespace Nancy.Tests.Unit
{
using System;
using System.Linq;
using Fakes;
using Xunit;
public class NancyModuleFixture
{
private readonly NancyModule module;
public NancyModuleFixture()
{
this.module = new FakeNancyModuleNoRoutes();
}
[Fact]
public void Adds_route_when_get_indexer_used()
{
// Given, When
this.module.Get["/test"] = d => null;
// Then
this.module.Routes.Count().ShouldEqual(1);
}
[Fact]
public void Adds_route_when_put_indexer_used()
{
// Given, When
this.module.Put["/test"] = d => null;
// Then
this.module.Routes.Count().ShouldEqual(1);
}
[Fact]
public void Adds_route_when_post_indexer_used()
{
// Given, When
this.module.Post["/test"] = d => null;
// Then
this.module.Routes.Count().ShouldEqual(1);
}
[Fact]
public void Adds_route_when_delete_indexer_used()
{
// Given, When
this.module.Delete["/test"] = d => null;
// Then
this.module.Routes.Count().ShouldEqual(1);
}
[Fact]
public void Adds_route_when_options_indexer_userd()
{
// Given, When
this.module.Options["/test"] = d => null;
// Then
this.module.Routes.Count().ShouldEqual(1);
}
[Fact]
public void Should_store_route_with_specified_path_when_route_indexer_is_invoked_with_a_path_but_no_condition()
{
// Given, When
this.module.Get["/test"] = d => null;
// Then
module.Routes.First().Description.Path.ShouldEqual("/test");
}
[Fact]
public void Should_store_route_with_specified_path_when_route_indexer_is_invoked_with_a_path_and_condition()
{
// Given
Func<NancyContext, bool> condition = r => true;
// When
this.module.Get["/test", condition] = d => null;
// Then
module.Routes.First().Description.Path.ShouldEqual("/test");
}
[Fact]
public void Should_store_route_with_null_condition_when_route_indexer_is_invoked_without_a_condition()
{
// Given, When
this.module.Get["/test"] = d => null;
// Then
module.Routes.First().Description.Condition.ShouldBeNull();
}
[Fact]
public void Should_store_route_with_condition_when_route_indexer_is_invoked_with_a_condition()
{
// Given
Func<NancyContext, bool> condition = r => true;
// When
this.module.Get["/test", condition] = d => null;
// Then
module.Routes.First().Description.Condition.ShouldBeSameAs(condition);
}
[Fact]
public void Should_add_route_with_get_method_when_added_using_get_indexer()
{
// Given, When
this.module.Get["/test"] = d => null;
// Then
module.Routes.First().Description.Method.ShouldEqual("GET");
}
[Fact]
public void Should_add_route_with_put_method_when_added_using_get_indexer()
{
// Given, When
this.module.Put["/test"] = d => null;
// Then
module.Routes.First().Description.Method.ShouldEqual("PUT");
}
[Fact]
public void Should_add_route_with_post_method_when_added_using_get_indexer()
{
// Given, When
this.module.Post["/test"] = d => null;
// Then
module.Routes.First().Description.Method.ShouldEqual("POST");
}
[Fact]
public void Should_add_route_with_delete_method_when_added_using_get_indexer()
{
// Given, When
this.module.Delete["/test"] = d => null;
// Then
module.Routes.First().Description.Method.ShouldEqual("DELETE");
}
[Fact]
public void Should_store_route_combine_with_base_path_if_one_specified()
{
// Given
var moduleWithBasePath = new FakeNancyModuleWithBasePath();
// When
moduleWithBasePath.Get["/NewRoute"] = d => null;
// Then
moduleWithBasePath.Routes.Last().Description.Path.ShouldEqual("/fake/NewRoute");
}
[Fact]
public void Should_add_leading_slash_to_route_if_missing()
{
// Given
var moduleWithBasePath = new FakeNancyModuleWithBasePath();
// When
moduleWithBasePath.Get["test"] = d => null;
// Then
moduleWithBasePath.Routes.Last().Description.Path.ShouldEqual("/fake/test");
}
[Fact]
public void Should_store_two_routes_when_registering_single_get_method()
{
// Given
var moduleWithBasePath = new CustomNancyModule();
// When
moduleWithBasePath.Get["/Test1", "/Test2"] = d => null;
// Then
moduleWithBasePath.Routes.First().Description.Path.ShouldEqual("/Test1");
moduleWithBasePath.Routes.Last().Description.Path.ShouldEqual("/Test2");
}
[Fact]
public void Should_store_single_route_when_calling_non_overridden_post_from_sub_module()
{
// Given
var moduleWithBasePath = new CustomNancyModule();
// When
moduleWithBasePath.Post["/Test1"] = d => null;
// Then
moduleWithBasePath.Routes.Last().Description.Path.ShouldEqual("/Test1");
}
[Fact]
public void Should_not_throw_when_null_passed_as_modulepath()
{
// Given
var moduleWithNullPath = new CustomModulePathModule(null);
// Then
Assert.DoesNotThrow(() =>
{
moduleWithNullPath.Post["/Test1"] = d => null;
});
}
[Fact]
public void Adds_named_route_when_named_indexer_used()
{
// Given, When
this.module.Get["Foo", "/test"] = d => null;
// Then
this.module.Routes.Count().ShouldEqual(1);
this.module.Routes.First().Description.Name.ShouldEqual("Foo");
}
private class CustomModulePathModule : NancyModule
{
public CustomModulePathModule(string modulePath)
: base(modulePath)
{
}
}
private class CustomNancyModule : NancyModule
{
public new CustomRouteBuilder Get
{
get { return new CustomRouteBuilder("GET", this); }
}
public class CustomRouteBuilder : RouteBuilder
{
public CustomRouteBuilder(string method, NancyModule parentModule)
: base(method, parentModule)
{
}
public Func<dynamic, dynamic> this[params string[] paths]
{
set
{
foreach (var path in paths)
{
this.AddRoute(String.Empty, path, null, value);
}
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.PageSettings.cs
//
// Authors:
// Dennis Hayes ([email protected])
// Herve Poussineau ([email protected])
// Andreas Nahr ([email protected])
//
// (C) 2002 Ximian, Inc
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.InteropServices;
namespace System.Drawing.Printing
{
[Serializable]
public class PageSettings : ICloneable
{
internal bool color;
internal bool landscape;
internal PaperSize paperSize;
internal PaperSource paperSource;
internal PrinterResolution printerResolution;
// create a new default Margins object (is 1 inch for all margins)
private Margins margins = new Margins();
#pragma warning disable 649
private float hardMarginX;
private float hardMarginY;
private RectangleF printableArea;
private PrinterSettings printerSettings;
#pragma warning restore 649
public PageSettings() : this(new PrinterSettings())
{
}
public PageSettings(PrinterSettings printerSettings)
{
PrinterSettings = printerSettings;
this.color = printerSettings.DefaultPageSettings.color;
this.landscape = printerSettings.DefaultPageSettings.landscape;
this.paperSize = printerSettings.DefaultPageSettings.paperSize;
this.paperSource = printerSettings.DefaultPageSettings.paperSource;
this.printerResolution = printerSettings.DefaultPageSettings.printerResolution;
}
// used by PrinterSettings.DefaultPageSettings
internal PageSettings(PrinterSettings printerSettings, bool color, bool landscape, PaperSize paperSize, PaperSource paperSource, PrinterResolution printerResolution)
{
PrinterSettings = printerSettings;
this.color = color;
this.landscape = landscape;
this.paperSize = paperSize;
this.paperSource = paperSource;
this.printerResolution = printerResolution;
}
//props
public Rectangle Bounds
{
get
{
int width = this.paperSize.Width;
int height = this.paperSize.Height;
width -= this.margins.Left + this.margins.Right;
height -= this.margins.Top + this.margins.Bottom;
if (this.landscape)
{
// swap width and height
int tmp = width;
width = height;
height = tmp;
}
return new Rectangle(this.margins.Left, this.margins.Top, width, height);
}
}
public bool Color
{
get
{
if (!this.printerSettings.IsValid)
throw new InvalidPrinterException(this.printerSettings);
return color;
}
set
{
color = value;
}
}
public bool Landscape
{
get
{
if (!this.printerSettings.IsValid)
throw new InvalidPrinterException(this.printerSettings);
return landscape;
}
set
{
landscape = value;
}
}
public Margins Margins
{
get
{
if (!this.printerSettings.IsValid)
throw new InvalidPrinterException(this.printerSettings);
return margins;
}
set
{
margins = value;
}
}
public PaperSize PaperSize
{
get
{
if (!this.printerSettings.IsValid)
throw new InvalidPrinterException(this.printerSettings);
return paperSize;
}
set
{
if (value != null)
paperSize = value;
}
}
public PaperSource PaperSource
{
get
{
if (!this.printerSettings.IsValid)
throw new InvalidPrinterException(this.printerSettings);
return paperSource;
}
set
{
if (value != null)
paperSource = value;
}
}
public PrinterResolution PrinterResolution
{
get
{
if (!this.printerSettings.IsValid)
throw new InvalidPrinterException(this.printerSettings);
return printerResolution;
}
set
{
if (value != null)
printerResolution = value;
}
}
public PrinterSettings PrinterSettings
{
get
{
return printerSettings;
}
set
{
printerSettings = value;
}
}
public float HardMarginX
{
get
{
return hardMarginX;
}
}
public float HardMarginY
{
get
{
return hardMarginY;
}
}
public RectangleF PrintableArea
{
get
{
return printableArea;
}
}
public object Clone()
{
// We do a deep copy
PrinterResolution pres = new PrinterResolution(this.printerResolution.Kind, this.printerResolution.X, this.printerResolution.Y);
PaperSource psource = new PaperSource(this.paperSource.Kind, this.paperSource.SourceName);
PaperSize psize = new PaperSize(this.paperSize.PaperName, this.paperSize.Width, this.paperSize.Height);
psize.RawKind = (int)this.paperSize.Kind;
PageSettings ps = new PageSettings(this.printerSettings, this.color, this.landscape,
psize, psource, pres);
ps.Margins = (Margins)this.margins.Clone();
return ps;
}
public void CopyToHdevmode(IntPtr hdevmode)
{
throw new NotImplementedException();
}
public void SetHdevmode(IntPtr hdevmode)
{
throw new NotImplementedException();
}
public override string ToString()
{
return $"[{nameof(PageSettings)}: {nameof(Color)}={color}, {nameof(Landscape)}={landscape}, {nameof(Margins)}={margins}, {nameof(PaperSize)}={paperSize}, {nameof(PaperSource)}={paperSource}, {nameof(PrinterResolution)}={printerResolution}]";
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using System.Threading;
public enum MegaAlter
{
Offset,
Scale,
Both,
}
public enum MegaAffect
{
X,
Y,
Z,
XY,
XZ,
YZ,
XYZ,
None,
}
// TODO: define box for effect, origin and sizes, and a falloff
[System.Serializable]
public class MegaSculptCurve
{
public MegaSculptCurve()
{
curve = new AnimationCurve(new Keyframe(0.0f, 0.0f), new Keyframe(1.0f, 0.0f));
offamount = Vector3.one;
sclamount = Vector3.one;
axis = MegaAxis.X;
affectOffset = MegaAffect.Y;
affectScale = MegaAffect.None;
enabled = true;
weight = 1.0f;
name = "None";
uselimits = false;
}
public AnimationCurve curve = new AnimationCurve(new Keyframe(0.0f, 0.0f), new Keyframe(1.0f, 0.0f));
public Vector3 offamount = Vector3.one;
public Vector3 sclamount = Vector3.one;
public MegaAxis axis = MegaAxis.X;
public MegaAffect affectOffset = MegaAffect.Y;
public MegaAffect affectScale = MegaAffect.None;
public bool enabled = true;
public float weight = 1.0f;
public string name = "None";
public Color regcol = Color.yellow;
public Vector3 origin = Vector3.zero;
public Vector3 boxsize = Vector3.one;
public bool uselimits = false;
public Vector3 size = Vector3.zero;
static public MegaSculptCurve Create()
{
MegaSculptCurve crv = new MegaSculptCurve();
return crv;
}
}
[AddComponentMenu("Modifiers/Curve Sculpt Layered")]
public class MegaCurveSculptLayered : MegaModifier
{
public List<MegaSculptCurve> curves = new List<MegaSculptCurve>();
Vector3 size = Vector3.zero;
public override string ModName() { return "CurveSculpLayered"; }
public override string GetHelpURL() { return "?page_id=2411"; }
static object resourceLock = new object();
public override void DoWork(MegaModifiers mc, int index, int start, int end, int cores)
{
if ( selection != null )
{
DoWorkWeighted(mc, index, start, end, cores);
return;
}
for ( int i = start; i < end; i++ )
sverts[i] = MapMT(i, verts[i]);
}
public override void DoWorkWeighted(MegaModifiers mc, int index, int start, int end, int cores)
{
for ( int i = start; i < end; i++ )
{
Vector3 p = verts[i];
float w = selection[i]; //[(int)weightChannel];
if ( w > 0.001f )
{
Vector3 mp = MapMT(i, verts[i]);
sverts[i].x = p.x + (mp.x - p.x) * w;
sverts[i].y = p.y + (mp.y - p.y) * w;
sverts[i].z = p.z + (mp.z - p.z) * w;
}
else
sverts[i] = p; //verts[i];
}
}
public Vector3 MapMT(int i, Vector3 p)
{
p = tm.MultiplyPoint3x4(p);
for ( int c = 0; c < curves.Count; c++ )
{
MegaSculptCurve crv = curves[c];
if ( crv.enabled )
{
int ax = (int)crv.axis;
if ( crv.uselimits )
{
// Is the point in the box
Vector3 bp = p - crv.origin;
if ( Mathf.Abs(bp.x) < crv.size.x && Mathf.Abs(bp.y) < crv.size.y && Mathf.Abs(bp.z) < crv.size.z )
{
float alpha = 0.5f + ((bp[ax] / crv.size[ax]) * 0.5f);
if ( alpha >= 0.0f && alpha <= 1.0f )
{
Monitor.Enter(resourceLock);
float a = crv.curve.Evaluate(alpha) * crv.weight;
Monitor.Exit(resourceLock);
switch ( crv.affectScale )
{
case MegaAffect.X:
p.x += bp.x * (a * crv.sclamount.x);
break;
case MegaAffect.Y:
p.y += bp.y * (a * crv.sclamount.y);
break;
case MegaAffect.Z:
p.z += bp.z * (a * crv.sclamount.z);
break;
case MegaAffect.XY:
p.x += bp.x * (a * crv.sclamount.x);
p.y += bp.y * (a * crv.sclamount.y);
break;
case MegaAffect.XZ:
p.x += bp.x * (a * crv.sclamount.x);
p.z += bp.z * (a * crv.sclamount.z);
break;
case MegaAffect.YZ:
p.y += bp.y * (a * crv.sclamount.y);
p.z += bp.z * (a * crv.sclamount.z);
break;
case MegaAffect.XYZ:
p.x += bp.x * (a * crv.sclamount.x);
p.y += bp.y * (a * crv.sclamount.y);
p.z += bp.z * (a * crv.sclamount.z);
break;
}
switch ( crv.affectOffset )
{
case MegaAffect.X:
p.x += a * crv.offamount.x;
break;
case MegaAffect.Y:
p.y += a * crv.offamount.y;
break;
case MegaAffect.Z:
p.z += a * crv.offamount.z;
break;
case MegaAffect.XY:
p.x += a * crv.offamount.x;
p.y += a * crv.offamount.y;
break;
case MegaAffect.XZ:
p.x += a * crv.offamount.x;
p.z += a * crv.offamount.z;
break;
case MegaAffect.YZ:
p.y += a * crv.offamount.y;
p.z += a * crv.offamount.z;
break;
case MegaAffect.XYZ:
p.x += a * crv.offamount.x;
p.y += a * crv.offamount.y;
p.z += a * crv.offamount.z;
break;
}
}
}
}
else
{
float alpha = (p[ax] - bbox.min[ax]) / size[ax];
Monitor.Enter(resourceLock);
float a = crv.curve.Evaluate(alpha) * crv.weight;
Monitor.Exit(resourceLock);
switch ( crv.affectScale )
{
case MegaAffect.X:
p.x *= 1.0f + (a * crv.sclamount.y);
break;
case MegaAffect.Y:
p.y *= 1.0f + (a * crv.sclamount.y);
break;
case MegaAffect.Z:
p.z *= 1.0f + (a * crv.sclamount.z);
break;
case MegaAffect.XY:
p.x *= 1.0f + (a * crv.sclamount.y);
p.y *= 1.0f + (a * crv.sclamount.y);
break;
case MegaAffect.XZ:
p.x *= 1.0f + (a * crv.sclamount.y);
p.z *= 1.0f + (a * crv.sclamount.z);
break;
case MegaAffect.YZ:
p.y *= 1.0f + (a * crv.sclamount.y);
p.z *= 1.0f + (a * crv.sclamount.z);
break;
case MegaAffect.XYZ:
p.x *= 1.0f + (a * crv.sclamount.y);
p.y *= 1.0f + (a * crv.sclamount.y);
p.z *= 1.0f + (a * crv.sclamount.z);
break;
}
switch ( crv.affectOffset )
{
case MegaAffect.X:
p.x += a * crv.offamount.x;
break;
case MegaAffect.Y:
p.y += a * crv.offamount.y;
break;
case MegaAffect.Z:
p.z += a * crv.offamount.z;
break;
case MegaAffect.XY:
p.x += a * crv.offamount.x;
p.y += a * crv.offamount.y;
break;
case MegaAffect.XZ:
p.x += a * crv.offamount.x;
p.z += a * crv.offamount.z;
break;
case MegaAffect.YZ:
p.y += a * crv.offamount.y;
p.z += a * crv.offamount.z;
break;
case MegaAffect.XYZ:
p.x += a * crv.offamount.x;
p.y += a * crv.offamount.y;
p.z += a * crv.offamount.z;
break;
}
}
}
}
return invtm.MultiplyPoint3x4(p);
}
public override Vector3 Map(int i, Vector3 p)
{
p = tm.MultiplyPoint3x4(p);
for ( int c = 0; c < curves.Count; c++ )
{
MegaSculptCurve crv = curves[c];
if ( crv.enabled )
{
int ax = (int)crv.axis;
if ( crv.uselimits )
{
// Is the point in the box
Vector3 bp = p - crv.origin;
if ( Mathf.Abs(bp.x) < crv.size.x && Mathf.Abs(bp.y) < crv.size.y && Mathf.Abs(bp.z) < crv.size.z )
{
float alpha = 0.5f + ((bp[ax] / crv.size[ax]) * 0.5f);
if ( alpha >= 0.0f && alpha <= 1.0f )
{
float a = crv.curve.Evaluate(alpha) * crv.weight;
switch ( crv.affectScale )
{
case MegaAffect.X:
p.x += bp.x * (a * crv.sclamount.x);
break;
case MegaAffect.Y:
p.y += bp.y * (a * crv.sclamount.y);
break;
case MegaAffect.Z:
p.z += bp.z * (a * crv.sclamount.z);
break;
case MegaAffect.XY:
p.x += bp.x * (a * crv.sclamount.x);
p.y += bp.y * (a * crv.sclamount.y);
break;
case MegaAffect.XZ:
p.x += bp.x * (a * crv.sclamount.x);
p.z += bp.z * (a * crv.sclamount.z);
break;
case MegaAffect.YZ:
p.y += bp.y * (a * crv.sclamount.y);
p.z += bp.z * (a * crv.sclamount.z);
break;
case MegaAffect.XYZ:
p.x += bp.x * (a * crv.sclamount.x);
p.y += bp.y * (a * crv.sclamount.y);
p.z += bp.z * (a * crv.sclamount.z);
break;
}
switch ( crv.affectOffset )
{
case MegaAffect.X:
p.x += a * crv.offamount.x;
break;
case MegaAffect.Y:
p.y += a * crv.offamount.y;
break;
case MegaAffect.Z:
p.z += a * crv.offamount.z;
break;
case MegaAffect.XY:
p.x += a * crv.offamount.x;
p.y += a * crv.offamount.y;
break;
case MegaAffect.XZ:
p.x += a * crv.offamount.x;
p.z += a * crv.offamount.z;
break;
case MegaAffect.YZ:
p.y += a * crv.offamount.y;
p.z += a * crv.offamount.z;
break;
case MegaAffect.XYZ:
p.x += a * crv.offamount.x;
p.y += a * crv.offamount.y;
p.z += a * crv.offamount.z;
break;
}
}
}
}
else
{
float alpha = (p[ax] - bbox.min[ax]) / size[ax];
float a = crv.curve.Evaluate(alpha) * crv.weight;
switch ( crv.affectScale )
{
case MegaAffect.X:
p.x *= 1.0f + (a * crv.sclamount.y);
break;
case MegaAffect.Y:
p.y *= 1.0f + (a * crv.sclamount.y);
break;
case MegaAffect.Z:
p.z *= 1.0f + (a * crv.sclamount.z);
break;
case MegaAffect.XY:
p.x *= 1.0f + (a * crv.sclamount.y);
p.y *= 1.0f + (a * crv.sclamount.y);
break;
case MegaAffect.XZ:
p.x *= 1.0f + (a * crv.sclamount.y);
p.z *= 1.0f + (a * crv.sclamount.z);
break;
case MegaAffect.YZ:
p.y *= 1.0f + (a * crv.sclamount.y);
p.z *= 1.0f + (a * crv.sclamount.z);
break;
case MegaAffect.XYZ:
p.x *= 1.0f + (a * crv.sclamount.y);
p.y *= 1.0f + (a * crv.sclamount.y);
p.z *= 1.0f + (a * crv.sclamount.z);
break;
}
switch ( crv.affectOffset )
{
case MegaAffect.X:
p.x += a * crv.offamount.x;
break;
case MegaAffect.Y:
p.y += a * crv.offamount.y;
break;
case MegaAffect.Z:
p.z += a * crv.offamount.z;
break;
case MegaAffect.XY:
p.x += a * crv.offamount.x;
p.y += a * crv.offamount.y;
break;
case MegaAffect.XZ:
p.x += a * crv.offamount.x;
p.z += a * crv.offamount.z;
break;
case MegaAffect.YZ:
p.y += a * crv.offamount.y;
p.z += a * crv.offamount.z;
break;
case MegaAffect.XYZ:
p.x += a * crv.offamount.x;
p.y += a * crv.offamount.y;
p.z += a * crv.offamount.z;
break;
}
}
}
}
return invtm.MultiplyPoint3x4(p);
}
public override bool ModLateUpdate(MegaModContext mc)
{
return Prepare(mc);
}
public override bool Prepare(MegaModContext mc)
{
size = bbox.max - bbox.min;
for ( int i = 0; i < curves.Count; i++ )
{
curves[i].size = curves[i].boxsize * 0.5f; //Vector3.Scale(size, curves[i].boxsize);
}
return true;
}
public override void DrawGizmo(MegaModContext context)
{
base.DrawGizmo(context);
for ( int i = 0; i < curves.Count; i++ )
{
if ( curves[i].enabled && curves[i].uselimits )
{
Gizmos.color = curves[i].regcol; //Color.yellow;
Gizmos.DrawWireCube(curves[i].origin, curves[i].boxsize); // * 0.5f);
}
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class NicProperties : IEquatable<NicProperties>
{
/// <summary>
/// Initializes a new instance of the <see cref="NicProperties" /> class.
/// </summary>
public NicProperties()
{
this.Dhcp = false;
this.FirewallActive = false;
}
/// <summary>
/// A name of that resource
/// </summary>
/// <value>A name of that resource</value>
[DataMember(Name = "name", EmitDefaultValue = false)]
public string Name { get; set; }
/// <summary>
/// The MAC address of the NIC
/// </summary>
/// <value>The MAC address of the NIC</value>
[DataMember(Name = "mac", EmitDefaultValue = false)]
public string Mac { get; set; }
/// <summary>
/// Collection of IP addresses assigned to a nic. Explicitly assigned public IPs need to come from reserved IP blocks, Passing value null or empty array will assign an IP address automatically.
/// </summary>
/// <value>Collection of IP addresses assigned to a nic. Explicitly assigned public IPs need to come from reserved IP blocks, Passing value null or empty array will assign an IP address automatically.</value>
[DataMember(Name = "ips", EmitDefaultValue = false)]
public List<string> Ips { get; set; }
/// <summary>
/// Indicates if the nic will reserve an IP using DHCP
/// </summary>
/// <value>Indicates if the nic will reserve an IP using DHCP</value>
[DataMember(Name = "dhcp", EmitDefaultValue = false)]
public bool? Dhcp { get; set; }
/// <summary>
/// The LAN ID the NIC will sit on. If the LAN ID does not exist it will be implicitly created
/// </summary>
/// <value>The LAN ID the NIC will sit on. If the LAN ID does not exist it will be implicitly created</value>
[DataMember(Name = "lan", EmitDefaultValue = false)]
public int? Lan { get; set; }
/// <summary>
/// Once you add a firewall rule this will reflect a true value. Can also be used to temporarily disable a firewall without losing defined rules.
/// </summary>
/// <value>Once you add a firewall rule this will reflect a true value. Can also be used to temporarily disable a firewall without losing defined rules.</value>
[DataMember(Name = "firewallActive", EmitDefaultValue = false)]
public bool? FirewallActive { get; set; }
[DataMember(Name = "nat", EmitDefaultValue = false)]
public bool? Nat { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class NicProperties {\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Mac: ").Append(Mac).Append("\n");
sb.Append(" Ips: ").Append(Ips).Append("\n");
sb.Append(" Dhcp: ").Append(Dhcp).Append("\n");
sb.Append(" Lan: ").Append(Lan).Append("\n");
sb.Append(" FirewallActive: ").Append(FirewallActive).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as NicProperties);
}
/// <summary>
/// Returns true if NicProperties instances are equal
/// </summary>
/// <param name="other">Instance of NicProperties to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(NicProperties other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Mac == other.Mac ||
this.Mac != null &&
this.Mac.Equals(other.Mac)
) &&
(
this.Ips == other.Ips ||
this.Ips != null &&
this.Ips.SequenceEqual(other.Ips)
) &&
(
this.Dhcp == other.Dhcp ||
this.Dhcp != null &&
this.Dhcp.Equals(other.Dhcp)
) &&
(
this.Lan == other.Lan ||
this.Lan != null &&
this.Lan.Equals(other.Lan)
) &&
(
this.FirewallActive == other.FirewallActive ||
this.FirewallActive != null &&
this.FirewallActive.Equals(other.FirewallActive)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Mac != null)
hash = hash * 59 + this.Mac.GetHashCode();
if (this.Ips != null)
hash = hash * 59 + this.Ips.GetHashCode();
if (this.Dhcp != null)
hash = hash * 59 + this.Dhcp.GetHashCode();
if (this.Lan != null)
hash = hash * 59 + this.Lan.GetHashCode();
if (this.FirewallActive != null)
hash = hash * 59 + this.FirewallActive.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Handles;
namespace LibGit2Sharp
{
/// <summary>
/// Provides methods to directly work against the Git object database
/// without involving the index nor the working directory.
/// </summary>
public class ObjectDatabase : IEnumerable<GitObject>
{
private readonly Repository repo;
private readonly ObjectDatabaseHandle handle;
/// <summary>
/// Needed for mocking purposes.
/// </summary>
protected ObjectDatabase()
{ }
internal ObjectDatabase(Repository repo)
{
this.repo = repo;
handle = Proxy.git_repository_odb(repo.Handle);
repo.RegisterForCleanup(handle);
}
#region Implementation of IEnumerable
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the collection.</returns>
public virtual IEnumerator<GitObject> GetEnumerator()
{
ICollection<ObjectId> oids = Proxy.git_odb_foreach(handle);
return oids
.Select(gitOid => repo.Lookup<GitObject>(gitOid))
.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
/// <summary>
/// Determines if the given object can be found in the object database.
/// </summary>
/// <param name="objectId">Identifier of the object being searched for.</param>
/// <returns>True if the object has been found; false otherwise.</returns>
public virtual bool Contains(ObjectId objectId)
{
Ensure.ArgumentNotNull(objectId, "objectId");
return Proxy.git_odb_exists(handle, objectId);
}
/// <summary>
/// Retrieves the header of a GitObject from the object database. The header contains the Size
/// and Type of the object. Note that most backends do not support reading only the header
/// of an object, so the whole object will be read and then size would be returned.
/// </summary>
/// <param name="objectId">Object Id of the queried object</param>
/// <returns>GitObjectMetadata object instance containg object header information</returns>
public virtual GitObjectMetadata RetrieveObjectMetadata(ObjectId objectId)
{
Ensure.ArgumentNotNull(objectId, "objectId");
return Proxy.git_odb_read_header(handle, objectId);
}
/// <summary>
/// Inserts a <see cref="Blob"/> into the object database, created from the content of a file.
/// </summary>
/// <param name="path">Path to the file to create the blob from. A relative path is allowed to
/// be passed if the <see cref="Repository"/> is a standard, non-bare, repository. The path
/// will then be considered as a path relative to the root of the working directory.</param>
/// <returns>The created <see cref="Blob"/>.</returns>
public virtual Blob CreateBlob(string path)
{
Ensure.ArgumentNotNullOrEmptyString(path, "path");
if (repo.Info.IsBare && !Path.IsPathRooted(path))
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"Cannot create a blob in a bare repository from a relative path ('{0}').",
path));
}
ObjectId id = Path.IsPathRooted(path)
? Proxy.git_blob_create_from_disk(repo.Handle, path)
: Proxy.git_blob_create_from_workdir(repo.Handle, path);
return repo.Lookup<Blob>(id);
}
/// <summary>
/// Adds the provided backend to the object database with the specified priority.
/// <para>
/// If the provided backend implements <see cref="IDisposable"/>, the <see cref="IDisposable.Dispose"/>
/// method will be honored and invoked upon the disposal of the repository.
/// </para>
/// </summary>
/// <param name="backend">The backend to add</param>
/// <param name="priority">The priority at which libgit2 should consult this backend (higher values are consulted first)</param>
public virtual void AddBackend(OdbBackend backend, int priority)
{
Ensure.ArgumentNotNull(backend, "backend");
Ensure.ArgumentConformsTo(priority, s => s > 0, "priority");
Proxy.git_odb_add_backend(handle, backend.GitOdbBackendPointer, priority);
}
private class Processor
{
private readonly Stream stream;
private readonly long? numberOfBytesToConsume;
private int totalNumberOfReadBytes;
public Processor(Stream stream, long? numberOfBytesToConsume)
{
this.stream = stream;
this.numberOfBytesToConsume = numberOfBytesToConsume;
}
public int Provider(IntPtr content, int max_length, IntPtr data)
{
var local = new byte[max_length];
int bytesToRead = max_length;
if (numberOfBytesToConsume.HasValue)
{
long totalRemainingBytesToRead = numberOfBytesToConsume.Value - totalNumberOfReadBytes;
if (totalRemainingBytesToRead < max_length)
{
bytesToRead = totalRemainingBytesToRead > int.MaxValue
? int.MaxValue
: (int)totalRemainingBytesToRead;
}
}
if (bytesToRead == 0)
{
return 0;
}
int numberOfReadBytes = stream.Read(local, 0, bytesToRead);
if (numberOfBytesToConsume.HasValue && numberOfReadBytes == 0)
{
return (int)GitErrorCode.User;
}
totalNumberOfReadBytes += numberOfReadBytes;
Marshal.Copy(local, 0, content, numberOfReadBytes);
return numberOfReadBytes;
}
}
/// <summary>
/// Writes an object to the object database.
/// </summary>
/// <param name="data">The contents of the object</param>
/// <typeparam name="T">The type of object to write</typeparam>
public virtual ObjectId Write<T>(byte[] data) where T : GitObject
{
return Proxy.git_odb_write(handle, data, GitObject.TypeToKindMap[typeof(T)]);
}
/// <summary>
/// Writes an object to the object database.
/// </summary>
/// <param name="stream">The contents of the object</param>
/// <param name="numberOfBytesToConsume">The number of bytes to consume from the stream</param>
/// <typeparam name="T">The type of object to write</typeparam>
public virtual ObjectId Write<T>(Stream stream, long numberOfBytesToConsume) where T : GitObject
{
Ensure.ArgumentNotNull(stream, "stream");
if (!stream.CanRead)
{
throw new ArgumentException("The stream cannot be read from.", "stream");
}
using (var odbStream = Proxy.git_odb_open_wstream(handle, numberOfBytesToConsume, GitObjectType.Blob))
{
var buffer = new byte[4 * 1024];
long totalRead = 0;
while (totalRead < numberOfBytesToConsume)
{
long left = numberOfBytesToConsume - totalRead;
int toRead = left < buffer.Length ? (int)left : buffer.Length;
var read = stream.Read(buffer, 0, toRead);
if (read == 0)
{
throw new EndOfStreamException("The stream ended unexpectedly");
}
Proxy.git_odb_stream_write(odbStream, buffer, read);
totalRead += read;
}
return Proxy.git_odb_stream_finalize_write(odbStream);
}
}
/// <summary>
/// Inserts a <see cref="Blob"/> into the object database, created from the content of a stream.
/// <para>Optionally, git filters will be applied to the content before storing it.</para>
/// </summary>
/// <param name="stream">The stream from which will be read the content of the blob to be created.</param>
/// <returns>The created <see cref="Blob"/>.</returns>
public virtual Blob CreateBlob(Stream stream)
{
return CreateBlob(stream, null, null);
}
/// <summary>
/// Inserts a <see cref="Blob"/> into the object database, created from the content of a stream.
/// <para>Optionally, git filters will be applied to the content before storing it.</para>
/// </summary>
/// <param name="stream">The stream from which will be read the content of the blob to be created.</param>
/// <param name="hintpath">The hintpath is used to determine what git filters should be applied to the object before it can be placed to the object database.</param>
/// <returns>The created <see cref="Blob"/>.</returns>
public virtual Blob CreateBlob(Stream stream, string hintpath)
{
return CreateBlob(stream, hintpath, null);
}
/// <summary>
/// Inserts a <see cref="Blob"/> into the object database, created from the content of a stream.
/// <para>Optionally, git filters will be applied to the content before storing it.</para>
/// </summary>
/// <param name="stream">The stream from which will be read the content of the blob to be created.</param>
/// <param name="hintpath">The hintpath is used to determine what git filters should be applied to the object before it can be placed to the object database.</param>
/// <param name="numberOfBytesToConsume">The number of bytes to consume from the stream.</param>
/// <returns>The created <see cref="Blob"/>.</returns>
public virtual Blob CreateBlob(Stream stream, string hintpath, long numberOfBytesToConsume)
{
return CreateBlob(stream, hintpath, (long?)numberOfBytesToConsume);
}
private unsafe Blob CreateBlob(Stream stream, string hintpath, long? numberOfBytesToConsume)
{
Ensure.ArgumentNotNull(stream, "stream");
// there's no need to buffer the file for filtering, so simply use a stream
if (hintpath == null && numberOfBytesToConsume.HasValue)
{
return CreateBlob(stream, numberOfBytesToConsume.Value);
}
if (!stream.CanRead)
{
throw new ArgumentException("The stream cannot be read from.", "stream");
}
IntPtr writestream_ptr = Proxy.git_blob_create_from_stream(repo.Handle, hintpath);
GitWriteStream writestream = Marshal.PtrToStructure<GitWriteStream>(writestream_ptr);
try
{
var buffer = new byte[4 * 1024];
long totalRead = 0;
int read = 0;
while (true)
{
int toRead = numberOfBytesToConsume.HasValue ?
(int)Math.Min(numberOfBytesToConsume.Value - totalRead, (long)buffer.Length) :
buffer.Length;
if (toRead > 0)
{
read = (toRead > 0) ? stream.Read(buffer, 0, toRead) : 0;
}
if (read == 0)
{
break;
}
fixed (byte* buffer_ptr = buffer)
{
writestream.write(writestream_ptr, (IntPtr)buffer_ptr, (UIntPtr)read);
}
totalRead += read;
}
if (numberOfBytesToConsume.HasValue && totalRead < numberOfBytesToConsume.Value)
{
throw new EndOfStreamException("The stream ended unexpectedly");
}
}
catch(Exception e)
{
writestream.free(writestream_ptr);
throw e;
}
ObjectId id = Proxy.git_blob_create_fromstream_commit(writestream_ptr);
return repo.Lookup<Blob>(id);
}
/// <summary>
/// Inserts a <see cref="Blob"/> into the object database created from the content of the stream.
/// </summary>
/// <param name="stream">The stream from which will be read the content of the blob to be created.</param>
/// <param name="numberOfBytesToConsume">Number of bytes to consume from the stream.</param>
/// <returns>The created <see cref="Blob"/>.</returns>
public virtual Blob CreateBlob(Stream stream, long numberOfBytesToConsume)
{
var id = Write<Blob>(stream, numberOfBytesToConsume);
return repo.Lookup<Blob>(id);
}
/// <summary>
/// Inserts a <see cref="Tree"/> into the object database, created from a <see cref="TreeDefinition"/>.
/// </summary>
/// <param name="treeDefinition">The <see cref="TreeDefinition"/>.</param>
/// <returns>The created <see cref="Tree"/>.</returns>
public virtual Tree CreateTree(TreeDefinition treeDefinition)
{
Ensure.ArgumentNotNull(treeDefinition, "treeDefinition");
return treeDefinition.Build(repo);
}
/// <summary>
/// Inserts a <see cref="Tree"/> into the object database, created from the <see cref="Index"/>.
/// <para>
/// It recursively creates tree objects for each of the subtrees stored in the index, but only returns the root tree.
/// </para>
/// <para>
/// The index must be fully merged.
/// </para>
/// </summary>
/// <param name="index">The <see cref="Index"/>.</param>
/// <returns>The created <see cref="Tree"/>. This can be used e.g. to create a <see cref="Commit"/>.</returns>
public virtual Tree CreateTree(Index index)
{
Ensure.ArgumentNotNull(index, "index");
var treeId = Proxy.git_index_write_tree(index.Handle);
return this.repo.Lookup<Tree>(treeId);
}
/// <summary>
/// Inserts a <see cref="Commit"/> into the object database, referencing an existing <see cref="Tree"/>.
/// <para>
/// Prettifing the message includes:
/// * Removing empty lines from the beginning and end.
/// * Removing trailing spaces from every line.
/// * Turning multiple consecutive empty lines between paragraphs into just one empty line.
/// * Ensuring the commit message ends with a newline.
/// * Removing every line starting with "#".
/// </para>
/// </summary>
/// <param name="author">The <see cref="Signature"/> of who made the change.</param>
/// <param name="committer">The <see cref="Signature"/> of who added the change to the repository.</param>
/// <param name="message">The description of why a change was made to the repository.</param>
/// <param name="tree">The <see cref="Tree"/> of the <see cref="Commit"/> to be created.</param>
/// <param name="parents">The parents of the <see cref="Commit"/> to be created.</param>
/// <param name="prettifyMessage">True to prettify the message, or false to leave it as is.</param>
/// <returns>The created <see cref="Commit"/>.</returns>
public virtual Commit CreateCommit(Signature author, Signature committer, string message, Tree tree, IEnumerable<Commit> parents, bool prettifyMessage)
{
return CreateCommit(author, committer, message, tree, parents, prettifyMessage, null);
}
/// <summary>
/// Inserts a <see cref="Commit"/> into the object database, referencing an existing <see cref="Tree"/>.
/// <para>
/// Prettifing the message includes:
/// * Removing empty lines from the beginning and end.
/// * Removing trailing spaces from every line.
/// * Turning multiple consecutive empty lines between paragraphs into just one empty line.
/// * Ensuring the commit message ends with a newline.
/// * Removing every line starting with the <paramref name="commentChar"/>.
/// </para>
/// </summary>
/// <param name="author">The <see cref="Signature"/> of who made the change.</param>
/// <param name="committer">The <see cref="Signature"/> of who added the change to the repository.</param>
/// <param name="message">The description of why a change was made to the repository.</param>
/// <param name="tree">The <see cref="Tree"/> of the <see cref="Commit"/> to be created.</param>
/// <param name="parents">The parents of the <see cref="Commit"/> to be created.</param>
/// <param name="prettifyMessage">True to prettify the message, or false to leave it as is.</param>
/// <param name="commentChar">When non null, lines starting with this character will be stripped if prettifyMessage is true.</param>
/// <returns>The created <see cref="Commit"/>.</returns>
public virtual Commit CreateCommit(Signature author, Signature committer, string message, Tree tree, IEnumerable<Commit> parents, bool prettifyMessage, char? commentChar)
{
Ensure.ArgumentNotNull(message, "message");
Ensure.ArgumentDoesNotContainZeroByte(message, "message");
Ensure.ArgumentNotNull(author, "author");
Ensure.ArgumentNotNull(committer, "committer");
Ensure.ArgumentNotNull(tree, "tree");
Ensure.ArgumentNotNull(parents, "parents");
if (prettifyMessage)
{
message = Proxy.git_message_prettify(message, commentChar);
}
GitOid[] parentIds = parents.Select(p => p.Id.Oid).ToArray();
ObjectId commitId = Proxy.git_commit_create(repo.Handle, null, author, committer, message, tree, parentIds);
Commit commit = repo.Lookup<Commit>(commitId);
Ensure.GitObjectIsNotNull(commit, commitId.Sha);
return commit;
}
/// <summary>
/// Inserts a <see cref="Commit"/> into the object database after attaching the given signature.
/// </summary>
/// <param name="commitContent">The raw unsigned commit</param>
/// <param name="signature">The signature data </param>
/// <param name="field">The header field in the commit in which to store the signature</param>
/// <returns>The created <see cref="Commit"/>.</returns>
public virtual ObjectId CreateCommitWithSignature(string commitContent, string signature, string field)
{
return Proxy.git_commit_create_with_signature(repo.Handle, commitContent, signature, field);
}
/// <summary>
/// Inserts a <see cref="Commit"/> into the object database after attaching the given signature.
/// <para>
/// This overload uses the default header field of "gpgsig"
/// </para>
/// </summary>
/// <param name="commitContent">The raw unsigned commit</param>
/// <param name="signature">The signature data </param>
/// <returns>The created <see cref="Commit"/>.</returns>
public virtual ObjectId CreateCommitWithSignature(string commitContent, string signature)
{
return Proxy.git_commit_create_with_signature(repo.Handle, commitContent, signature, null);
}
/// <summary>
/// Inserts a <see cref="TagAnnotation"/> into the object database, pointing to a specific <see cref="GitObject"/>.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="target">The <see cref="GitObject"/> being pointed at.</param>
/// <param name="tagger">The tagger.</param>
/// <param name="message">The message.</param>
/// <returns>The created <see cref="TagAnnotation"/>.</returns>
public virtual TagAnnotation CreateTagAnnotation(string name, GitObject target, Signature tagger, string message)
{
Ensure.ArgumentNotNullOrEmptyString(name, "name");
Ensure.ArgumentNotNull(message, "message");
Ensure.ArgumentNotNull(target, "target");
Ensure.ArgumentNotNull(tagger, "tagger");
Ensure.ArgumentDoesNotContainZeroByte(name, "name");
Ensure.ArgumentDoesNotContainZeroByte(message, "message");
string prettifiedMessage = Proxy.git_message_prettify(message, null);
ObjectId tagId = Proxy.git_tag_annotation_create(repo.Handle, name, target, tagger, prettifiedMessage);
return repo.Lookup<TagAnnotation>(tagId);
}
/// <summary>
/// Create a TAR archive of the given tree.
/// </summary>
/// <param name="tree">The tree.</param>
/// <param name="archivePath">The archive path.</param>
public virtual void Archive(Tree tree, string archivePath)
{
using (var output = new FileStream(archivePath, FileMode.Create))
using (var archiver = new TarArchiver(output))
{
Archive(tree, archiver);
}
}
/// <summary>
/// Create a TAR archive of the given commit.
/// </summary>
/// <param name="commit">commit.</param>
/// <param name="archivePath">The archive path.</param>
public virtual void Archive(Commit commit, string archivePath)
{
using (var output = new FileStream(archivePath, FileMode.Create))
using (var archiver = new TarArchiver(output))
{
Archive(commit, archiver);
}
}
/// <summary>
/// Archive the given commit.
/// </summary>
/// <param name="commit">The commit.</param>
/// <param name="archiver">The archiver to use.</param>
public virtual void Archive(Commit commit, ArchiverBase archiver)
{
Ensure.ArgumentNotNull(commit, "commit");
Ensure.ArgumentNotNull(archiver, "archiver");
archiver.OrchestrateArchiving(commit.Tree, commit.Id, commit.Committer.When);
}
/// <summary>
/// Archive the given tree.
/// </summary>
/// <param name="tree">The tree.</param>
/// <param name="archiver">The archiver to use.</param>
public virtual void Archive(Tree tree, ArchiverBase archiver)
{
Ensure.ArgumentNotNull(tree, "tree");
Ensure.ArgumentNotNull(archiver, "archiver");
archiver.OrchestrateArchiving(tree, null, DateTimeOffset.UtcNow);
}
/// <summary>
/// Returns the merge base (best common ancestor) of the given commits
/// and the distance between each of these commits and this base.
/// </summary>
/// <param name="one">The <see cref="Commit"/> being used as a reference.</param>
/// <param name="another">The <see cref="Commit"/> being compared against <paramref name="one"/>.</param>
/// <returns>A instance of <see cref="HistoryDivergence"/>.</returns>
public virtual HistoryDivergence CalculateHistoryDivergence(Commit one, Commit another)
{
Ensure.ArgumentNotNull(one, "one");
Ensure.ArgumentNotNull(another, "another");
return new HistoryDivergence(repo, one, another);
}
/// <summary>
/// Performs a cherry-pick of <paramref name="cherryPickCommit"/> onto <paramref name="cherryPickOnto"/> commit.
/// </summary>
/// <param name="cherryPickCommit">The commit to cherry-pick.</param>
/// <param name="cherryPickOnto">The commit to cherry-pick onto.</param>
/// <param name="mainline">Which commit to consider the parent for the diff when cherry-picking a merge commit.</param>
/// <param name="options">The options for the merging in the cherry-pick operation.</param>
/// <returns>A result containing a <see cref="Tree"/> if the cherry-pick was successful and a list of <see cref="Conflict"/>s if it is not.</returns>
public virtual MergeTreeResult CherryPickCommit(Commit cherryPickCommit, Commit cherryPickOnto, int mainline, MergeTreeOptions options)
{
Ensure.ArgumentNotNull(cherryPickCommit, "cherryPickCommit");
Ensure.ArgumentNotNull(cherryPickOnto, "cherryPickOnto");
var modifiedOptions = new MergeTreeOptions();
// We throw away the index after looking at the conflicts, so we'll never need the REUC
// entries to be there
modifiedOptions.SkipReuc = true;
if (options != null)
{
modifiedOptions.FailOnConflict = options.FailOnConflict;
modifiedOptions.FindRenames = options.FindRenames;
modifiedOptions.MergeFileFavor = options.MergeFileFavor;
modifiedOptions.RenameThreshold = options.RenameThreshold;
modifiedOptions.TargetLimit = options.TargetLimit;
}
bool earlyStop;
using (var indexHandle = CherryPickCommit(cherryPickCommit, cherryPickOnto, mainline, modifiedOptions, out earlyStop))
{
MergeTreeResult cherryPickResult;
// Stopped due to FailOnConflict so there's no index or conflict list
if (earlyStop)
{
return new MergeTreeResult(new Conflict[] { });
}
if (Proxy.git_index_has_conflicts(indexHandle))
{
List<Conflict> conflicts = new List<Conflict>();
Conflict conflict;
using (ConflictIteratorHandle iterator = Proxy.git_index_conflict_iterator_new(indexHandle))
{
while ((conflict = Proxy.git_index_conflict_next(iterator)) != null)
{
conflicts.Add(conflict);
}
}
cherryPickResult = new MergeTreeResult(conflicts);
}
else
{
var treeId = Proxy.git_index_write_tree_to(indexHandle, repo.Handle);
cherryPickResult = new MergeTreeResult(this.repo.Lookup<Tree>(treeId));
}
return cherryPickResult;
}
}
/// <summary>
/// Calculates the current shortest abbreviated <see cref="ObjectId"/>
/// string representation for a <see cref="GitObject"/>.
/// </summary>
/// <param name="gitObject">The <see cref="GitObject"/> which identifier should be shortened.</param>
/// <returns>A short string representation of the <see cref="ObjectId"/>.</returns>
public virtual string ShortenObjectId(GitObject gitObject)
{
var shortSha = Proxy.git_object_short_id(repo.Handle, gitObject.Id);
return shortSha;
}
/// <summary>
/// Calculates the current shortest abbreviated <see cref="ObjectId"/>
/// string representation for a <see cref="GitObject"/>.
/// </summary>
/// <param name="gitObject">The <see cref="GitObject"/> which identifier should be shortened.</param>
/// <param name="minLength">Minimum length of the shortened representation.</param>
/// <returns>A short string representation of the <see cref="ObjectId"/>.</returns>
public virtual string ShortenObjectId(GitObject gitObject, int minLength)
{
Ensure.ArgumentNotNull(gitObject, "gitObject");
if (minLength <= 0 || minLength > ObjectId.HexSize)
{
throw new ArgumentOutOfRangeException("minLength",
minLength,
string.Format("Expected value should be greater than zero and less than or equal to {0}.",
ObjectId.HexSize));
}
string shortSha = Proxy.git_object_short_id(repo.Handle, gitObject.Id);
if (shortSha == null)
{
throw new LibGit2SharpException("Unable to abbreviate SHA-1 value for GitObject " + gitObject.Id);
}
if (minLength <= shortSha.Length)
{
return shortSha;
}
return gitObject.Sha.Substring(0, minLength);
}
/// <summary>
/// Returns whether merging <paramref name="one"/> into <paramref name="another"/>
/// would result in merge conflicts.
/// </summary>
/// <param name="one">The commit wrapping the base tree to merge into.</param>
/// <param name="another">The commit wrapping the tree to merge into <paramref name="one"/>.</param>
/// <returns>True if the merge does not result in a conflict, false otherwise.</returns>
public virtual bool CanMergeWithoutConflict(Commit one, Commit another)
{
Ensure.ArgumentNotNull(one, "one");
Ensure.ArgumentNotNull(another, "another");
var opts = new MergeTreeOptions()
{
SkipReuc = true,
FailOnConflict = true,
};
var result = repo.ObjectDatabase.MergeCommits(one, another, opts);
return (result.Status == MergeTreeStatus.Succeeded);
}
/// <summary>
/// Find the best possible merge base given two <see cref="Commit"/>s.
/// </summary>
/// <param name="first">The first <see cref="Commit"/>.</param>
/// <param name="second">The second <see cref="Commit"/>.</param>
/// <returns>The merge base or null if none found.</returns>
public virtual Commit FindMergeBase(Commit first, Commit second)
{
Ensure.ArgumentNotNull(first, "first");
Ensure.ArgumentNotNull(second, "second");
return FindMergeBase(new[] { first, second }, MergeBaseFindingStrategy.Standard);
}
/// <summary>
/// Find the best possible merge base given two or more <see cref="Commit"/> according to the <see cref="MergeBaseFindingStrategy"/>.
/// </summary>
/// <param name="commits">The <see cref="Commit"/>s for which to find the merge base.</param>
/// <param name="strategy">The strategy to leverage in order to find the merge base.</param>
/// <returns>The merge base or null if none found.</returns>
public virtual Commit FindMergeBase(IEnumerable<Commit> commits, MergeBaseFindingStrategy strategy)
{
Ensure.ArgumentNotNull(commits, "commits");
ObjectId id;
List<GitOid> ids = new List<GitOid>(8);
int count = 0;
foreach (var commit in commits)
{
if (commit == null)
{
throw new ArgumentException("Enumerable contains null at position: " + count.ToString(CultureInfo.InvariantCulture), "commits");
}
ids.Add(commit.Id.Oid);
count++;
}
if (count < 2)
{
throw new ArgumentException("The enumerable must contains at least two commits.", "commits");
}
switch (strategy)
{
case MergeBaseFindingStrategy.Standard:
id = Proxy.git_merge_base_many(repo.Handle, ids.ToArray());
break;
case MergeBaseFindingStrategy.Octopus:
id = Proxy.git_merge_base_octopus(repo.Handle, ids.ToArray());
break;
default:
throw new ArgumentException("", "strategy");
}
return id == null ? null : repo.Lookup<Commit>(id);
}
/// <summary>
/// Perform a three-way merge of two commits, looking up their
/// commit ancestor. The returned <see cref="MergeTreeResult"/> will contain the results
/// of the merge and can be examined for conflicts.
/// </summary>
/// <param name="ours">The first commit</param>
/// <param name="theirs">The second commit</param>
/// <param name="options">The <see cref="MergeTreeOptions"/> controlling the merge</param>
/// <returns>The <see cref="MergeTreeResult"/> containing the merged trees and any conflicts</returns>
public virtual MergeTreeResult MergeCommits(Commit ours, Commit theirs, MergeTreeOptions options)
{
Ensure.ArgumentNotNull(ours, "ours");
Ensure.ArgumentNotNull(theirs, "theirs");
var modifiedOptions = new MergeTreeOptions();
// We throw away the index after looking at the conflicts, so we'll never need the REUC
// entries to be there
modifiedOptions.SkipReuc = true;
if (options != null)
{
modifiedOptions.FailOnConflict = options.FailOnConflict;
modifiedOptions.FindRenames = options.FindRenames;
modifiedOptions.IgnoreWhitespaceChange = options.IgnoreWhitespaceChange;
modifiedOptions.MergeFileFavor = options.MergeFileFavor;
modifiedOptions.RenameThreshold = options.RenameThreshold;
modifiedOptions.TargetLimit = options.TargetLimit;
}
bool earlyStop;
using (var indexHandle = MergeCommits(ours, theirs, modifiedOptions, out earlyStop))
{
MergeTreeResult mergeResult;
// Stopped due to FailOnConflict so there's no index or conflict list
if (earlyStop)
{
return new MergeTreeResult(new Conflict[] { });
}
if (Proxy.git_index_has_conflicts(indexHandle))
{
List<Conflict> conflicts = new List<Conflict>();
Conflict conflict;
using (ConflictIteratorHandle iterator = Proxy.git_index_conflict_iterator_new(indexHandle))
{
while ((conflict = Proxy.git_index_conflict_next(iterator)) != null)
{
conflicts.Add(conflict);
}
}
mergeResult = new MergeTreeResult(conflicts);
}
else
{
var treeId = Proxy.git_index_write_tree_to(indexHandle, repo.Handle);
mergeResult = new MergeTreeResult(this.repo.Lookup<Tree>(treeId));
}
return mergeResult;
}
}
/// <summary>
/// Packs all the objects in the <see cref="ObjectDatabase"/> and write a pack (.pack) and index (.idx) files for them.
/// </summary>
/// <param name="options">Packing options</param>
/// This method will invoke the default action of packing all objects in an arbitrary order.
/// <returns>Packing results</returns>
public virtual PackBuilderResults Pack(PackBuilderOptions options)
{
return InternalPack(options, builder =>
{
foreach (GitObject obj in repo.ObjectDatabase)
{
builder.Add(obj.Id);
}
});
}
/// <summary>
/// Packs objects in the <see cref="ObjectDatabase"/> chosen by the packDelegate action
/// and write a pack (.pack) and index (.idx) files for them
/// </summary>
/// <param name="options">Packing options</param>
/// <param name="packDelegate">Packing action</param>
/// <returns>Packing results</returns>
public virtual PackBuilderResults Pack(PackBuilderOptions options, Action<PackBuilder> packDelegate)
{
return InternalPack(options, packDelegate);
}
/// <summary>
/// Perform a three-way merge of two commits, looking up their
/// commit ancestor. The returned index will contain the results
/// of the merge and can be examined for conflicts.
/// </summary>
/// <param name="ours">The first tree</param>
/// <param name="theirs">The second tree</param>
/// <param name="options">The <see cref="MergeTreeOptions"/> controlling the merge</param>
/// <returns>The <see cref="TransientIndex"/> containing the merged trees and any conflicts, or null if the merge stopped early due to conflicts.
/// The index must be disposed by the caller.</returns>
public virtual TransientIndex MergeCommitsIntoIndex(Commit ours, Commit theirs, MergeTreeOptions options)
{
Ensure.ArgumentNotNull(ours, "ours");
Ensure.ArgumentNotNull(theirs, "theirs");
options = options ?? new MergeTreeOptions();
bool earlyStop;
var indexHandle = MergeCommits(ours, theirs, options, out earlyStop);
if (earlyStop)
{
if (indexHandle != null)
{
indexHandle.Dispose();
}
return null;
}
var result = new TransientIndex(indexHandle, repo);
return result;
}
/// <summary>
/// Performs a cherry-pick of <paramref name="cherryPickCommit"/> onto <paramref name="cherryPickOnto"/> commit.
/// </summary>
/// <param name="cherryPickCommit">The commit to cherry-pick.</param>
/// <param name="cherryPickOnto">The commit to cherry-pick onto.</param>
/// <param name="mainline">Which commit to consider the parent for the diff when cherry-picking a merge commit.</param>
/// <param name="options">The options for the merging in the cherry-pick operation.</param>
/// <returns>The <see cref="TransientIndex"/> containing the cherry-pick result tree and any conflicts, or null if the merge stopped early due to conflicts.
/// The index must be disposed by the caller. </returns>
public virtual TransientIndex CherryPickCommitIntoIndex(Commit cherryPickCommit, Commit cherryPickOnto, int mainline, MergeTreeOptions options)
{
Ensure.ArgumentNotNull(cherryPickCommit, "cherryPickCommit");
Ensure.ArgumentNotNull(cherryPickOnto, "cherryPickOnto");
options = options ?? new MergeTreeOptions();
bool earlyStop;
var indexHandle = CherryPickCommit(cherryPickCommit, cherryPickOnto, mainline, options, out earlyStop);
if (earlyStop)
{
if (indexHandle != null)
{
indexHandle.Dispose();
}
return null;
}
var result = new TransientIndex(indexHandle, repo);
return result;
}
/// <summary>
/// Perform a three-way merge of two commits, looking up their
/// commit ancestor. The returned index will contain the results
/// of the merge and can be examined for conflicts.
/// </summary>
/// <param name="ours">The first tree</param>
/// <param name="theirs">The second tree</param>
/// <param name="options">The <see cref="MergeTreeOptions"/> controlling the merge</param>
/// <param name="earlyStop">True if the merge stopped early due to conflicts</param>
/// <returns>The <see cref="IndexHandle"/> containing the merged trees and any conflicts</returns>
private IndexHandle MergeCommits(Commit ours, Commit theirs, MergeTreeOptions options, out bool earlyStop)
{
GitMergeFlag mergeFlags = GitMergeFlag.GIT_MERGE_NORMAL;
if (options.SkipReuc)
{
mergeFlags |= GitMergeFlag.GIT_MERGE_SKIP_REUC;
}
if (options.FindRenames)
{
mergeFlags |= GitMergeFlag.GIT_MERGE_FIND_RENAMES;
}
if (options.FailOnConflict)
{
mergeFlags |= GitMergeFlag.GIT_MERGE_FAIL_ON_CONFLICT;
}
var mergeOptions = new GitMergeOpts
{
Version = 1,
MergeFileFavorFlags = options.MergeFileFavor,
MergeTreeFlags = mergeFlags,
RenameThreshold = (uint)options.RenameThreshold,
TargetLimit = (uint)options.TargetLimit,
};
using (var oneHandle = Proxy.git_object_lookup(repo.Handle, ours.Id, GitObjectType.Commit))
using (var twoHandle = Proxy.git_object_lookup(repo.Handle, theirs.Id, GitObjectType.Commit))
{
var indexHandle = Proxy.git_merge_commits(repo.Handle, oneHandle, twoHandle, mergeOptions, out earlyStop);
return indexHandle;
}
}
/// <summary>
/// Performs a cherry-pick of <paramref name="cherryPickCommit"/> onto <paramref name="cherryPickOnto"/> commit.
/// </summary>
/// <param name="cherryPickCommit">The commit to cherry-pick.</param>
/// <param name="cherryPickOnto">The commit to cherry-pick onto.</param>
/// <param name="mainline">Which commit to consider the parent for the diff when cherry-picking a merge commit.</param>
/// <param name="options">The options for the merging in the cherry-pick operation.</param>
/// <param name="earlyStop">True if the cherry-pick stopped early due to conflicts</param>
/// <returns>The <see cref="IndexHandle"/> containing the cherry-pick result tree and any conflicts</returns>
private IndexHandle CherryPickCommit(Commit cherryPickCommit, Commit cherryPickOnto, int mainline, MergeTreeOptions options, out bool earlyStop)
{
GitMergeFlag mergeFlags = GitMergeFlag.GIT_MERGE_NORMAL;
if (options.SkipReuc)
{
mergeFlags |= GitMergeFlag.GIT_MERGE_SKIP_REUC;
}
if (options.FindRenames)
{
mergeFlags |= GitMergeFlag.GIT_MERGE_FIND_RENAMES;
}
if (options.FailOnConflict)
{
mergeFlags |= GitMergeFlag.GIT_MERGE_FAIL_ON_CONFLICT;
}
var mergeOptions = new GitMergeOpts
{
Version = 1,
MergeFileFavorFlags = options.MergeFileFavor,
MergeTreeFlags = mergeFlags,
RenameThreshold = (uint)options.RenameThreshold,
TargetLimit = (uint)options.TargetLimit,
};
using (var cherryPickOntoHandle = Proxy.git_object_lookup(repo.Handle, cherryPickOnto.Id, GitObjectType.Commit))
using (var cherryPickCommitHandle = Proxy.git_object_lookup(repo.Handle, cherryPickCommit.Id, GitObjectType.Commit))
{
var indexHandle = Proxy.git_cherrypick_commit(repo.Handle, cherryPickCommitHandle, cherryPickOntoHandle, (uint)mainline, mergeOptions, out earlyStop);
return indexHandle;
}
}
/// <summary>
/// Packs objects in the <see cref="ObjectDatabase"/> and write a pack (.pack) and index (.idx) files for them.
/// For internal use only.
/// </summary>
/// <param name="options">Packing options</param>
/// <param name="packDelegate">Packing action</param>
/// <returns>Packing results</returns>
private PackBuilderResults InternalPack(PackBuilderOptions options, Action<PackBuilder> packDelegate)
{
Ensure.ArgumentNotNull(options, "options");
Ensure.ArgumentNotNull(packDelegate, "packDelegate");
PackBuilderResults results = new PackBuilderResults();
using (PackBuilder builder = new PackBuilder(repo))
{
// set pre-build options
builder.SetMaximumNumberOfThreads(options.MaximumNumberOfThreads);
// call the provided action
packDelegate(builder);
// writing the pack and index files
builder.Write(options.PackDirectoryPath);
// adding the results to the PackBuilderResults object
results.WrittenObjectsCount = builder.WrittenObjectsCount;
}
return results;
}
/// <summary>
/// Performs a revert of <paramref name="revertCommit"/> onto <paramref name="revertOnto"/> commit.
/// </summary>
/// <param name="revertCommit">The commit to revert.</param>
/// <param name="revertOnto">The commit to revert onto.</param>
/// <param name="mainline">Which commit to consider the parent for the diff when reverting a merge commit.</param>
/// <param name="options">The options for the merging in the revert operation.</param>
/// <returns>A result containing a <see cref="Tree"/> if the revert was successful and a list of <see cref="Conflict"/>s if it is not.</returns>
public virtual MergeTreeResult RevertCommit(Commit revertCommit, Commit revertOnto, int mainline, MergeTreeOptions options)
{
Ensure.ArgumentNotNull(revertCommit, "revertCommit");
Ensure.ArgumentNotNull(revertOnto, "revertOnto");
options = options ?? new MergeTreeOptions();
// We throw away the index after looking at the conflicts, so we'll never need the REUC
// entries to be there
GitMergeFlag mergeFlags = GitMergeFlag.GIT_MERGE_NORMAL | GitMergeFlag.GIT_MERGE_SKIP_REUC;
if (options.FindRenames)
{
mergeFlags |= GitMergeFlag.GIT_MERGE_FIND_RENAMES;
}
if (options.FailOnConflict)
{
mergeFlags |= GitMergeFlag.GIT_MERGE_FAIL_ON_CONFLICT;
}
var opts = new GitMergeOpts
{
Version = 1,
MergeFileFavorFlags = options.MergeFileFavor,
MergeTreeFlags = mergeFlags,
RenameThreshold = (uint)options.RenameThreshold,
TargetLimit = (uint)options.TargetLimit
};
bool earlyStop;
using (var revertOntoHandle = Proxy.git_object_lookup(repo.Handle, revertOnto.Id, GitObjectType.Commit))
using (var revertCommitHandle = Proxy.git_object_lookup(repo.Handle, revertCommit.Id, GitObjectType.Commit))
using (var indexHandle = Proxy.git_revert_commit(repo.Handle, revertCommitHandle, revertOntoHandle, (uint)mainline, opts, out earlyStop))
{
MergeTreeResult revertTreeResult;
// Stopped due to FailOnConflict so there's no index or conflict list
if (earlyStop)
{
return new MergeTreeResult(new Conflict[] { });
}
if (Proxy.git_index_has_conflicts(indexHandle))
{
List<Conflict> conflicts = new List<Conflict>();
Conflict conflict;
using (ConflictIteratorHandle iterator = Proxy.git_index_conflict_iterator_new(indexHandle))
{
while ((conflict = Proxy.git_index_conflict_next(iterator)) != null)
{
conflicts.Add(conflict);
}
}
revertTreeResult = new MergeTreeResult(conflicts);
}
else
{
var treeId = Proxy.git_index_write_tree_to(indexHandle, repo.Handle);
revertTreeResult = new MergeTreeResult(this.repo.Lookup<Tree>(treeId));
}
return revertTreeResult;
}
}
}
}
| |
// 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.
//
// Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused.
//
namespace System.Text
{
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
// Encodes text into and out of UTF-32. UTF-32 is a way of writing
// Unicode characters with a single storage unit (32 bits) per character,
//
// The UTF-32 byte order mark is simply the Unicode byte order mark
// (0x00FEFF) written in UTF-32 (0x0000FEFF or 0xFFFE0000). The byte order
// mark is used mostly to distinguish UTF-32 text from other encodings, and doesn't
// switch the byte orderings.
[Serializable]
public sealed class UTF32Encoding : Encoding
{
/*
words bits UTF-32 representation
----- ---- -----------------------------------
1 16 00000000 00000000 xxxxxxxx xxxxxxxx
2 21 00000000 000xxxxx hhhhhhll llllllll
----- ---- -----------------------------------
Surrogate:
Real Unicode value = (HighSurrogate - 0xD800) * 0x400 + (LowSurrogate - 0xDC00) + 0x10000
*/
// Used by Encoding.UTF32/BigEndianUTF32 for lazy initialization
// The initialization code will not be run until a static member of the class is referenced
internal static readonly UTF32Encoding s_default = new UTF32Encoding(bigEndian: false, byteOrderMark: true);
internal static readonly UTF32Encoding s_bigEndianDefault = new UTF32Encoding(bigEndian: true, byteOrderMark: true);
private bool emitUTF32ByteOrderMark = false;
private bool isThrowException = false;
private bool bigEndian = false;
public UTF32Encoding(): this(false, true, false)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark):
this(bigEndian, byteOrderMark, false)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidCharacters):
base(bigEndian ? 12001 : 12000)
{
this.bigEndian = bigEndian;
this.emitUTF32ByteOrderMark = byteOrderMark;
this.isThrowException = throwOnInvalidCharacters;
// Encoding's constructor already did this, but it'll be wrong if we're throwing exceptions
if (this.isThrowException)
SetDefaultFallbacks();
}
internal override void SetDefaultFallbacks()
{
// For UTF-X encodings, we use a replacement fallback with an empty string
if (this.isThrowException)
{
this.encoderFallback = EncoderFallback.ExceptionFallback;
this.decoderFallback = DecoderFallback.ExceptionFallback;
}
else
{
this.encoderFallback = new EncoderReplacementFallback("\xFFFD");
this.decoderFallback = new DecoderReplacementFallback("\xFFFD");
}
}
// NOTE: Many methods in this class forward to EncodingForwarder for
// validating arguments/wrapping the unsafe methods in this class
// which do the actual work. That class contains
// shared logic for doing this which is used by
// ASCIIEncoding, EncodingNLS, UnicodeEncoding, UTF32Encoding,
// UTF7Encoding, and UTF8Encoding.
// The reason the code is separated out into a static class, rather
// than a base class which overrides all of these methods for us
// (which is what EncodingNLS is for internal Encodings) is because
// that's really more of an implementation detail so it's internal.
// At the same time, C# doesn't allow a public class subclassing an
// internal/private one, so we end up having to re-override these
// methods in all of the public Encodings + EncodingNLS.
// Returns the number of bytes required to encode a range of characters in
// a character array.
public override int GetByteCount(char[] chars, int index, int count)
{
return EncodingForwarder.GetByteCount(this, chars, index, count);
}
public override int GetByteCount(String s)
{
return EncodingForwarder.GetByteCount(this, s);
}
[CLSCompliant(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
return EncodingForwarder.GetByteCount(this, chars, count);
}
public override int GetBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
return EncodingForwarder.GetBytes(this, s, charIndex, charCount, bytes, byteIndex);
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. An exception occurs if the byte array is not large
// enough to hold the complete encoding of the characters. The
// GetByteCount method can be used to determine the exact number of
// bytes that will be produced for a given range of characters.
// Alternatively, the GetMaxByteCount method can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
public override int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
}
[CLSCompliant(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
}
// Returns the number of characters produced by decoding a range of bytes
// in a byte array.
public override int GetCharCount(byte[] bytes, int index, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, index, count);
}
[CLSCompliant(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, count);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
}
[CLSCompliant(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
}
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
public override String GetString(byte[] bytes, int index, int count)
{
return EncodingForwarder.GetString(this, bytes, index, count);
}
// End of overridden methods which use EncodingForwarder
internal override unsafe int GetByteCount(char *chars, int count, EncoderNLS encoder)
{
Debug.Assert(chars!=null, "[UTF32Encoding.GetByteCount]chars!=null");
Debug.Assert(count >=0, "[UTF32Encoding.GetByteCount]count >=0");
char* end = chars + count;
char* charStart = chars;
int byteCount = 0;
char highSurrogate = '\0';
// For fallback we may need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
if (encoder != null)
{
highSurrogate = encoder.charLeftOver;
fallbackBuffer = encoder.FallbackBuffer;
// We mustn't have left over fallback data when counting
if (fallbackBuffer.Remaining > 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, end, encoder, false);
char ch;
TryAgain:
while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < end)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Do we need a low surrogate?
if (highSurrogate != '\0')
{
//
// In previous char, we encounter a high surrogate, so we are expecting a low surrogate here.
//
if (Char.IsLowSurrogate(ch))
{
// They're all legal
highSurrogate = '\0';
//
// One surrogate pair will be translated into 4 bytes UTF32.
//
byteCount += 4;
continue;
}
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
Debug.Assert(chars > charStart,
"[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate");
chars--;
// Do the fallback
fallbackBuffer.InternalFallback(highSurrogate, ref chars);
// We're going to fallback the old high surrogate.
highSurrogate = '\0';
continue;
}
// Do we have another high surrogate?
if (Char.IsHighSurrogate(ch))
{
//
// We'll have a high surrogate to check next time.
//
highSurrogate = ch;
continue;
}
// Check for illegal characters
if (Char.IsLowSurrogate(ch))
{
// We have a leading low surrogate, do the fallback
fallbackBuffer.InternalFallback(ch, ref chars);
// Try again with fallback buffer
continue;
}
// We get to add the character (4 bytes UTF32)
byteCount += 4;
}
// May have to do our last surrogate
if ((encoder == null || encoder.MustFlush) && highSurrogate > 0)
{
// We have to do the fallback for the lonely high surrogate
fallbackBuffer.InternalFallback(highSurrogate, ref chars);
highSurrogate = (char)0;
goto TryAgain;
}
// Check for overflows.
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString(
"ArgumentOutOfRange_GetByteCountOverflow"));
// Shouldn't have anything in fallback buffer for GetByteCount
// (don't have to check m_throwOnOverflow for count)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetByteCount]Expected empty fallback buffer at end");
// Return our count
return byteCount;
}
internal override unsafe int GetBytes(char *chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
Debug.Assert(chars!=null, "[UTF32Encoding.GetBytes]chars!=null");
Debug.Assert(bytes!=null, "[UTF32Encoding.GetBytes]bytes!=null");
Debug.Assert(byteCount >=0, "[UTF32Encoding.GetBytes]byteCount >=0");
Debug.Assert(charCount >=0, "[UTF32Encoding.GetBytes]charCount >=0");
char* charStart = chars;
char* charEnd = chars + charCount;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
char highSurrogate = '\0';
// For fallback we may need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
if (encoder != null)
{
highSurrogate = encoder.charLeftOver;
fallbackBuffer = encoder.FallbackBuffer;
// We mustn't have left over fallback data when not converting
if (encoder.m_throwOnOverflow && fallbackBuffer.Remaining > 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
char ch;
TryAgain:
while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Do we need a low surrogate?
if (highSurrogate != '\0')
{
//
// In previous char, we encountered a high surrogate, so we are expecting a low surrogate here.
//
if (Char.IsLowSurrogate(ch))
{
// Is it a legal one?
uint iTemp = GetSurrogate(highSurrogate, ch);
highSurrogate = '\0';
//
// One surrogate pair will be translated into 4 bytes UTF32.
//
if (bytes+3 >= byteEnd)
{
// Don't have 4 bytes
if (fallbackBuffer.bFallingBack)
{
fallbackBuffer.MovePrevious(); // Aren't using these 2 fallback chars
fallbackBuffer.MovePrevious();
}
else
{
// If we don't have enough room, then either we should've advanced a while
// or we should have bytes==byteStart and throw below
Debug.Assert(chars > charStart + 1 || bytes == byteStart,
"[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
chars-=2; // Aren't using those 2 chars
}
ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
highSurrogate = (char)0; // Nothing left over (we backed up to start of pair if supplimentary)
break;
}
if (bigEndian)
{
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0
*(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF
*(bytes++) = (byte)(iTemp); // Implies & 0xFF
}
else
{
*(bytes++) = (byte)(iTemp); // Implies & 0xFF
*(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF
*(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0
*(bytes++) = (byte)(0x00);
}
continue;
}
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
Debug.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate");
chars--;
// Do the fallback
fallbackBuffer.InternalFallback(highSurrogate, ref chars);
// We're going to fallback the old high surrogate.
highSurrogate = '\0';
continue;
}
// Do we have another high surrogate?, if so remember it
if (Char.IsHighSurrogate(ch))
{
//
// We'll have a high surrogate to check next time.
//
highSurrogate = ch;
continue;
}
// Check for illegal characters (low surrogate)
if (Char.IsLowSurrogate(ch))
{
// We have a leading low surrogate, do the fallback
fallbackBuffer.InternalFallback(ch, ref chars);
// Try again with fallback buffer
continue;
}
// We get to add the character, yippee.
if (bytes+3 >= byteEnd)
{
// Don't have 4 bytes
if (fallbackBuffer.bFallingBack)
fallbackBuffer.MovePrevious(); // Aren't using this fallback char
else
{
// Must've advanced already
Debug.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if normal character");
chars--; // Aren't using this char
}
ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
break; // Didn't throw, stop
}
if (bigEndian)
{
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF
*(bytes++) = (byte)(ch); // Implies & 0xFF
}
else
{
*(bytes++) = (byte)(ch); // Implies & 0xFF
*(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(0x00);
}
}
// May have to do our last surrogate
if ((encoder == null || encoder.MustFlush) && highSurrogate > 0)
{
// We have to do the fallback for the lonely high surrogate
fallbackBuffer.InternalFallback(highSurrogate, ref chars);
highSurrogate = (char)0;
goto TryAgain;
}
// Fix our encoder if we have one
Debug.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush),
"[UTF32Encoding.GetBytes]Expected encoder to be flushed.");
if (encoder != null)
{
// Remember our left over surrogate (or 0 if flushing)
encoder.charLeftOver = highSurrogate;
// Need # chars used
encoder.m_charsUsed = (int)(chars-charStart);
}
// return the new length
return (int)(bytes - byteStart);
}
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
Debug.Assert(bytes!=null, "[UTF32Encoding.GetCharCount]bytes!=null");
Debug.Assert(count >=0, "[UTF32Encoding.GetCharCount]count >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// None so far!
int charCount = 0;
byte* end = bytes + count;
byte* byteStart = bytes;
// Set up decoder
int readCount = 0;
uint iChar = 0;
// For fallback we may need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
// See if there's anything in our decoder
if (decoder != null)
{
readCount = decoder.readByteCount;
iChar = (uint)decoder.iChar;
fallbackBuffer = decoder.FallbackBuffer;
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for chars or count)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at start");
}
else
{
fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(byteStart, null);
// Loop through our input, 4 characters at a time!
while (bytes < end && charCount >= 0)
{
// Get our next character
if(bigEndian)
{
// Scoot left and add it to the bottom
iChar <<= 8;
iChar += *(bytes++);
}
else
{
// Scoot right and add it to the top
iChar >>= 8;
iChar += (uint)(*(bytes++)) << 24;
}
readCount++;
// See if we have all the bytes yet
if (readCount < 4)
continue;
// Have the bytes
readCount = 0;
// See if its valid to encode
if ( iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
{
// Need to fall back these 4 bytes
byte[] fallbackBytes;
if (this.bigEndian)
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) };
}
else
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)),
unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) };
}
charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes);
// Ignore the illegal character
iChar = 0;
continue;
}
// Ok, we have something we can add to our output
if (iChar >= 0x10000)
{
// Surrogates take 2
charCount++;
}
// Add the rest of the surrogate or our normal character
charCount++;
// iChar is back to 0
iChar = 0;
}
// See if we have something left over that has to be decoded
if (readCount > 0 && (decoder == null || decoder.MustFlush))
{
// Oops, there's something left over with no place to go.
byte[] fallbackBytes = new byte[readCount];
if (this.bigEndian)
{
while(readCount > 0)
{
fallbackBytes[--readCount] = unchecked((byte)iChar);
iChar >>= 8;
}
}
else
{
while (readCount > 0)
{
fallbackBytes[--readCount] = unchecked((byte)(iChar>>24));
iChar <<= 8;
}
}
charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes);
}
// Check for overflows.
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for chars or count)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at end");
// Return our count
return charCount;
}
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
Debug.Assert(chars!=null, "[UTF32Encoding.GetChars]chars!=null");
Debug.Assert(bytes!=null, "[UTF32Encoding.GetChars]bytes!=null");
Debug.Assert(byteCount >=0, "[UTF32Encoding.GetChars]byteCount >=0");
Debug.Assert(charCount >=0, "[UTF32Encoding.GetChars]charCount >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// None so far!
char* charStart = chars;
char* charEnd = chars + charCount;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
// See if there's anything in our decoder (but don't clear it yet)
int readCount = 0;
uint iChar = 0;
// For fallback we may need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
// See if there's anything in our decoder
if (decoder != null)
{
readCount = decoder.readByteCount;
iChar = (uint)decoder.iChar;
fallbackBuffer = baseDecoder.FallbackBuffer;
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at start");
}
else
{
fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(bytes, chars + charCount);
// Loop through our input, 4 characters at a time!
while (bytes < byteEnd)
{
// Get our next character
if(bigEndian)
{
// Scoot left and add it to the bottom
iChar <<= 8;
iChar += *(bytes++);
}
else
{
// Scoot right and add it to the top
iChar >>= 8;
iChar += (uint)(*(bytes++)) << 24;
}
readCount++;
// See if we have all the bytes yet
if (readCount < 4)
continue;
// Have the bytes
readCount = 0;
// See if its valid to encode
if ( iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
{
// Need to fall back these 4 bytes
byte[] fallbackBytes;
if (this.bigEndian)
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) };
}
else
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)),
unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) };
}
// Chars won't be updated unless this works.
if (!fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref chars))
{
// Couldn't fallback, throw or wait til next time
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (bad surrogate)");
bytes-=4; // get back to where we were
iChar=0; // Remembering nothing
fallbackBuffer.InternalReset();
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
// Ignore the illegal character
iChar = 0;
continue;
}
// Ok, we have something we can add to our output
if (iChar >= 0x10000)
{
// Surrogates take 2
if (chars >= charEnd - 1)
{
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (surrogate)");
bytes-=4; // get back to where we were
iChar=0; // Remembering nothing
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
*(chars++) = GetHighSurrogate(iChar);
iChar = GetLowSurrogate(iChar);
}
// Bounds check for normal character
else if (chars >= charEnd)
{
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (normal char)");
bytes-=4; // get back to where we were
iChar=0; // Remembering nothing
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
// Add the rest of the surrogate or our normal character
*(chars++) = (char)iChar;
// iChar is back to 0
iChar = 0;
}
// See if we have something left over that has to be decoded
if (readCount > 0 && (decoder == null || decoder.MustFlush))
{
// Oops, there's something left over with no place to go.
byte[] fallbackBytes = new byte[readCount];
int tempCount = readCount;
if (this.bigEndian)
{
while(tempCount > 0)
{
fallbackBytes[--tempCount] = unchecked((byte)iChar);
iChar >>= 8;
}
}
else
{
while (tempCount > 0)
{
fallbackBytes[--tempCount] = unchecked((byte)(iChar>>24));
iChar <<= 8;
}
}
if (!fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref chars))
{
// Couldn't fallback.
fallbackBuffer.InternalReset();
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
// Stop here, didn't throw, backed up, so still nothing in buffer
}
else
{
// Don't clear our decoder unless we could fall it back.
// If we caught the if above, then we're a convert() and will catch this next time.
readCount = 0;
iChar = 0;
}
}
// Remember any left over stuff, clearing buffer as well for MustFlush
if (decoder != null)
{
decoder.iChar = (int)iChar;
decoder.readByteCount = readCount;
decoder.m_bytesUsed = (int)(bytes - byteStart);
}
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at end");
// Return our count
return (int)(chars - charStart);
}
private uint GetSurrogate(char cHigh, char cLow)
{
return (((uint)cHigh - 0xD800) * 0x400) + ((uint)cLow - 0xDC00) + 0x10000;
}
private char GetHighSurrogate(uint iChar)
{
return (char)((iChar - 0x10000) / 0x400 + 0xD800);
}
private char GetLowSurrogate(uint iChar)
{
return (char)((iChar - 0x10000) % 0x400 + 0xDC00);
}
public override Decoder GetDecoder()
{
return new UTF32Decoder(this);
}
public override Encoder GetEncoder()
{
return new EncoderNLS(this);
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback
long byteCount = (long)charCount + 1;
if (EncoderFallback.MaxCharCount > 1)
byteCount *= EncoderFallback.MaxCharCount;
// 4 bytes per char
byteCount *= 4;
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(byteCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// A supplementary character becomes 2 surrogate characters, so 4 input bytes becomes 2 chars,
// plus we may have 1 surrogate char left over if the decoder has 3 bytes in it already for a non-bmp char.
// Have to add another one because 1/2 == 0, but 3 bytes left over could be 2 char surrogate pair
int charCount = (byteCount / 2) + 2;
// Also consider fallback because our input bytes could be out of range of unicode.
// Since fallback would fallback 4 bytes at a time, we'll only fall back 1/2 of MaxCharCount.
if (DecoderFallback.MaxCharCount > 2)
{
// Multiply time fallback size
charCount *= DecoderFallback.MaxCharCount;
// We were already figuring 2 chars per 4 bytes, but fallback will be different #
charCount /= 2;
}
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
return (int)charCount;
}
public override byte[] GetPreamble()
{
if (emitUTF32ByteOrderMark)
{
// Allocate new array to prevent users from modifying it.
if (bigEndian)
{
return new byte[4] { 0x00, 0x00, 0xFE, 0xFF };
}
else
{
return new byte[4] { 0xFF, 0xFE, 0x00, 0x00 }; // 00 00 FE FF
}
}
else
return EmptyArray<Byte>.Value;
}
public override bool Equals(Object value)
{
UTF32Encoding that = value as UTF32Encoding;
if (that != null)
{
return (emitUTF32ByteOrderMark == that.emitUTF32ByteOrderMark) &&
(bigEndian == that.bigEndian) &&
// (isThrowException == that.isThrowException) && // same as encoder/decoderfallback being exceptions
(EncoderFallback.Equals(that.EncoderFallback)) &&
(DecoderFallback.Equals(that.DecoderFallback));
}
return (false);
}
public override int GetHashCode()
{
//Not great distribution, but this is relatively unlikely to be used as the key in a hashtable.
return this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() +
CodePage + (emitUTF32ByteOrderMark?4:0) + (bigEndian?8:0);
}
[Serializable]
internal class UTF32Decoder : DecoderNLS
{
// Need a place to store any extra bytes we may have picked up
internal int iChar = 0;
internal int readByteCount = 0;
public UTF32Decoder(UTF32Encoding encoding) : base(encoding)
{
// base calls reset
}
public override void Reset()
{
this.iChar = 0;
this.readByteCount = 0;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
// Anything left in our decoder?
internal override bool HasState
{
get
{
// ReadByteCount is our flag. (iChar==0 doesn't mean much).
return (this.readByteCount != 0);
}
}
}
}
}
| |
using ExampleApp;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace ExampleAppWPF
{
public class SearchMenuView : MenuView, INotifyPropertyChanged
{
private TextBox m_editText;
private MenuListAdapter m_adapter;
private Grid m_searchBox;
private ListBox m_resultsList;
private ScrollViewer m_resultsListScrollViewer;
private MenuListAdapter m_resultListAdapter;
private Grid m_resultsSpinner;
private TextBlock m_resultsCount;
private Button m_resultsClearButton;
private ScrollViewer m_menuOptionsView;
private FrameworkElement m_searchArrow;
private FrameworkElement m_resultsSeparator;
private RepeatButton m_searchResultsScrollButton;
private Image m_searchResultsFade;
private Grid m_searchResultsButtonAndFadeContainer;
private Grid m_resultsCountContainer;
private bool m_searchInFlight;
private bool m_hasResults;
private bool m_hasTagSearch;
private double m_scrollSpeed;
private ControlClickHandler m_menuListClickHandler;
private ControlClickHandler m_resultsListClickHandler;
private Storyboard m_searchInputOpen;
private Storyboard m_searchInputClose;
private Storyboard m_searchInputTextOpen;
private Storyboard m_searchInputTextClose;
private Storyboard m_searchArrowOpen;
private Storyboard m_searchArrowClosed;
private WindowInteractionTouchHandler m_touchHandler;
private TouchDevice m_searchResultsListCurrentTouchDevice;
private bool m_editingText;
public event PropertyChangedEventHandler PropertyChanged;
private ImageSource m_searchIconOffImageSource;
private ImageSource m_searchIconOnImageSource;
private ImageSource m_closeIconOffImageSource;
private ImageSource m_closeIconOnImageSource;
private ImageSource m_iconOffImageSource;
private ImageSource m_iconOnImageSource;
public ImageSource SearchMenuIconOffImageSource
{
get
{
return m_iconOffImageSource;
}
set
{
m_iconOffImageSource = value;
OnPropertyChanged("SearchMenuIconOffImageSource");
}
}
public ImageSource SearchMenuIconOnImageSource
{
get
{
return m_iconOnImageSource;
}
set
{
m_iconOnImageSource = value;
OnPropertyChanged("SearchMenuIconOnImageSource");
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
static SearchMenuView()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(SearchMenuView), new FrameworkPropertyMetadata(typeof(SearchMenuView)));
}
public SearchMenuView(IntPtr nativeCallerPointer, bool isInKioskMode) : base(nativeCallerPointer, isInKioskMode)
{
MainWindow mainWindow = (MainWindow)Application.Current.MainWindow;
mainWindow.MainGrid.Children.Add(this);
Loaded += MainWindow_Loaded;
mainWindow.SizeChanged += PerformLayout;
m_searchInFlight = false;
m_hasResults = false;
m_hasTagSearch = false;
m_touchHandler = new WindowInteractionTouchHandler(this, false, true, true);
m_editingText = false;
}
public Button GetSearchButton()
{
return m_menuIcon;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
PerformLayout(sender, null);
m_menuViewContainer.SizeChanged += OnMenuContainerSizeChanged;
m_resultsListScrollViewer = (ScrollViewer) VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(m_resultsList, 0), 0);
m_resultsListScrollViewer.ScrollChanged += OnSearchResultsScrolled;
m_resultsListScrollViewer.ManipulationBoundaryFeedback += OnResultsListBoundaryFeedback;
}
private new void PerformLayout(object sender, SizeChangedEventArgs e)
{
var screenWidth = m_mainWindow.MainGrid.ActualWidth;
var totalWidth = m_mainContainer.ActualWidth + m_menuIcon.ActualWidth;
m_onScreenPos = -(screenWidth / 2);
m_offScreenPos = -(screenWidth / 2) - (totalWidth / 2);
base.PerformLayout(sender, e);
}
private void OnMenuContainerSizeChanged(object sender, SizeChangedEventArgs e)
{
m_resultsList.MaxHeight = CalcResultOptionsViewMaxHeight();
m_menuOptionsView.MaxHeight = CalcMenuOptionsViewMaxHeight();
}
private double CalcResultOptionsViewMaxHeight()
{
var menuViewHeight = m_menuViewContainer.ActualHeight;
var searchBoxBackgroundDefaultHeight = m_backgroundRectangle.ActualHeight;
var menuOptionsViewDefaultHeight = m_menuOptionsView.ActualHeight;
var separatorHeight = m_resultsSeparator.ActualHeight;
var seperatorCount = 2;
return Math.Max(0.0, menuViewHeight - searchBoxBackgroundDefaultHeight - menuOptionsViewDefaultHeight - seperatorCount * separatorHeight);
}
private double CalcMenuOptionsViewMaxHeight()
{
var menuViewHeight = m_menuViewContainer.ActualHeight;
var searchBoxBackgroundDefaultHeight = m_backgroundRectangle.ActualHeight;
var separatorHeight = m_resultsSeparator.ActualHeight;
return Math.Max(0.0, menuViewHeight - searchBoxBackgroundDefaultHeight + 2 * separatorHeight);
}
protected override Size ArrangeOverride(Size arrangeBounds)
{
m_resultsList.MaxHeight = CalcResultOptionsViewMaxHeight();
m_menuOptionsView.MaxHeight = CalcMenuOptionsViewMaxHeight();
return base.ArrangeOverride(arrangeBounds);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
m_menuOptionsView = (ScrollViewer)GetTemplateChild("MenuOptionsView");
m_resultsSpinner = (Grid)GetTemplateChild("SearchResultsSpinner");
m_resultsCount = (TextBlock)GetTemplateChild("SearchResultCount");
m_resultsCountContainer = (Grid)GetTemplateChild("SearchResultCountContainer");
m_menuViewContainer = (Grid)GetTemplateChild("SearchMenuViewContainer");
m_backgroundRectangle = (Rectangle)GetTemplateChild("BackgroundRect");
m_searchBox = (Grid)GetTemplateChild("SearchBox");
m_searchArrow = (FrameworkElement)GetTemplateChild("SearchArrow");
m_resultsSeparator = (FrameworkElement)GetTemplateChild("ResultsListSeparator");
m_searchResultsFade = (Image)GetTemplateChild("SearchResultsFade");
m_searchResultsButtonAndFadeContainer = (Grid)GetTemplateChild("SearchResultsButtonAndFadeContainer");
m_searchResultsScrollButton = (RepeatButton)GetTemplateChild("SearchResultsScrollButton");
m_searchResultsScrollButton.Click += OnResultsScrollButtonMouseDown;
m_searchResultsScrollButton.PreviewMouseWheel += OnResultsMenuScrollWheel;
m_searchResultsScrollButton.MouseUp += OnResultsScrollButtonMouseUp;
m_searchResultsScrollButton.MouseLeave += OnResultsScrollButtonMouseLeave;
m_resultsClearButton = (Button)GetTemplateChild("SearchClear");
m_resultsClearButton.Click += OnResultsClear;
m_list = (ListBox)GetTemplateChild("SecondaryMenuItemList");
m_menuListClickHandler = new ControlClickHandler(OnMenuListItemSelected, m_list);
m_list.PreviewMouseWheel += OnMenuScrollWheel;
m_resultsList = (ListBox)GetTemplateChild("SearchResultsList");
m_resultsList.TouchDown += new EventHandler<TouchEventArgs>(OnSearchResultsListTouchDown);
m_resultsList.TouchUp += new EventHandler<TouchEventArgs>(OnSearchResultsListTouchUp);
m_resultsList.TouchLeave += new EventHandler<TouchEventArgs>(OnSearchResultsListTouchLeave);
m_resultsList.LostTouchCapture += new EventHandler<TouchEventArgs>(OnSearchResultsListLostTouchCapture);
m_resultsListClickHandler = new ControlClickHandler(OnResultsListItemsSelected, m_resultsList);
m_resultsList.PreviewMouseWheel += OnResultsMenuScrollWheel;
m_menuIcon = (Button)GetTemplateChild("SecondaryMenuDragTabView");
m_menuIconGrid = (Grid)GetTemplateChild("SearchIconGrid");
m_menuIcon.Click += OnIconClick;
m_editText = (TextBox)GetTemplateChild("SearchInputBox");
m_editText.KeyDown += OnKeyDown;
m_editText.GotFocus += OnSearchBoxSelected;
m_editText.LostFocus += OnSearchBoxUnSelected;
m_editText.TextChanged += OnSearchBoxTextChanged;
m_mainContainer = (Grid)GetTemplateChild("SerchMenuMainContainer");
var itemShutterOpenStoryboard = ((Storyboard)Template.Resources["ItemShutterOpen"]).Clone();
var itemShutterCloseStoryboard = ((Storyboard)Template.Resources["ItemShutterClose"]).Clone();
var slideInItemStoryboard = ((Storyboard)Template.Resources["SlideInNewItems"]).Clone();
var slideOutItemStoryboard = ((Storyboard)Template.Resources["SlideOutOldItems"]).Clone();
string searchAnimString = "SearchAnim";
string openMenuViewIconString = "OpenSearchViewIcon";
m_openMenuIconAnim = ((Storyboard)Template.Resources[openMenuViewIconString]).Clone();
XamlHelpers.UpdateThicknessAnimationMarginValue(m_openMenuIconAnim, searchAnimString + openMenuViewIconString);
string closeMenuViewIconString = "CloseSearchViewIcon";
m_closeMenuIconAnim = ((Storyboard)Template.Resources[closeMenuViewIconString]).Clone();
XamlHelpers.UpdateThicknessAnimationMarginValue(m_closeMenuIconAnim, searchAnimString + closeMenuViewIconString);
string openMenuContainerString = "OpenSearchContainer";
m_openMenuContainerAnim = ((Storyboard)Template.Resources[openMenuContainerString]).Clone();
XamlHelpers.UpdateThicknessAnimationMarginValue(m_openMenuContainerAnim, searchAnimString + openMenuContainerString);
string closeMenuContainerString = "CloseSearchContainer";
m_closeMenuContainerAnim = ((Storyboard)Template.Resources[closeMenuContainerString]).Clone();
XamlHelpers.UpdateThicknessAnimationMarginValue(m_closeMenuContainerAnim, searchAnimString + closeMenuContainerString);
string openBackgroundRectString = "OpenBackgroundRect";
m_openBackgroundRect = ((Storyboard)Template.Resources[openBackgroundRectString]).Clone();
XamlHelpers.UpdateThicknessAnimationMarginValue(m_openBackgroundRect, searchAnimString + openBackgroundRectString);
string closeBackgroundRectString = "CloseBackgroundRect";
m_closeBackgroundRect = ((Storyboard)Template.Resources[closeBackgroundRectString]).Clone();
XamlHelpers.UpdateThicknessAnimationMarginValue(m_closeBackgroundRect, searchAnimString + closeBackgroundRectString);
string openSearchInputBoxString = "OpenSearchInputBox";
m_searchInputOpen = ((Storyboard)Template.Resources[openSearchInputBoxString]).Clone();
XamlHelpers.UpdateThicknessAnimationMarginValue(m_searchInputOpen, searchAnimString + openSearchInputBoxString);
m_searchInputClose = ((Storyboard)Template.Resources["CloseSearchInputBox"]).Clone();
m_searchInputTextOpen = ((Storyboard)Template.Resources["OpenSearchInputBoxText"]).Clone();
m_searchInputTextClose = ((Storyboard)Template.Resources["CloseSearchInputBoxText"]).Clone();
string openSearchArrowString = "OpenSearchArrow";
m_searchArrowOpen = ((Storyboard)Template.Resources[openSearchArrowString]).Clone();
XamlHelpers.UpdateThicknessAnimationMarginValue(m_searchArrowOpen, searchAnimString + openSearchArrowString);
string closeSearchArrowString = "CloseSearchArrow";
m_searchArrowClosed = ((Storyboard)Template.Resources[closeSearchArrowString]).Clone();
XamlHelpers.UpdateThicknessAnimationMarginValue(m_searchArrowClosed, searchAnimString + closeSearchArrowString);
m_adapter = new MenuListAdapter(false, m_list, slideInItemStoryboard, slideOutItemStoryboard, itemShutterOpenStoryboard, itemShutterCloseStoryboard, "SubMenuItemPanel", m_isInKioskMode);
m_resultListAdapter = new MenuListAdapter(false, m_resultsList, slideInItemStoryboard, slideOutItemStoryboard, itemShutterOpenStoryboard, itemShutterCloseStoryboard, "SearchResultPanel", m_isInKioskMode);
m_scrollSpeed = (double) Application.Current.Resources["ScrollViewButtonScrollSpeed"];
m_searchIconOffImageSource = (ImageSource) Application.Current.Resources["ButtonSearchOffImage"];
m_searchIconOnImageSource = (ImageSource) Application.Current.Resources["ButtonSearchOnImage"];
m_closeIconOffImageSource = (ImageSource) Application.Current.Resources["ButtonSearchCloseOffImage"];
m_closeIconOnImageSource = (ImageSource) Application.Current.Resources["ButtonSearchCloseOnImage"];
SearchMenuIconOffImageSource = m_searchIconOffImageSource;
SearchMenuIconOnImageSource = m_searchIconOnImageSource;
}
public void RemoveSearchQueryResults()
{
HideSearchResultCount();
if (!m_editingText)
{
m_editText.Text = String.Empty;
}
m_hasTagSearch = false;
}
private void OnSearchResultsScrolled(object sender, RoutedEventArgs e)
{
if (m_resultsListScrollViewer.VerticalOffset == m_resultsListScrollViewer.ScrollableHeight)
{
m_searchResultsButtonAndFadeContainer.Visibility = Visibility.Collapsed;
m_searchResultsFade.Visibility = Visibility.Hidden;
m_searchResultsScrollButton.Visibility = Visibility.Hidden;
}
else
{
m_searchResultsButtonAndFadeContainer.Visibility = Visibility.Visible;
m_searchResultsFade.Visibility = Visibility.Visible;
m_searchResultsScrollButton.Visibility = Visibility.Visible;
}
m_resultsList.Items.Refresh();
}
private void OnResultsScrollButtonMouseDown(object sender, RoutedEventArgs e)
{
m_resultsListScrollViewer.IsEnabled = false;
m_resultsListScrollViewer.ScrollToVerticalOffset(m_resultsListScrollViewer.VerticalOffset + m_scrollSpeed);
}
private void OnResultsScrollButtonMouseUp(object sender, RoutedEventArgs e)
{
m_resultsListScrollViewer.IsEnabled = true;
}
private void OnResultsScrollButtonMouseLeave(object sender, RoutedEventArgs e)
{
m_resultsListScrollViewer.IsEnabled = true;
}
private void OnResultsListBoundaryFeedback(object sender, ManipulationBoundaryFeedbackEventArgs e)
{
e.Handled = true;
m_resultsList.Items.Refresh();
}
private void OnSearchBoxTextChanged(object sender, TextChangedEventArgs e)
{
if (m_editText.Text?.Length > 0)
{
m_resultsClearButton.Visibility = Visibility.Visible;
m_editText.Foreground = Colour.black;
m_editingText = true;
}
else if(!m_hasResults)
{
m_resultsClearButton.Visibility = Visibility.Hidden;
m_editText.Foreground = Colour.darkgrey;
}
ShowCloseButtonView(m_editText.Text.Length == 0);
m_hasTagSearch = false;
}
private void OnMenuScrollWheel(object sender, MouseWheelEventArgs e)
{
m_menuOptionsView.ScrollToVerticalOffset(m_menuOptionsView.VerticalOffset - e.Delta);
e.Handled = true;
}
private void OnResultsMenuScrollWheel(object sender, MouseWheelEventArgs e)
{
m_resultsListScrollViewer.ScrollToVerticalOffset(m_resultsListScrollViewer.VerticalOffset - e.Delta);
e.Handled = true;
}
private void OnMenuListItemSelected(object sender, MouseEventArgs e)
{
if (m_searchInFlight || IsAnimating() || m_adapter.IsAnimating())
{
(sender as ListBox).SelectedItem = null;
return;
}
var item = m_list.SelectedItem as MenuListItem;
if (item != null)
{
var sectionChildIndices = m_adapter.GetSectionAndChildIndicesFromSelection(m_list.SelectedIndex);
if (item.IsExpandable)
{
SearchMenuViewCLIMethods.OnSearchCleared(m_nativeCallerPointer);
}
MenuViewCLIMethods.SelectedItem(m_nativeCallerPointer, sectionChildIndices.Item1, sectionChildIndices.Item2);
}
}
private void OnResultsListItemsSelected(object sender, MouseEventArgs e)
{
if (m_resultsList.SelectedItems?.Count > 0)
{
SearchMenuViewCLIMethods.HandleSearchItemSelected(m_nativeCallerPointer, m_resultsList.SelectedIndex);
}
m_resultsList.Items.Refresh();
}
private void OnSearchBoxUnSelected(object sender, RoutedEventArgs e)
{
if(m_editText.Text.Replace(" ", null) == string.Empty)
{
m_editText.Text = string.Empty;
}
}
private void OnSearchBoxSelected(object sender, RoutedEventArgs e)
{
if (m_hasTagSearch)
{
m_editText.Text = string.Empty;
}
}
private void OnSearchResultsListTouchDown(object sender, TouchEventArgs touchEventArgs)
{
m_resultsList.CaptureTouch(touchEventArgs.TouchDevice);
if(m_searchResultsListCurrentTouchDevice == null)
{
CaptureSearchResultsListTouchDevice(touchEventArgs);
}
else
{
touchEventArgs.Handled = true;
}
}
private void OnSearchResultsListTouchUp(object sender, TouchEventArgs touchEventArgs)
{
m_resultsList.ReleaseTouchCapture(touchEventArgs.TouchDevice);
if (m_searchResultsListCurrentTouchDevice != null && m_searchResultsListCurrentTouchDevice.Id == touchEventArgs.TouchDevice.Id)
{
ReleaseSearchResultsListCurrentTouchDevice();
}
}
private void OnSearchResultsListTouchLeave(object sender, TouchEventArgs touchEventArgs)
{
m_resultsList.ReleaseTouchCapture(touchEventArgs.TouchDevice);
if (m_searchResultsListCurrentTouchDevice != null && m_searchResultsListCurrentTouchDevice.Id == touchEventArgs.TouchDevice.Id)
{
ReleaseSearchResultsListCurrentTouchDevice();
}
}
private void OnSearchResultsListLostTouchCapture(object sender, TouchEventArgs touchEventArgs)
{
if (m_searchResultsListCurrentTouchDevice != null && m_searchResultsListCurrentTouchDevice.Id == touchEventArgs.TouchDevice.Id)
{
CaptureSearchResultsListTouchDevice(touchEventArgs);
}
}
private void ReleaseSearchResultsListCurrentTouchDevice()
{
if (m_searchResultsListCurrentTouchDevice != null)
{
TouchDevice currentTouchDevice = m_searchResultsListCurrentTouchDevice;
m_searchResultsListCurrentTouchDevice = null;
m_resultsListScrollViewer.ReleaseTouchCapture(currentTouchDevice);
if(m_resultsList.SelectedIndex < 0)
{
m_resultsList.Items.Refresh();
}
}
}
private void CaptureSearchResultsListTouchDevice(TouchEventArgs touchEventArgs)
{
if (m_resultsListScrollViewer.CaptureTouch(touchEventArgs.TouchDevice))
{
m_searchResultsListCurrentTouchDevice = touchEventArgs.TouchDevice;
}
}
private void ClearSearchResultsListBox()
{
m_resultListAdapter.CollapseAndClearAll();
m_resultsCountContainer.Visibility = Visibility.Hidden;
m_resultsClearButton.Visibility = Visibility.Hidden;
m_searchArrow.Visibility = Visibility.Hidden;
m_resultsSeparator.Visibility = Visibility.Collapsed;
}
private void OnResultsClear(object sender, RoutedEventArgs e)
{
ClearSearch();
}
private void ClearSearch()
{
m_hasResults = false;
m_hasTagSearch = false;
if (m_resultsList.Items?.Count > 0)
{
SearchMenuViewCLIMethods.OnSearchCleared(m_nativeCallerPointer);
}
else
{
m_editText.Text = string.Empty;
}
ClearSearchResultsListBox();
//m_editText.Text = m_defaultEditText;
m_editText.Text = String.Empty;
m_editText.Foreground = Colour.darkgrey;
}
private void OnIconClick(object sender, RoutedEventArgs e)
{
MenuViewCLIMethods.ViewClicked(m_nativeCallerPointer);
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
Encoding enc = Encoding.GetEncoding("Windows-1252");
byte[] bytes = Encoding.UTF8.GetBytes(m_editText.Text);
string queryText = enc.GetString(bytes);
if (queryText.Length > 0)
{
SearchMenuViewCLIMethods.PerformedSearchQuery(m_nativeCallerPointer, queryText);
m_resultsSpinner.Visibility = Visibility.Visible;
m_resultsClearButton.Visibility = Visibility.Hidden;
m_searchInFlight = true;
}
}
}
public void SetSearchSection(string tag, string[] searchResults)
{
var groups = new List<string>(searchResults.Length);
var groupsExpandable = new List<bool>(searchResults.Length);
var groupToChildren = new Dictionary<string, List<string>>();
var itemsSource = new List<SearchMenuListItem>();
foreach (var str in searchResults)
{
var jObject = JObject.Parse(str);
var item = new SearchMenuListItem();
item.Name = jObject["name"] != null ? jObject["name"].Value<string>() : string.Empty;
item.Details = jObject["details"] != null ? jObject["details"].Value<string>() : string.Empty;
JToken iconStringToken;
var iconTagName = jObject.TryGetValue("icon", out iconStringToken) ? iconStringToken.Value<string>() : "";
item.Icon = IconProvider.GetIconForTag(iconTagName, m_isInKioskMode);
itemsSource.Add(item);
groups.Add(str);
groupsExpandable.Add(false);
if (!groupToChildren.ContainsKey(str))
{
groupToChildren.Add(str, new List<string>());
}
}
m_resultListAdapter.SetData(itemsSource, groups, groupsExpandable, groupToChildren);
m_resultsSpinner.Visibility = Visibility.Hidden;
m_resultsClearButton.Visibility = Visibility.Visible;
m_searchArrow.Visibility = Visibility.Visible;
m_resultsSeparator.Visibility = Visibility.Visible;
m_searchInFlight = false;
}
public override void AnimateToClosedOnScreen()
{
if (m_openState != MENU_CLOSED && m_openState != MENU_CLOSING)
{
if(m_isOffScreen)
{
m_searchBox.Visibility = Visibility.Hidden;
if (m_searchArrow.Visibility == Visibility.Visible)
{
m_searchArrowClosed.Begin(m_searchArrow);
}
}
else
{
m_searchBox.Visibility = Visibility.Visible;
m_searchInputClose.Begin(m_searchBox);
m_searchInputTextClose.Begin(m_editText);
m_searchArrowClosed.Begin(m_searchArrow);
}
base.AnimateToClosedOnScreen();
m_mainWindow.EnableInput();
}
ShowCloseButtonView(false);
}
public override void AnimateToOpenOnScreen()
{
if (m_openState != MENU_OPEN && m_openState != MENU_OPENING)
{
m_searchBox.Visibility = Visibility.Visible;
m_searchInputOpen.Begin(m_searchBox);
m_searchInputTextOpen.Begin(m_editText);
m_searchArrowOpen.Begin(m_searchArrow);
base.AnimateToOpenOnScreen();
m_mainWindow.EnableInput();
}
ShowCloseButtonView(m_editText.Text.Length == 0);
}
public void SetSearchInProgress()
{
Dispatcher.Invoke(() =>
{
m_resultsSpinner.Visibility = Visibility.Visible;
m_resultsClearButton.Visibility = Visibility.Hidden;
});
m_editingText = false;
}
public void SetSearchEnded()
{
Dispatcher.Invoke(() =>
{
m_resultsSpinner.Visibility = Visibility.Hidden;
m_resultsClearButton.Visibility = Visibility.Visible;
});
}
public void SetEditText(string text, bool isTag)
{
if(!m_editText.IsFocused)
{
byte[] bytes = Encoding.Default.GetBytes(text);
string encodedText = Encoding.UTF8.GetString(bytes);
m_editText.Text = encodedText;
}
m_hasTagSearch = isTag;
}
public string GetEditText()
{
return m_editText.Text;
}
public void SetSearchResultCount(int count)
{
m_resultsCount.Text = count.ToString();
m_resultsCountContainer.Visibility = Visibility.Visible;
m_searchResultsFade.Visibility = Visibility.Visible;
m_searchResultsScrollButton.Visibility = Visibility.Visible;
m_resultsListScrollViewer.ScrollToTop();
m_searchInFlight = false;
m_hasResults = true;
if (count == 0)
{
m_resultListAdapter.CollapseAndClearAll();
m_searchArrow.Visibility = Visibility.Hidden;
m_resultsSeparator.Visibility = Visibility.Collapsed;
return;
}
}
public void HideSearchResultCount()
{
m_searchResultsButtonAndFadeContainer.Visibility = Visibility.Collapsed;
m_searchResultsFade.Visibility = Visibility.Hidden;
m_searchResultsScrollButton.Visibility = Visibility.Hidden;
m_resultsCountContainer.Visibility = Visibility.Hidden;
m_resultsSpinner.Visibility = Visibility.Hidden;
ClearSearchResultsListBox();
m_searchInFlight = false;
m_hasResults = false;
}
protected override void RefreshListData(List<string> groups, List<bool> groupsExpandable, Dictionary<string, List<string>> groupToChildrenMap)
{
m_adapter.SetData(m_list.ItemsSource, groups, groupsExpandable, groupToChildrenMap);
m_resultsList.MaxHeight = CalcResultOptionsViewMaxHeight();
}
private void ShowCloseButtonView(bool shouldShowCloseView)
{
if(shouldShowCloseView)
{
SearchMenuIconOffImageSource = m_closeIconOffImageSource;
SearchMenuIconOnImageSource = m_closeIconOnImageSource;
}
else
{
SearchMenuIconOffImageSource = m_searchIconOffImageSource;
SearchMenuIconOnImageSource = m_searchIconOnImageSource;
}
}
public bool HasTagSearch()
{
return m_hasTagSearch;
}
}
}
| |
using System;
using Xunit;
using Shouldly;
using System.Linq;
namespace AutoMapper.UnitTests.ValueTypes
{
public class When_value_types_are_the_source_of_map_cycles : AutoMapperSpecBase
{
public struct Source
{
public InnerSource Value { get; set; }
}
public class InnerSource
{
public Source Parent { get; set; }
}
public struct Destination
{
public InnerDestination Value { get; set; }
}
public class InnerDestination
{
public Destination Parent { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg=>
{
cfg.CreateMap<Source, Destination>().MaxDepth(2);
cfg.CreateMap<InnerSource, InnerDestination>();
});
[Fact]
public void Should_work()
{
var innerSource = new InnerSource();
var source = new Source { Value = innerSource };
innerSource.Parent = source;
Mapper.Map<Destination>(source);
}
}
public class When_value_types_are_the_source_of_map_cycles_with_PreserveReferences : AutoMapperSpecBase
{
public struct Source
{
public InnerSource Value { get; set; }
}
public class InnerSource
{
public Source Parent { get; set; }
public InnerSource Inner { get; set; }
}
public struct Destination
{
public InnerDestination Value { get; set; }
}
public class InnerDestination
{
public Destination Parent { get; set; }
public InnerDestination Inner { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>().MaxDepth(2);
cfg.CreateMap<InnerSource, InnerDestination>();
});
[Fact]
public void Should_work()
{
var innerSource = new InnerSource();
var source = new Source { Value = innerSource };
innerSource.Parent = source;
innerSource.Inner = innerSource;
var destinationValue = Mapper.Map<Destination>(source).Value;
destinationValue.Inner.ShouldBe(destinationValue);
FindTypeMapFor<InnerSource, InnerDestination>().MemberMaps.Single(m => m.DestinationName == nameof(InnerDestination.Inner)).Inline.ShouldBeFalse();
}
}
public class When_destination_type_is_a_value_type : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int Value1 { get; set; }
public string Value2 { get; set; }
}
public struct Destination
{
public int Value1 { get; set; }
public string Value2;
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source {Value1 = 4, Value2 = "hello"});
}
[Fact]
public void Should_map_property_value()
{
_destination.Value1.ShouldBe(4);
}
[Fact]
public void Should_map_field_value()
{
_destination.Value2.ShouldBe("hello");
}
}
public class When_source_struct_config_has_custom_mappings : AutoMapperSpecBase
{
public struct matrixDigiInStruct1
{
public ushort CNCinfo;
public ushort Reg1;
public ushort Reg2;
}
public class DigiIn1
{
public ushort CncInfo { get; set; }
public ushort Reg1 { get; set; }
public ushort Reg2 { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(
cfg => cfg.CreateMap<matrixDigiInStruct1, DigiIn1>()
.ForMember(d => d.CncInfo, x => x.MapFrom(s => s.CNCinfo)));
[Fact]
public void Should_map_correctly()
{
var source = new matrixDigiInStruct1
{
CNCinfo = 5,
Reg1 = 6,
Reg2 = 7
};
var dest = Mapper.Map<matrixDigiInStruct1, DigiIn1>(source);
dest.CncInfo.ShouldBe(source.CNCinfo);
dest.Reg1.ShouldBe(source.Reg1);
dest.Reg2.ShouldBe(source.Reg2);
}
}
public class When_destination_type_is_a_nullable_value_type : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public string Value1 { get; set; }
public string Value2 { get; set; }
}
public struct Destination
{
public int Value1 { get; set; }
public int? Value2 { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<string, int>().ConvertUsing((string s) => Convert.ToInt32(s));
cfg.CreateMap<string, int?>().ConvertUsing((string s) => (int?) Convert.ToInt32(s));
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source {Value1 = "10", Value2 = "20"});
}
[Fact]
public void Should_use_map_registered_for_underlying_type()
{
_destination.Value2.ShouldBe(20);
}
[Fact]
public void Should_still_map_value_type()
{
_destination.Value1.ShouldBe(10);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Auth0.Core.Exceptions;
using Newtonsoft.Json;
// ReSharper disable once CheckNamespace
namespace Auth0.Core.Http
{
/// <summary>
/// The communication layer between the various API clients and the actual API backend.
/// </summary>
public class ApiConnection : IApiConnection
{
private readonly string _baseUrl;
private readonly DiagnosticsHeader _diagnostics;
private readonly HttpClient _httpClient;
private readonly string _token;
/// <summary>
/// Contains information about the last API call made by the connection.
/// </summary>
public ApiInfo ApiInfo { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="ApiConnection" /> class.
/// </summary>
/// <param name="token">The API token.</param>
/// <param name="baseUrl">The base URL of the requests.</param>
/// <param name="diagnostics">The diagnostics. header</param>
/// <param name="handler"></param>
public ApiConnection(string token, string baseUrl, DiagnosticsHeader diagnostics,
HttpMessageHandler handler = null)
{
_token = token;
_diagnostics = diagnostics;
_baseUrl = baseUrl;
_httpClient = new HttpClient(handler ?? new HttpClientHandler());
}
public ApiConnection(string token, string baseUrl, DiagnosticsHeader diagnostics,
HttpClient httpClient)
{
_token = token;
_diagnostics = diagnostics;
_baseUrl = baseUrl;
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
}
private void ApplyHeaders(HttpRequestMessage message, IDictionary<string, object> headers)
{
// Add the diagnostics header, unless user explicitly opted out of it
if (!ReferenceEquals(_diagnostics, DiagnosticsHeader.Suppress))
message.Headers.Add("Auth0-Client", _diagnostics.ToString());
// Set the authorization header
if (headers == null || !headers.ContainsKey("Authorization"))
// Auth header can be overridden by passing custom value in headers dictionary
if (!string.IsNullOrEmpty(_token))
message.Headers.Add("Authorization", $"Bearer {_token}");
// Add the user agent
message.Headers.Add("User-Agent", ".NET/PCL");
// Apply other headers
if (headers != null)
foreach (var pair in headers)
if (pair.Key != null && pair.Value != null)
message.Headers.Add(pair.Key, pair.Value.ToString());
}
/// <summary>
/// Builds the content of the message. This will build the appropriate <see cref="HttpContent" /> for the request based
/// on the type of the parameters passed in.
/// </summary>
/// <param name="body">The body.</param>
/// <param name="parameters">The parameters.</param>
/// <param name="fileParameters">The file parameters.</param>
/// <returns>HttpContent.</returns>
private HttpContent BuildMessageContent(object body, IDictionary<string, object> parameters,
IList<FileUploadParameter> fileParameters)
{
// If user sent in file parameters, then we handle this as a multipart content
if (fileParameters != null && fileParameters.Count > 0)
{
var multipartContent = new MultipartFormDataContent();
// Add the file parameters
foreach (var fileParameter in fileParameters)
if (string.IsNullOrEmpty(fileParameter.Filename))
multipartContent.Add(new StreamContent(fileParameter.FileStream), fileParameter.Key);
else
multipartContent.Add(new StreamContent(fileParameter.FileStream), fileParameter.Key,
fileParameter.Filename);
// Add the other parameters
foreach (var parameter in parameters)
multipartContent.Add(new StringContent(Uri.EscapeDataString(parameter.Value?.ToString() ?? "")),
parameter.Key);
return multipartContent;
}
if (parameters != null)
return
new FormUrlEncodedContent(
parameters.Select(
kvp => new KeyValuePair<string, string>(kvp.Key, kvp.Value?.ToString() ?? string.Empty)));
return new StringContent(JsonConvert.SerializeObject(body, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}), Encoding.UTF8, "application/json");
}
/// <summary>
/// Builds up the URL for the request by substituting values for URL segments and adding query string parameters.
/// </summary>
/// <param name="resource">The resource.</param>
/// <param name="urlSegments">The URL segments.</param>
/// <param name="queryStrings">The query strings.</param>
/// <returns>Uri.</returns>
private Uri BuildRequestUri(string resource, IDictionary<string, string> urlSegments,
IDictionary<string, string> queryStrings)
{
return Utils.BuildUri(_baseUrl, resource, urlSegments, queryStrings);
}
/// <summary>
/// Performs an HTTP DELETE.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="resource">The resource.</param>
/// <param name="urlSegments">The URL segments.</param>
/// <param name="queryStrings"></param>
/// <returns>Task<T>.</returns>
public async Task<T> DeleteAsync<T>(string resource, IDictionary<string, string> urlSegments,
IDictionary<string, string> queryStrings) where T : class
{
return await RunAsync<T>(resource,
HttpMethod.Delete,
null,
urlSegments,
queryStrings,
null,
null,
null,
null).ConfigureAwait(false);
}
private void ExtractApiInfo(HttpResponseMessage response)
{
ApiInfo = ApiInfoParser.Parse(response.Headers);
}
/// <summary>
/// Performs an HTTP GET.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="resource">The resource.</param>
/// <param name="urlSegments">The URL segments.</param>
/// <param name="queryStrings">The query strings.</param>
/// <param name="headers">The headers.</param>
/// <param name="converters">The list of <see cref="JsonConverter" /> to use during deserialization.</param>
/// <returns>Task<T>.</returns>
public async Task<T> GetAsync<T>(string resource, IDictionary<string, string> urlSegments,
IDictionary<string, string> queryStrings, IDictionary<string, object> headers,
params JsonConverter[] converters) where T : class
{
return await RunAsync<T>(resource,
HttpMethod.Get,
null,
urlSegments,
queryStrings,
null,
headers,
null,
converters).ConfigureAwait(false);
}
/// <summary>
/// Handles errors returned from the API. It will check the response code, deserialize any relevant JSON error payload
/// and throw an appropriate exception.
/// </summary>
/// <param name="response">The <see cref="HttpResponseMessage" /> returned from the API.</param>
/// <returns>A <see cref="Task" />.</returns>
/// <exception cref="ApiException"></exception>
private async Task HandleErrors(HttpResponseMessage response)
{
if (!response.IsSuccessStatusCode)
{
ApiError apiError = null;
// Grab the content
if (response.Content != null)
{
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if (!string.IsNullOrEmpty(responseContent))
try
{
apiError = JsonConvert.DeserializeObject<ApiError>(responseContent);
if (apiError.StatusCode == 0)
apiError.StatusCode = (int) response.StatusCode;
}
catch (Exception)
{
apiError = new ApiError
{
Error = responseContent,
Message = responseContent,
StatusCode = (int) response.StatusCode
};
}
}
throw new ApiException(response.StatusCode, apiError);
}
}
/// <summary>
/// Performs an HTTP PATCH.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="resource">The resource.</param>
/// <param name="body">The body.</param>
/// <param name="urlSegments">The URL segments.</param>
/// <returns>Task<T>.</returns>
public async Task<T> PatchAsync<T>(string resource, object body, Dictionary<string, string> urlSegments)
where T : class
{
return await RunAsync<T>(resource,
new HttpMethod("PATCH"),
body,
urlSegments,
null,
null,
null,
null,
null).ConfigureAwait(false);
}
/// <summary>
/// Performs an HTTP POST.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="resource">The resource.</param>
/// <param name="body">The body.</param>
/// <param name="parameters">The parameters.</param>
/// <param name="fileParameters">The file parameters.</param>
/// <param name="urlSegments">The URL segments.</param>
/// <param name="headers">The headers.</param>
/// <param name="queryStrings">The query strings.</param>
/// <returns>Task<T>.</returns>
public async Task<T> PostAsync<T>(string resource, object body, IDictionary<string, object> parameters,
IList<FileUploadParameter> fileParameters, IDictionary<string, string> urlSegments,
IDictionary<string, object> headers, IDictionary<string, string> queryStrings) where T : class
{
return await RunAsync<T>(resource,
HttpMethod.Post,
body,
urlSegments,
queryStrings,
parameters,
headers,
fileParameters,
null).ConfigureAwait(false);
}
/// <summary>
/// Performs an HTTP PUT.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="resource">The resource.</param>
/// <param name="body">The body.</param>
/// <param name="parameters">The parameters.</param>
/// <param name="fileParameters">The file parameters.</param>
/// <param name="urlSegments">The URL segments.</param>
/// <param name="headers">The headers.</param>
/// <param name="queryStrings">The query strings.</param>
/// <returns>Task<T>.</returns>
public async Task<T> PutAsync<T>(string resource, object body, IDictionary<string, object> parameters,
IList<FileUploadParameter> fileParameters, IDictionary<string, string> urlSegments,
IDictionary<string, object> headers, IDictionary<string, string> queryStrings) where T : class
{
return await RunAsync<T>(resource,
HttpMethod.Put,
body,
urlSegments,
queryStrings,
parameters,
headers,
fileParameters,
null).ConfigureAwait(false);
}
/// <summary>
/// Executes the request. All requests will pass through this method as it will apply the headers, do the JSON
/// formatting, check for errors on return, etc.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="resource">The resource.</param>
/// <param name="httpMethod">The HTTP method.</param>
/// <param name="body">The body.</param>
/// <param name="urlSegments">The URL segments.</param>
/// <param name="queryStrings">The query strings.</param>
/// <param name="parameters">The parameters.</param>
/// <param name="headers">The headers.</param>
/// <param name="fileParameters">The file parameters.</param>
/// <param name="converters">The list of <see cref="JsonConverter" /> to use during deserialization.</param>
/// <returns>Task<T>.</returns>
private async Task<T> RunAsync<T>(string resource, HttpMethod httpMethod, object body,
IDictionary<string, string> urlSegments, IDictionary<string, string> queryStrings,
IDictionary<string, object> parameters, IDictionary<string, object> headers,
IList<FileUploadParameter> fileParameters, params JsonConverter[] converters) where T : class
{
// Build the request URL
var requestMessage = new HttpRequestMessage(httpMethod, BuildRequestUri(resource, urlSegments, queryStrings));
// Get the message content
if (httpMethod != HttpMethod.Get)
requestMessage.Content = BuildMessageContent(body, parameters, fileParameters);
// Apply the headers
ApplyHeaders(requestMessage, headers);
// Send the request
var response = await _httpClient.SendAsync(requestMessage).ConfigureAwait(false);
// Extract the relevate API headers
ExtractApiInfo(response);
// Handle API errors
await HandleErrors(response).ConfigureAwait(false);
// Deserialize the content
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if (typeof(T) == typeof(string)) // Let string content pass throug
return (T) (object) content;
return JsonConvert.DeserializeObject<T>(content, converters);
}
}
}
| |
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 SinglePageApplication.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System.Collections.Generic;
using CodeContractNullability.Test.TestDataBuilders;
using Xunit;
namespace CodeContractNullability.Test.Specs
{
/// <summary>
/// Tests concerning the interpretation of full metadata name notation of members, as they occur in external annotation files.
/// </summary>
public sealed class ExternalAnnotationMemberNamingSpecs : NullabilityTest
{
[Fact]
public void When_property_in_generic_class_is_externally_annotated_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(IEnumerable<>).Namespace)
.InGlobalScope(@"
namespace SampleNamespace
{
public class SampleClass<T>
{
public virtual IEnumerable<T> TheEnumerable { get; set; }
}
}
")
.ExternallyAnnotated(new ExternalAnnotationsBuilder()
.IncludingMember(new ExternalAnnotationFragmentBuilder()
.Named("P:SampleNamespace.SampleClass`1.TheEnumerable")
.CanBeNull()))
.Build();
// Act and assert
VerifyNullabilityDiagnostic(source);
}
[Fact]
public void When_variable_length_parameter_in_method_is_externally_annotated_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
namespace TestSystem
{
public class StringFormatter
{
public static string Format(IFormatProvider provider, string format, params object[] args)
{
throw new NotImplementedException();
}
}
}
")
.ExternallyAnnotated(new ExternalAnnotationsBuilder()
.IncludingMember(new ExternalAnnotationFragmentBuilder()
.Named("M:TestSystem.StringFormatter.Format(System.IFormatProvider,System.String,System.Object[])")
.NotNull()
.WithParameter(new ExternalAnnotationParameterBuilder()
.Named("provider")
.CanBeNull())
.WithParameter(new ExternalAnnotationParameterBuilder()
.Named("format")
.CanBeNull())
.WithParameter(new ExternalAnnotationParameterBuilder()
.Named("args")
.CanBeNull())))
.Build();
// Act and assert
VerifyNullabilityDiagnostic(source);
}
[Fact]
public void When_generic_parameters_in_method_of_generic_class_are_externally_annotated_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
namespace SystemCollections
{
public class Dictionary<TKey, TValue>
{
public void Add(TKey key, TValue value) { throw new NotImplementedException(); }
}
}
")
.ExternallyAnnotated(new ExternalAnnotationsBuilder()
.IncludingMember(new ExternalAnnotationFragmentBuilder()
.Named("M:SystemCollections.Dictionary`2.Add(`0,`1)")
.WithParameter(new ExternalAnnotationParameterBuilder()
.Named("key")
.CanBeNull())
.WithParameter(new ExternalAnnotationParameterBuilder()
.Named("value")
.CanBeNull())))
.Build();
// Act and assert
VerifyNullabilityDiagnostic(source);
}
[Fact]
public void When_nested_generic_parameters_in_method_of_generic_interface_is_externally_annotated_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(IEnumerable<>).Namespace)
.InGlobalScope(@"
namespace SystemCollections
{
public interface IDictionary<TKey, TValue>
{
void SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items);
}
}
")
.ExternallyAnnotated(new ExternalAnnotationsBuilder()
.IncludingMember(new ExternalAnnotationFragmentBuilder()
.Named(
"M:SystemCollections.IDictionary`2.SetItems(System.Collections.Generic.IEnumerable{System.Collections.Generic.KeyValuePair{`0,`1}})")
.WithParameter(new ExternalAnnotationParameterBuilder()
.Named("items")
.CanBeNull())))
.Build();
// Act and assert
VerifyNullabilityDiagnostic(source);
}
[Fact]
public void When_generic_parameters_in_generic_method_of_non_generic_class_are_externally_annotated_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(IEnumerable<>).Namespace)
.InGlobalScope(@"
namespace SystemCollections
{
public static class Enumerable
{
public static IEnumerable<TResult> SelectMany<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector)
{
throw new NotImplementedException();
}
}
}
")
.ExternallyAnnotated(new ExternalAnnotationsBuilder()
.IncludingMember(new ExternalAnnotationFragmentBuilder()
.Named(
"M:SystemCollections.Enumerable.SelectMany``2(System.Collections.Generic.IEnumerable{``0},System.Func{``0,System.Collections.Generic.IEnumerable{``1}})")
.NotNull()
.WithParameter(new ExternalAnnotationParameterBuilder()
.Named("source")
.CanBeNull())
.WithParameter(new ExternalAnnotationParameterBuilder()
.Named("selector")
.CanBeNull())))
.Build();
// Act and assert
VerifyNullabilityDiagnostic(source);
}
[Fact]
public void When_field_in_nested_class_is_externally_annotated_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
namespace TestSystem
{
public class Outer
{
private class Inner
{
public int? Value;
}
}
}
")
.ExternallyAnnotated(new ExternalAnnotationsBuilder()
.IncludingMember(new ExternalAnnotationFragmentBuilder()
.Named("F:TestSystem.Outer.Inner.Value")
.CanBeNull()))
.Build();
// Act and assert
VerifyNullabilityDiagnostic(source);
}
[Fact]
public void
When_generic_parameters_in_generic_method_in_generic_nested_classes_are_externally_annotated_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(KeyValuePair<,>).Namespace)
.InGlobalScope(@"
namespace TestSystem
{
public class OuterClass<TOuter1, TOuter2>
{
public class InnerClass<TInner>
{
public TMethod1 TestMethod<TMethod1, TMethod2>(TOuter2 testOuter2,
TInner testInner, TMethod2 testMethod2, KeyValuePair<TMethod1, TOuter1> pair)
{
throw new NotImplementedException();
}
}
}
}
")
.ExternallyAnnotated(new ExternalAnnotationsBuilder()
.IncludingMember(new ExternalAnnotationFragmentBuilder()
.Named("M:TestSystem.OuterClass`2.InnerClass`1.TestMethod``2(`1,`2,``1,System.Collections.Generic.KeyValuePair{``0,`0})")
.CanBeNull()
.WithParameter(new ExternalAnnotationParameterBuilder()
.Named("testOuter2")
.CanBeNull())
.WithParameter(new ExternalAnnotationParameterBuilder()
.Named("testInner")
.CanBeNull())
.WithParameter(new ExternalAnnotationParameterBuilder()
.Named("testMethod2")
.CanBeNull())
.WithParameter(new ExternalAnnotationParameterBuilder()
.Named("pair")
.CanBeNull())))
.Build();
// Act and assert
VerifyNullabilityDiagnostic(source);
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.MatLab.MatLab
File: MatLabConnector.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.MatLab
{
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.BusinessEntities;
/// <summary>
/// The interface <see cref="IConnector"/> implementation which provides ability to use from MatLab scripts.
/// </summary>
public class MatLabConnector : Disposable
{
private readonly bool _ownTrader;
/// <summary>
/// Initializes a new instance of the <see cref="MatLabConnector"/>.
/// </summary>
/// <param name="realConnector">The connection for market-data and transactions.</param>
public MatLabConnector(IConnector realConnector)
: this(realConnector, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MatLabConnector"/>.
/// </summary>
/// <param name="realConnector">The connection for market-data and transactions.</param>
/// <param name="ownTrader">Track the connection <paramref name="realConnector" /> lifetime.</param>
public MatLabConnector(IConnector realConnector, bool ownTrader)
{
if (realConnector == null)
throw new ArgumentNullException(nameof(realConnector));
RealConnector = realConnector;
RealConnector.Connected += RealTraderOnConnected;
RealConnector.ConnectionError += RealTraderOnConnectionError;
RealConnector.Disconnected += RealTraderOnDisconnected;
RealConnector.Error += RealTraderOnError;
RealConnector.MarketTimeChanged += RealTraderOnMarketTimeChanged;
RealConnector.NewSecurities += RealTraderOnNewSecurities;
RealConnector.SecuritiesChanged += RealTraderOnSecuritiesChanged;
RealConnector.NewPortfolios += RealTraderOnNewPortfolios;
RealConnector.PortfoliosChanged += RealTraderOnPortfoliosChanged;
RealConnector.NewPositions += RealTraderOnNewPositions;
RealConnector.PositionsChanged += RealTraderOnPositionsChanged;
RealConnector.NewTrades += RealTraderOnNewTrades;
RealConnector.NewMyTrades += RealTraderOnNewMyTrades;
RealConnector.NewMarketDepths += RealTraderOnNewMarketDepths;
RealConnector.MarketDepthsChanged += RealTraderOnMarketDepthsChanged;
RealConnector.NewOrders += RealTraderOnNewOrders;
RealConnector.OrdersChanged += RealTraderOnOrdersChanged;
RealConnector.OrdersRegisterFailed += RealTraderOnOrdersRegisterFailed;
RealConnector.OrdersCancelFailed += RealTraderOnOrdersCancelFailed;
RealConnector.NewStopOrders += RealTraderOnNewStopOrders;
RealConnector.StopOrdersChanged += RealTraderOnStopOrdersChanged;
RealConnector.StopOrdersRegisterFailed += RealTraderOnStopOrdersRegisterFailed;
RealConnector.StopOrdersCancelFailed += RealTraderOnStopOrdersCancelFailed;
RealConnector.NewOrderLogItems += RealTraderOnNewOrderLogItems;
_ownTrader = ownTrader;
}
/// <summary>
/// The connection for market-data and transactions.
/// </summary>
public IConnector RealConnector { get; }
/// <summary>
/// Connected.
/// </summary>
public event EventHandler Connected;
/// <summary>
/// Connection error (for example, the connection was aborted by server).
/// </summary>
public event EventHandler<ErrorEventArgs> ConnectionError;
/// <summary>
/// Disconnected.
/// </summary>
public event EventHandler Disconnected;
/// <summary>
/// Dats process error.
/// </summary>
public event EventHandler<ErrorEventArgs> Error;
/// <summary>
/// Server time changed <see cref="IConnector.ExchangeBoards"/>. It passed the time difference since the last call of the event. The first time the event passes the value <see cref="TimeSpan.Zero"/>.
/// </summary>
public event EventHandler MarketTimeChanged;
/// <summary>
/// Securities received.
/// </summary>
public event EventHandler<SecuritiesEventArgs> NewSecurities;
/// <summary>
/// Securities changed.
/// </summary>
public event EventHandler<SecuritiesEventArgs> SecuritiesChanged;
/// <summary>
/// Portfolios received.
/// </summary>
public event EventHandler<PortfoliosEventArgs> NewPortfolios;
/// <summary>
/// Portfolios changed.
/// </summary>
public event EventHandler<PortfoliosEventArgs> PortfoliosChanged;
/// <summary>
/// Positions received.
/// </summary>
public event EventHandler<PositionsEventArgs> NewPositions;
/// <summary>
/// Positions changed.
/// </summary>
public event EventHandler<PositionsEventArgs> PositionsChanged;
/// <summary>
/// Tick trades received.
/// </summary>
public event EventHandler<TradesEventArgs> NewTrades;
/// <summary>
/// Own trades received.
/// </summary>
public event EventHandler<MyTradesEventArgs> NewMyTrades;
/// <summary>
/// Orders received.
/// </summary>
public event EventHandler<OrdersEventArgs> NewOrders;
/// <summary>
/// Orders changed (cancelled, matched).
/// </summary>
public event EventHandler<OrdersEventArgs> OrdersChanged;
/// <summary>
/// Order registration errors event.
/// </summary>
public event EventHandler<OrderFailsEventArgs> OrdersRegisterFailed;
/// <summary>
/// Order cancellation errors event.
/// </summary>
public event EventHandler<OrderFailsEventArgs> OrdersCancelFailed;
/// <summary>
/// Stop-orders received.
/// </summary>
public event EventHandler<OrdersEventArgs> NewStopOrders;
/// <summary>
/// Stop orders state change event .
/// </summary>
public event EventHandler<OrdersEventArgs> StopOrdersChanged;
/// <summary>
/// Stop-order registration errors event.
/// </summary>
public event EventHandler<OrderFailsEventArgs> StopOrdersRegisterFailed;
/// <summary>
/// Stop-order cancellation errors event.
/// </summary>
public event EventHandler<OrderFailsEventArgs> StopOrdersCancelFailed;
/// <summary>
/// Order books received.
/// </summary>
public event EventHandler<MarketDepthsEventArgs> NewMarketDepths;
/// <summary>
/// Order books changed.
/// </summary>
public event EventHandler<MarketDepthsEventArgs> MarketDepthsChanged;
/// <summary>
/// Order log received.
/// </summary>
public event EventHandler<OrderLogItemsEventArg> NewOrderLogItems;
private void RealTraderOnNewMyTrades(IEnumerable<MyTrade> trades)
{
NewMyTrades.SafeInvoke(this, new MyTradesEventArgs(trades));
}
private void RealTraderOnError(Exception exception)
{
Error.SafeInvoke(this, new ErrorEventArgs(exception));
}
private void RealTraderOnStopOrdersCancelFailed(IEnumerable<OrderFail> fails)
{
StopOrdersCancelFailed.SafeInvoke(this, new OrderFailsEventArgs(fails));
}
private void RealTraderOnStopOrdersRegisterFailed(IEnumerable<OrderFail> fails)
{
StopOrdersRegisterFailed.SafeInvoke(this, new OrderFailsEventArgs(fails));
}
private void RealTraderOnStopOrdersChanged(IEnumerable<Order> orders)
{
StopOrdersChanged.SafeInvoke(this, new OrdersEventArgs(orders));
}
private void RealTraderOnNewStopOrders(IEnumerable<Order> orders)
{
NewStopOrders.SafeInvoke(this, new OrdersEventArgs(orders));
}
private void RealTraderOnOrdersCancelFailed(IEnumerable<OrderFail> fails)
{
OrdersCancelFailed.SafeInvoke(this, new OrderFailsEventArgs(fails));
}
private void RealTraderOnOrdersRegisterFailed(IEnumerable<OrderFail> fails)
{
OrdersRegisterFailed.SafeInvoke(this, new OrderFailsEventArgs(fails));
}
private void RealTraderOnOrdersChanged(IEnumerable<Order> orders)
{
OrdersChanged.SafeInvoke(this, new OrdersEventArgs(orders));
}
private void RealTraderOnNewOrders(IEnumerable<Order> orders)
{
NewOrders.SafeInvoke(this, new OrdersEventArgs(orders));
}
private void RealTraderOnNewMarketDepths(IEnumerable<MarketDepth> depths)
{
NewMarketDepths.SafeInvoke(this, new MarketDepthsEventArgs(depths));
}
private void RealTraderOnMarketDepthsChanged(IEnumerable<MarketDepth> depths)
{
MarketDepthsChanged.SafeInvoke(this, new MarketDepthsEventArgs(depths));
}
private void RealTraderOnNewTrades(IEnumerable<Trade> trades)
{
NewTrades.SafeInvoke(this, new TradesEventArgs(trades));
}
private void RealTraderOnPositionsChanged(IEnumerable<Position> positions)
{
PositionsChanged.SafeInvoke(this, new PositionsEventArgs(positions));
}
private void RealTraderOnNewPositions(IEnumerable<Position> positions)
{
NewPositions.SafeInvoke(this, new PositionsEventArgs(positions));
}
private void RealTraderOnPortfoliosChanged(IEnumerable<Portfolio> portfolios)
{
PortfoliosChanged.SafeInvoke(this, new PortfoliosEventArgs(portfolios));
}
private void RealTraderOnNewPortfolios(IEnumerable<Portfolio> portfolios)
{
NewPortfolios.SafeInvoke(this, new PortfoliosEventArgs(portfolios));
}
private void RealTraderOnSecuritiesChanged(IEnumerable<Security> securities)
{
SecuritiesChanged.SafeInvoke(this, new SecuritiesEventArgs(securities));
}
private void RealTraderOnNewSecurities(IEnumerable<Security> securities)
{
NewSecurities.SafeInvoke(this, new SecuritiesEventArgs(securities));
}
private void RealTraderOnNewOrderLogItems(IEnumerable<OrderLogItem> items)
{
NewOrderLogItems.SafeInvoke(this, new OrderLogItemsEventArg(items));
}
private void RealTraderOnMarketTimeChanged(TimeSpan diff)
{
MarketTimeChanged.Cast().SafeInvoke(this);
}
private void RealTraderOnDisconnected()
{
Disconnected.Cast().SafeInvoke(this);
}
private void RealTraderOnConnectionError(Exception exception)
{
ConnectionError.SafeInvoke(this, new ErrorEventArgs(exception));
}
private void RealTraderOnConnected()
{
Connected.Cast().SafeInvoke(this);
}
/// <summary>
/// Release resources.
/// </summary>
protected override void DisposeManaged()
{
RealConnector.Connected -= RealTraderOnConnected;
RealConnector.ConnectionError -= RealTraderOnConnectionError;
RealConnector.Disconnected -= RealTraderOnDisconnected;
RealConnector.Error -= RealTraderOnError;
RealConnector.MarketTimeChanged -= RealTraderOnMarketTimeChanged;
RealConnector.NewSecurities -= RealTraderOnNewSecurities;
RealConnector.SecuritiesChanged -= RealTraderOnSecuritiesChanged;
RealConnector.NewPortfolios -= RealTraderOnNewPortfolios;
RealConnector.PortfoliosChanged -= RealTraderOnPortfoliosChanged;
RealConnector.NewPositions -= RealTraderOnNewPositions;
RealConnector.PositionsChanged -= RealTraderOnPositionsChanged;
RealConnector.NewTrades -= RealTraderOnNewTrades;
RealConnector.NewMyTrades -= RealTraderOnNewMyTrades;
RealConnector.MarketDepthsChanged -= RealTraderOnMarketDepthsChanged;
RealConnector.NewOrders -= RealTraderOnNewOrders;
RealConnector.OrdersChanged -= RealTraderOnOrdersChanged;
RealConnector.OrdersRegisterFailed -= RealTraderOnOrdersRegisterFailed;
RealConnector.OrdersCancelFailed -= RealTraderOnOrdersCancelFailed;
RealConnector.NewStopOrders -= RealTraderOnNewStopOrders;
RealConnector.StopOrdersChanged -= RealTraderOnStopOrdersChanged;
RealConnector.StopOrdersRegisterFailed -= RealTraderOnStopOrdersRegisterFailed;
RealConnector.StopOrdersCancelFailed -= RealTraderOnStopOrdersCancelFailed;
if (_ownTrader)
RealConnector.Dispose();
base.DisposeManaged();
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="SearchTermViewServiceClient"/> instances.</summary>
public sealed partial class SearchTermViewServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="SearchTermViewServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="SearchTermViewServiceSettings"/>.</returns>
public static SearchTermViewServiceSettings GetDefault() => new SearchTermViewServiceSettings();
/// <summary>
/// Constructs a new <see cref="SearchTermViewServiceSettings"/> object with default settings.
/// </summary>
public SearchTermViewServiceSettings()
{
}
private SearchTermViewServiceSettings(SearchTermViewServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetSearchTermViewSettings = existing.GetSearchTermViewSettings;
OnCopy(existing);
}
partial void OnCopy(SearchTermViewServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>SearchTermViewServiceClient.GetSearchTermView</c> and
/// <c>SearchTermViewServiceClient.GetSearchTermViewAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetSearchTermViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="SearchTermViewServiceSettings"/> object.</returns>
public SearchTermViewServiceSettings Clone() => new SearchTermViewServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="SearchTermViewServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class SearchTermViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<SearchTermViewServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public SearchTermViewServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public SearchTermViewServiceClientBuilder()
{
UseJwtAccessWithScopes = SearchTermViewServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref SearchTermViewServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<SearchTermViewServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override SearchTermViewServiceClient Build()
{
SearchTermViewServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<SearchTermViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<SearchTermViewServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private SearchTermViewServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return SearchTermViewServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<SearchTermViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return SearchTermViewServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => SearchTermViewServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => SearchTermViewServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => SearchTermViewServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>SearchTermViewService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage search term views.
/// </remarks>
public abstract partial class SearchTermViewServiceClient
{
/// <summary>
/// The default endpoint for the SearchTermViewService service, which is a host of "googleads.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default SearchTermViewService scopes.</summary>
/// <remarks>
/// The default SearchTermViewService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="SearchTermViewServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="SearchTermViewServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="SearchTermViewServiceClient"/>.</returns>
public static stt::Task<SearchTermViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new SearchTermViewServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="SearchTermViewServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="SearchTermViewServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="SearchTermViewServiceClient"/>.</returns>
public static SearchTermViewServiceClient Create() => new SearchTermViewServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="SearchTermViewServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="SearchTermViewServiceSettings"/>.</param>
/// <returns>The created <see cref="SearchTermViewServiceClient"/>.</returns>
internal static SearchTermViewServiceClient Create(grpccore::CallInvoker callInvoker, SearchTermViewServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
SearchTermViewService.SearchTermViewServiceClient grpcClient = new SearchTermViewService.SearchTermViewServiceClient(callInvoker);
return new SearchTermViewServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC SearchTermViewService client</summary>
public virtual SearchTermViewService.SearchTermViewServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the attributes of the requested search term view.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::SearchTermView GetSearchTermView(GetSearchTermViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the attributes of the requested search term view.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::SearchTermView> GetSearchTermViewAsync(GetSearchTermViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the attributes of the requested search term view.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::SearchTermView> GetSearchTermViewAsync(GetSearchTermViewRequest request, st::CancellationToken cancellationToken) =>
GetSearchTermViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the attributes of the requested search term view.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the search term view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::SearchTermView GetSearchTermView(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetSearchTermView(new GetSearchTermViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the attributes of the requested search term view.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the search term view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::SearchTermView> GetSearchTermViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetSearchTermViewAsync(new GetSearchTermViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the attributes of the requested search term view.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the search term view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::SearchTermView> GetSearchTermViewAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetSearchTermViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the attributes of the requested search term view.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the search term view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::SearchTermView GetSearchTermView(gagvr::SearchTermViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetSearchTermView(new GetSearchTermViewRequest
{
ResourceNameAsSearchTermViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the attributes of the requested search term view.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the search term view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::SearchTermView> GetSearchTermViewAsync(gagvr::SearchTermViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetSearchTermViewAsync(new GetSearchTermViewRequest
{
ResourceNameAsSearchTermViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the attributes of the requested search term view.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the search term view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::SearchTermView> GetSearchTermViewAsync(gagvr::SearchTermViewName resourceName, st::CancellationToken cancellationToken) =>
GetSearchTermViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>SearchTermViewService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage search term views.
/// </remarks>
public sealed partial class SearchTermViewServiceClientImpl : SearchTermViewServiceClient
{
private readonly gaxgrpc::ApiCall<GetSearchTermViewRequest, gagvr::SearchTermView> _callGetSearchTermView;
/// <summary>
/// Constructs a client wrapper for the SearchTermViewService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="SearchTermViewServiceSettings"/> used within this client.</param>
public SearchTermViewServiceClientImpl(SearchTermViewService.SearchTermViewServiceClient grpcClient, SearchTermViewServiceSettings settings)
{
GrpcClient = grpcClient;
SearchTermViewServiceSettings effectiveSettings = settings ?? SearchTermViewServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetSearchTermView = clientHelper.BuildApiCall<GetSearchTermViewRequest, gagvr::SearchTermView>(grpcClient.GetSearchTermViewAsync, grpcClient.GetSearchTermView, effectiveSettings.GetSearchTermViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetSearchTermView);
Modify_GetSearchTermViewApiCall(ref _callGetSearchTermView);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetSearchTermViewApiCall(ref gaxgrpc::ApiCall<GetSearchTermViewRequest, gagvr::SearchTermView> call);
partial void OnConstruction(SearchTermViewService.SearchTermViewServiceClient grpcClient, SearchTermViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC SearchTermViewService client</summary>
public override SearchTermViewService.SearchTermViewServiceClient GrpcClient { get; }
partial void Modify_GetSearchTermViewRequest(ref GetSearchTermViewRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the attributes of the requested search term view.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::SearchTermView GetSearchTermView(GetSearchTermViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetSearchTermViewRequest(ref request, ref callSettings);
return _callGetSearchTermView.Sync(request, callSettings);
}
/// <summary>
/// Returns the attributes of the requested search term view.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::SearchTermView> GetSearchTermViewAsync(GetSearchTermViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetSearchTermViewRequest(ref request, ref callSettings);
return _callGetSearchTermView.Async(request, callSettings);
}
}
}
| |
namespace More.ComponentModel
{
using FluentAssertions;
using Moq;
using Moq.Protected;
using System;
using Xunit;
public class UnitOfWorkTTest
{
[Fact]
public void register_new_should_mark_item_for_insert()
{
// arrange
var mock = new Mock<UnitOfWork<object>>() { CallBase = true };
var unitOfWork = mock.Object;
unitOfWork.MonitorEvents();
// act
unitOfWork.RegisterNew( new object() );
// assert
unitOfWork.HasPendingChanges.Should().BeTrue();
unitOfWork.ShouldRaisePropertyChangeFor( u => u.HasPendingChanges );
}
[Fact]
public void register_new_should_not_allow_delete()
{
// arrange
var item = new object();
var mock = new Mock<UnitOfWork<object>>() { CallBase = true };
mock.Protected().Setup<bool>( "IsNew", ItExpr.IsAny<object>() ).Returns( false );
var unitOfWork = mock.Object;
unitOfWork.RegisterRemoved( item );
// act
Action registerNew = () => unitOfWork.RegisterNew( item );
// assert
registerNew.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void register_new_should_not_allow_update()
{
// arrange
var item = new object();
var mock = new Mock<UnitOfWork<object>>() { CallBase = true };
mock.Protected().Setup<bool>( "IsNew", ItExpr.IsAny<object>() ).Returns( false );
var unitOfWork = mock.Object;
unitOfWork.RegisterChanged( item );
// act
Action registerNew = () => unitOfWork.RegisterNew( item );
// assert
registerNew.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void register_changed_should_mark_item_for_update()
{
// arrange
var mock = new Mock<UnitOfWork<object>>() { CallBase = true };
var unitOfWork = mock.Object;
unitOfWork.MonitorEvents();
// act
unitOfWork.RegisterNew( new object() );
// assert
unitOfWork.HasPendingChanges.Should().BeTrue();
unitOfWork.ShouldRaisePropertyChangeFor( u => u.HasPendingChanges );
}
[Fact]
public void register_changed_should_not_trigger_update_for_new_item()
{
// arrange
var item = new object();
var mock = new Mock<UnitOfWork<object>>() { CallBase = true };
var unitOfWork = mock.Object;
unitOfWork.RegisterNew( item );
unitOfWork.MonitorEvents();
// act
unitOfWork.RegisterChanged( item );
// assert
unitOfWork.HasPendingChanges.Should().BeTrue();
unitOfWork.ShouldNotRaisePropertyChangeFor( u => u.HasPendingChanges );
}
[Fact]
public void register_changed_should_not_trigger_update_for_deleted_item()
{
// arrange
var item = new object();
var mock = new Mock<UnitOfWork<object>>() { CallBase = true };
mock.Protected().Setup<bool>( "IsNew", ItExpr.IsAny<object>() ).Returns( false );
var unitOfWork = mock.Object;
unitOfWork.RegisterRemoved( item );
unitOfWork.MonitorEvents();
// act
unitOfWork.RegisterChanged( item );
// assert
unitOfWork.HasPendingChanges.Should().BeTrue();
unitOfWork.ShouldNotRaisePropertyChangeFor( u => u.HasPendingChanges );
}
[Fact]
public void register_removed_should_mark_item_for_delete()
{
// arrange
var item = new object();
var mock = new Mock<UnitOfWork<object>>() { CallBase = true };
mock.Protected().Setup<bool>( "IsNew", ItExpr.IsAny<object>() ).Returns( false );
var unitOfWork = mock.Object;
unitOfWork.MonitorEvents();
// act
unitOfWork.RegisterRemoved( item );
// assert
unitOfWork.HasPendingChanges.Should().BeTrue();
unitOfWork.ShouldRaisePropertyChangeFor( u => u.HasPendingChanges );
}
[Fact]
public void register_removed_should_not_trigger_delete_of_new_item()
{
// arrange
var item = new object();
var mock = new Mock<UnitOfWork<object>>() { CallBase = true };
mock.Protected().Setup<bool>( "IsNew", ItExpr.IsAny<object>() ).Returns( true );
var unitOfWork = mock.Object;
unitOfWork.RegisterNew( item );
unitOfWork.MonitorEvents();
// act
unitOfWork.RegisterRemoved( item );
// assert
unitOfWork.HasPendingChanges.Should().BeFalse();
unitOfWork.ShouldRaisePropertyChangeFor( u => u.HasPendingChanges );
}
[Fact]
public void register_removed_should_not_trigger_delete_of_untracked_item()
{
// arrange
var item = new object();
var mock = new Mock<UnitOfWork<object>>() { CallBase = true };
mock.Protected().Setup<bool>( "IsNew", ItExpr.IsAny<object>() ).Returns( true );
var unitOfWork = mock.Object;
unitOfWork.MonitorEvents();
// act
unitOfWork.RegisterRemoved( item );
// assert
unitOfWork.HasPendingChanges.Should().BeFalse();
unitOfWork.ShouldNotRaisePropertyChangeFor( u => u.HasPendingChanges );
}
[Fact]
public void unregister_should_not_raise_event_when_no_changes_are_triggered()
{
// arrange
var item = new object();
var mock = new Mock<UnitOfWork<object>>() { CallBase = true };
var unitOfWork = mock.Object;
unitOfWork.MonitorEvents();
// act
unitOfWork.Unregister( item );
// assert
unitOfWork.HasPendingChanges.Should().BeFalse();
unitOfWork.ShouldNotRaisePropertyChangeFor( u => u.HasPendingChanges );
}
[Fact]
public void unregister_should_raise_event_when_changes_are_triggered()
{
// arrange
var item = new object();
var mock = new Mock<UnitOfWork<object>>() { CallBase = true };
var unitOfWork = mock.Object;
unitOfWork.RegisterNew( item );
unitOfWork.MonitorEvents();
// act
unitOfWork.Unregister( item );
// assert
unitOfWork.HasPendingChanges.Should().BeFalse();
unitOfWork.ShouldRaisePropertyChangeFor( u => u.HasPendingChanges );
}
[Fact]
public void rollback_should_accept_changes()
{
// arrange
var mock = new Mock<UnitOfWork<object>>() { CallBase = true };
mock.Protected().Setup( "AcceptChanges" );
var unitOfWork = mock.Object;
unitOfWork.MonitorEvents();
// act
unitOfWork.Rollback();
// assert
mock.Protected().Verify( "AcceptChanges", Times.Once() );
unitOfWork.HasPendingChanges.Should().BeFalse();
unitOfWork.ShouldNotRaisePropertyChangeFor( u => u.HasPendingChanges );
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// KeyInfo.cs
//
// 21 [....] 2000
//
namespace System.Security.Cryptography.Xml
{
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class KeyInfo : IEnumerable {
private string m_id = null;
private ArrayList m_KeyInfoClauses;
//
// public constructors
//
public KeyInfo() {
m_KeyInfoClauses = new ArrayList();
}
//
// public properties
//
public String Id {
get { return m_id; }
set { m_id = value; }
}
public XmlElement GetXml() {
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.PreserveWhitespace = true;
return GetXml(xmlDocument);
}
internal XmlElement GetXml (XmlDocument xmlDocument) {
// Create the KeyInfo element itself
XmlElement keyInfoElement = xmlDocument.CreateElement("KeyInfo", SignedXml.XmlDsigNamespaceUrl);
if (!String.IsNullOrEmpty(m_id)) {
keyInfoElement.SetAttribute("Id", m_id);
}
// Add all the clauses that go underneath it
for (int i = 0; i < m_KeyInfoClauses.Count; ++i) {
XmlElement xmlElement = ((KeyInfoClause) m_KeyInfoClauses[i]).GetXml(xmlDocument);
if (xmlElement != null) {
keyInfoElement.AppendChild(xmlElement);
}
}
return keyInfoElement;
}
public void LoadXml(XmlElement value) {
if (value == null)
throw new ArgumentNullException("value");
XmlElement keyInfoElement = value;
m_id = Utils.GetAttribute(keyInfoElement, "Id", SignedXml.XmlDsigNamespaceUrl);
XmlNode child = keyInfoElement.FirstChild;
while (child != null) {
XmlElement elem = child as XmlElement;
if (elem != null) {
// Create the right type of KeyInfoClause; we use a combination of the namespace and tag name (local name)
String kicString = elem.NamespaceURI + " " + elem.LocalName;
// Special-case handling for KeyValue -- we have to go one level deeper
if (kicString == "http://www.w3.org/2000/09/xmldsig# KeyValue") {
XmlNodeList nodeList2 = elem.ChildNodes;
foreach (XmlNode node2 in nodeList2) {
XmlElement elem2 = node2 as XmlElement;
if (elem2 != null) {
kicString += "/" + elem2.LocalName;
break;
}
}
}
KeyInfoClause keyInfoClause = (KeyInfoClause) CryptoConfig.CreateFromName(kicString);
// if we don't know what kind of KeyInfoClause we're looking at, use a generic KeyInfoNode:
if (keyInfoClause == null)
keyInfoClause = new KeyInfoNode();
// Ask the create clause to fill itself with the corresponding XML
keyInfoClause.LoadXml(elem);
// Add it to our list of KeyInfoClauses
AddClause(keyInfoClause);
}
child = child.NextSibling;
}
}
public Int32 Count {
get { return m_KeyInfoClauses.Count; }
}
//
// public constructors
//
public void AddClause(KeyInfoClause clause) {
m_KeyInfoClauses.Add(clause);
}
public IEnumerator GetEnumerator() {
return m_KeyInfoClauses.GetEnumerator();
}
public IEnumerator GetEnumerator(Type requestedObjectType) {
ArrayList requestedList = new ArrayList();
Object tempObj;
IEnumerator tempEnum = m_KeyInfoClauses.GetEnumerator();
while(tempEnum.MoveNext()) {
tempObj = tempEnum.Current;
if (requestedObjectType.Equals(tempObj.GetType()))
requestedList.Add(tempObj);
}
return requestedList.GetEnumerator();
}
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public abstract class KeyInfoClause {
//
// protected constructors
//
protected KeyInfoClause () {}
//
// public methods
//
public abstract XmlElement GetXml();
internal virtual XmlElement GetXml (XmlDocument xmlDocument) {
XmlElement keyInfo = GetXml();
return (XmlElement) xmlDocument.ImportNode(keyInfo, true);
}
public abstract void LoadXml(XmlElement element);
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class KeyInfoName : KeyInfoClause {
private string m_keyName;
//
// public constructors
//
public KeyInfoName () : this (null) {}
public KeyInfoName (string keyName) {
this.Value = keyName;
}
//
// public properties
//
public String Value {
get { return m_keyName; }
set { m_keyName = value; }
}
//
// public methods
//
public override XmlElement GetXml() {
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.PreserveWhitespace = true;
return GetXml(xmlDocument);
}
internal override XmlElement GetXml (XmlDocument xmlDocument) {
XmlElement nameElement = xmlDocument.CreateElement("KeyName", SignedXml.XmlDsigNamespaceUrl);
nameElement.AppendChild(xmlDocument.CreateTextNode(m_keyName));
return nameElement;
}
public override void LoadXml(XmlElement value) {
if (value == null)
throw new ArgumentNullException("value");
XmlElement nameElement = value;
m_keyName = nameElement.InnerText.Trim();
}
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class DSAKeyValue : KeyInfoClause {
private DSA m_key;
//
// public constructors
//
public DSAKeyValue () {
m_key = DSA.Create();
}
public DSAKeyValue (DSA key) {
m_key = key;
}
//
// public properties
//
public DSA Key {
get { return m_key; }
set { m_key = value; }
}
//
// public methods
//
public override XmlElement GetXml() {
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.PreserveWhitespace = true;
return GetXml(xmlDocument);
}
internal override XmlElement GetXml (XmlDocument xmlDocument) {
DSAParameters dsaParams = m_key.ExportParameters(false);
XmlElement keyValueElement = xmlDocument.CreateElement("KeyValue", SignedXml.XmlDsigNamespaceUrl);
XmlElement dsaKeyValueElement = xmlDocument.CreateElement("DSAKeyValue", SignedXml.XmlDsigNamespaceUrl);
XmlElement pElement = xmlDocument.CreateElement("P", SignedXml.XmlDsigNamespaceUrl);
pElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.P)));
dsaKeyValueElement.AppendChild(pElement);
XmlElement qElement = xmlDocument.CreateElement("Q", SignedXml.XmlDsigNamespaceUrl);
qElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.Q)));
dsaKeyValueElement.AppendChild(qElement);
XmlElement gElement = xmlDocument.CreateElement("G", SignedXml.XmlDsigNamespaceUrl);
gElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.G)));
dsaKeyValueElement.AppendChild(gElement);
XmlElement yElement = xmlDocument.CreateElement("Y", SignedXml.XmlDsigNamespaceUrl);
yElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.Y)));
dsaKeyValueElement.AppendChild(yElement);
// Add optional components if present
if (dsaParams.J != null) {
XmlElement jElement = xmlDocument.CreateElement("J", SignedXml.XmlDsigNamespaceUrl);
jElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.J)));
dsaKeyValueElement.AppendChild(jElement);
}
if (dsaParams.Seed != null) { // note we assume counter is correct if Seed is present
XmlElement seedElement = xmlDocument.CreateElement("Seed", SignedXml.XmlDsigNamespaceUrl);
seedElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.Seed)));
dsaKeyValueElement.AppendChild(seedElement);
XmlElement counterElement = xmlDocument.CreateElement("PgenCounter", SignedXml.XmlDsigNamespaceUrl);
counterElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(Utils.ConvertIntToByteArray(dsaParams.Counter))));
dsaKeyValueElement.AppendChild(counterElement);
}
keyValueElement.AppendChild(dsaKeyValueElement);
return keyValueElement;
}
public override void LoadXml(XmlElement value) {
if (value == null)
throw new ArgumentNullException("value");
// Get the XML string
m_key.FromXmlString(value.OuterXml);
}
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class RSAKeyValue : KeyInfoClause {
private RSA m_key;
//
// public constructors
//
public RSAKeyValue () {
m_key = RSA.Create();
}
public RSAKeyValue (RSA key) {
m_key = key;
}
//
// public properties
//
public RSA Key {
get { return m_key; }
set { m_key = value; }
}
//
// public methods
//
public override XmlElement GetXml() {
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.PreserveWhitespace = true;
return GetXml(xmlDocument);
}
internal override XmlElement GetXml (XmlDocument xmlDocument) {
RSAParameters rsaParams = m_key.ExportParameters(false);
XmlElement keyValueElement = xmlDocument.CreateElement("KeyValue", SignedXml.XmlDsigNamespaceUrl);
XmlElement rsaKeyValueElement = xmlDocument.CreateElement("RSAKeyValue", SignedXml.XmlDsigNamespaceUrl);
XmlElement modulusElement = xmlDocument.CreateElement("Modulus", SignedXml.XmlDsigNamespaceUrl);
modulusElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(rsaParams.Modulus)));
rsaKeyValueElement.AppendChild(modulusElement);
XmlElement exponentElement = xmlDocument.CreateElement("Exponent", SignedXml.XmlDsigNamespaceUrl);
exponentElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(rsaParams.Exponent)));
rsaKeyValueElement.AppendChild(exponentElement);
keyValueElement.AppendChild(rsaKeyValueElement);
return keyValueElement;
}
public override void LoadXml(XmlElement value) {
if (value == null)
throw new ArgumentNullException("value");
// Get the XML string
m_key.FromXmlString(value.OuterXml);
}
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class KeyInfoRetrievalMethod : KeyInfoClause {
private String m_uri;
private String m_type;
//
// public constructors
//
public KeyInfoRetrievalMethod () {}
public KeyInfoRetrievalMethod (string strUri) {
m_uri = strUri;
}
public KeyInfoRetrievalMethod (String strUri, String typeName) {
m_uri = strUri;
m_type = typeName;
}
//
// public properties
//
public String Uri {
get { return m_uri; }
set { m_uri = value; }
}
[ComVisible(false)]
public String Type {
get { return m_type; }
set { m_type = value; }
}
public override XmlElement GetXml() {
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.PreserveWhitespace = true;
return GetXml(xmlDocument);
}
internal override XmlElement GetXml (XmlDocument xmlDocument) {
// Create the actual element
XmlElement retrievalMethodElement = xmlDocument.CreateElement("RetrievalMethod",SignedXml.XmlDsigNamespaceUrl);
if (!String.IsNullOrEmpty(m_uri))
retrievalMethodElement.SetAttribute("URI", m_uri);
if (!String.IsNullOrEmpty(m_type))
retrievalMethodElement.SetAttribute("Type", m_type);
return retrievalMethodElement;
}
public override void LoadXml (XmlElement value) {
if (value == null)
throw new ArgumentNullException("value");
XmlElement retrievalMethodElement = value;
m_uri = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl);
m_type = Utils.GetAttribute(value, "Type", SignedXml.XmlDsigNamespaceUrl);
}
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class KeyInfoEncryptedKey : KeyInfoClause {
private EncryptedKey m_encryptedKey;
public KeyInfoEncryptedKey () {}
public KeyInfoEncryptedKey (EncryptedKey encryptedKey) {
m_encryptedKey = encryptedKey;
}
public EncryptedKey EncryptedKey {
get { return m_encryptedKey; }
set { m_encryptedKey = value; }
}
public override XmlElement GetXml() {
if (m_encryptedKey == null)
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "KeyInfoEncryptedKey");
return m_encryptedKey.GetXml();
}
internal override XmlElement GetXml (XmlDocument xmlDocument) {
if (m_encryptedKey == null)
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "KeyInfoEncryptedKey");
return m_encryptedKey.GetXml(xmlDocument);
}
public override void LoadXml(XmlElement value) {
m_encryptedKey = new EncryptedKey();
m_encryptedKey.LoadXml(value);
}
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public struct X509IssuerSerial {
private string issuerName;
private string serialNumber;
internal X509IssuerSerial (string issuerName, string serialNumber) {
if (issuerName == null || issuerName.Length == 0)
throw new ArgumentException(SecurityResources.GetResourceString("Arg_EmptyOrNullString"), "issuerName");
if (serialNumber == null || serialNumber.Length == 0)
throw new ArgumentException(SecurityResources.GetResourceString("Arg_EmptyOrNullString"), "serialNumber");
this.issuerName = issuerName;
this.serialNumber = serialNumber;
}
public string IssuerName {
get {
return issuerName;
}
set {
issuerName = value;
}
}
public string SerialNumber {
get {
return serialNumber;
}
set {
serialNumber = value;
}
}
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class KeyInfoX509Data : KeyInfoClause {
// An array of certificates representing the certificate chain
private ArrayList m_certificates = null;
// An array of issuer serial structs
private ArrayList m_issuerSerials = null;
// An array of SKIs
private ArrayList m_subjectKeyIds = null;
// An array of subject names
private ArrayList m_subjectNames = null;
// A raw byte data representing a certificate revocation list
private byte[] m_CRL = null;
//
// public constructors
//
public KeyInfoX509Data () {}
public KeyInfoX509Data (byte[] rgbCert) {
X509Certificate2 certificate = new X509Certificate2(rgbCert);
AddCertificate(certificate);
}
public KeyInfoX509Data (X509Certificate cert) {
AddCertificate(cert);
}
[SecuritySafeCritical]
public KeyInfoX509Data (X509Certificate cert, X509IncludeOption includeOption) {
if (cert == null)
throw new ArgumentNullException("cert");
X509Certificate2 certificate = new X509Certificate2(cert);
X509ChainElementCollection elements = null;
X509Chain chain = null;
switch (includeOption) {
case X509IncludeOption.ExcludeRoot:
// Build the certificate chain
chain = new X509Chain();
chain.Build(certificate);
// Can't honor the option if we only have a partial chain.
if ((chain.ChainStatus.Length > 0) &&
((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain))
throw new CryptographicException(CAPI.CERT_E_CHAINING);
elements = (X509ChainElementCollection) chain.ChainElements;
for (int index = 0; index < (X509Utils.IsSelfSigned(chain) ? 1 : elements.Count - 1); index++) {
AddCertificate(elements[index].Certificate);
}
break;
case X509IncludeOption.EndCertOnly:
AddCertificate(certificate);
break;
case X509IncludeOption.WholeChain:
// Build the certificate chain
chain = new X509Chain();
chain.Build(certificate);
// Can't honor the option if we only have a partial chain.
if ((chain.ChainStatus.Length > 0) &&
((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain))
throw new CryptographicException(CAPI.CERT_E_CHAINING);
elements = (X509ChainElementCollection) chain.ChainElements;
foreach (X509ChainElement element in elements) {
AddCertificate(element.Certificate);
}
break;
}
}
//
// public properties
//
public ArrayList Certificates {
get { return m_certificates; }
}
public void AddCertificate (X509Certificate certificate) {
if (certificate == null)
throw new ArgumentNullException("certificate");
if (m_certificates == null)
m_certificates = new ArrayList();
X509Certificate2 x509 = new X509Certificate2(certificate);
m_certificates.Add(x509);
}
public ArrayList SubjectKeyIds {
get { return m_subjectKeyIds; }
}
public void AddSubjectKeyId(byte[] subjectKeyId) {
if (m_subjectKeyIds == null)
m_subjectKeyIds = new ArrayList();
m_subjectKeyIds.Add(subjectKeyId);
}
[ComVisible(false)]
public void AddSubjectKeyId(string subjectKeyId) {
if (m_subjectKeyIds == null)
m_subjectKeyIds = new ArrayList();
m_subjectKeyIds.Add(X509Utils.DecodeHexString(subjectKeyId));
}
public ArrayList SubjectNames {
get { return m_subjectNames; }
}
public void AddSubjectName(string subjectName) {
if (m_subjectNames == null)
m_subjectNames = new ArrayList();
m_subjectNames.Add(subjectName);
}
public ArrayList IssuerSerials {
get { return m_issuerSerials; }
}
public void AddIssuerSerial(string issuerName, string serialNumber) {
BigInt h = new BigInt();
h.FromHexadecimal(serialNumber);
if (m_issuerSerials == null)
m_issuerSerials = new ArrayList();
m_issuerSerials.Add(new X509IssuerSerial(issuerName, h.ToDecimal()));
}
// When we load an X509Data from Xml, we know the serial number is in decimal representation.
internal void InternalAddIssuerSerial(string issuerName, string serialNumber) {
if (m_issuerSerials == null)
m_issuerSerials = new ArrayList();
m_issuerSerials.Add(new X509IssuerSerial(issuerName, serialNumber));
}
public byte[] CRL {
get { return m_CRL; }
set { m_CRL = value; }
}
//
// private methods
//
private void Clear() {
m_CRL = null;
if (m_subjectKeyIds != null) m_subjectKeyIds.Clear();
if (m_subjectNames != null) m_subjectNames.Clear();
if (m_issuerSerials != null) m_issuerSerials.Clear();
if (m_certificates != null) m_certificates.Clear();
}
//
// public methods
//
public override XmlElement GetXml() {
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.PreserveWhitespace = true;
return GetXml(xmlDocument);
}
internal override XmlElement GetXml (XmlDocument xmlDocument) {
XmlElement x509DataElement = xmlDocument.CreateElement("X509Data", SignedXml.XmlDsigNamespaceUrl);
if (m_issuerSerials != null) {
foreach(X509IssuerSerial issuerSerial in m_issuerSerials) {
XmlElement issuerSerialElement = xmlDocument.CreateElement("X509IssuerSerial", SignedXml.XmlDsigNamespaceUrl);
XmlElement issuerNameElement = xmlDocument.CreateElement("X509IssuerName", SignedXml.XmlDsigNamespaceUrl);
issuerNameElement.AppendChild(xmlDocument.CreateTextNode(issuerSerial.IssuerName));
issuerSerialElement.AppendChild(issuerNameElement);
XmlElement serialNumberElement = xmlDocument.CreateElement("X509SerialNumber", SignedXml.XmlDsigNamespaceUrl);
serialNumberElement.AppendChild(xmlDocument.CreateTextNode(issuerSerial.SerialNumber));
issuerSerialElement.AppendChild(serialNumberElement);
x509DataElement.AppendChild(issuerSerialElement);
}
}
if (m_subjectKeyIds != null) {
foreach(byte[] subjectKeyId in m_subjectKeyIds) {
XmlElement subjectKeyIdElement = xmlDocument.CreateElement("X509SKI", SignedXml.XmlDsigNamespaceUrl);
subjectKeyIdElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(subjectKeyId)));
x509DataElement.AppendChild(subjectKeyIdElement);
}
}
if (m_subjectNames != null) {
foreach(string subjectName in m_subjectNames) {
XmlElement subjectNameElement = xmlDocument.CreateElement("X509SubjectName", SignedXml.XmlDsigNamespaceUrl);
subjectNameElement.AppendChild(xmlDocument.CreateTextNode(subjectName));
x509DataElement.AppendChild(subjectNameElement);
}
}
if (m_certificates != null) {
foreach(X509Certificate certificate in m_certificates) {
XmlElement x509Element = xmlDocument.CreateElement("X509Certificate", SignedXml.XmlDsigNamespaceUrl);
x509Element.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(certificate.GetRawCertData())));
x509DataElement.AppendChild(x509Element);
}
}
if (m_CRL != null) {
XmlElement crlElement = xmlDocument.CreateElement("X509CRL", SignedXml.XmlDsigNamespaceUrl);
crlElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(m_CRL)));
x509DataElement.AppendChild(crlElement);
}
return x509DataElement;
}
public override void LoadXml(XmlElement element) {
if (element == null)
throw new ArgumentNullException("element");
XmlNamespaceManager nsm = new XmlNamespaceManager(element.OwnerDocument.NameTable);
nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
XmlNodeList x509IssuerSerialNodes = element.SelectNodes("ds:X509IssuerSerial", nsm);
XmlNodeList x509SKINodes = element.SelectNodes("ds:X509SKI", nsm);
XmlNodeList x509SubjectNameNodes = element.SelectNodes("ds:X509SubjectName", nsm);
XmlNodeList x509CertificateNodes = element.SelectNodes("ds:X509Certificate", nsm);
XmlNodeList x509CRLNodes = element.SelectNodes("ds:X509CRL", nsm);
if ((x509CRLNodes.Count == 0 && x509IssuerSerialNodes.Count == 0 && x509SKINodes.Count == 0
&& x509SubjectNameNodes.Count == 0 && x509CertificateNodes.Count == 0)) // Bad X509Data tag, or Empty tag
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "X509Data");
// Flush anything in the lists
Clear();
if (x509CRLNodes.Count != 0)
m_CRL = Convert.FromBase64String(Utils.DiscardWhiteSpaces(x509CRLNodes.Item(0).InnerText));
foreach (XmlNode issuerSerialNode in x509IssuerSerialNodes) {
XmlNode x509IssuerNameNode = issuerSerialNode.SelectSingleNode("ds:X509IssuerName", nsm);
XmlNode x509SerialNumberNode = issuerSerialNode.SelectSingleNode("ds:X509SerialNumber", nsm);
if (x509IssuerNameNode == null || x509SerialNumberNode == null)
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "IssuerSerial");
InternalAddIssuerSerial(x509IssuerNameNode.InnerText.Trim(), x509SerialNumberNode.InnerText.Trim());
}
foreach (XmlNode node in x509SKINodes) {
AddSubjectKeyId(Convert.FromBase64String(Utils.DiscardWhiteSpaces(node.InnerText)));
}
foreach (XmlNode node in x509SubjectNameNodes) {
AddSubjectName(node.InnerText.Trim());
}
foreach (XmlNode node in x509CertificateNodes) {
AddCertificate(new X509Certificate2(Convert.FromBase64String(Utils.DiscardWhiteSpaces(node.InnerText))));
}
}
}
// This is for generic, unknown nodes
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class KeyInfoNode : KeyInfoClause {
private XmlElement m_node;
//
// public constructors
//
public KeyInfoNode() {}
public KeyInfoNode(XmlElement node) {
m_node = node;
}
//
// public properties
//
public XmlElement Value {
get { return m_node; }
set { m_node = value; }
}
//
// public methods
//
public override XmlElement GetXml() {
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.PreserveWhitespace = true;
return GetXml(xmlDocument);
}
internal override XmlElement GetXml (XmlDocument xmlDocument) {
return xmlDocument.ImportNode(m_node, true) as XmlElement;
}
public override void LoadXml(XmlElement value) {
m_node = value;
}
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace Pinta.Effects
{
public partial class LevelsDialog
{
private global::Gtk.HBox hbox1;
private global::Gtk.VBox vbox2;
private global::Gtk.HBox hbox2;
private global::Gtk.Label labelInputHist;
private global::Gtk.HSeparator hseparator1;
private global::Pinta.Gui.Widgets.HistogramWidget histogramInput;
private global::Gtk.VBox vbox3;
private global::Gtk.HBox hbox3;
private global::Gtk.Label labelInput;
private global::Gtk.HSeparator hseparator2;
private global::Gtk.HBox hbox8;
private global::Gtk.VBox vboxInputSpin;
private global::Gtk.SpinButton spinInHigh;
private global::Pinta.Gui.Widgets.ColorPanelWidget colorpanelInHigh;
private global::Gtk.Alignment alignment1;
private global::Pinta.Gui.Widgets.ColorPanelWidget colorpanelInLow;
private global::Gtk.SpinButton spinInLow;
private global::Pinta.Gui.Widgets.ColorGradientWidget gradientInput;
private global::Gtk.VBox vbox4;
private global::Gtk.HBox hbox4;
private global::Gtk.Label labelOutput;
private global::Gtk.HSeparator hseparator3;
private global::Gtk.HBox hbox9;
private global::Pinta.Gui.Widgets.ColorGradientWidget gradientOutput;
private global::Gtk.VBox vboxOutputSpin;
private global::Gtk.SpinButton spinOutHigh;
private global::Pinta.Gui.Widgets.ColorPanelWidget colorpanelOutHigh;
private global::Gtk.SpinButton spinOutGamma;
private global::Pinta.Gui.Widgets.ColorPanelWidget colorpanelOutMid;
private global::Pinta.Gui.Widgets.ColorPanelWidget colorpanelOutLow;
private global::Gtk.SpinButton spinOutLow;
private global::Gtk.VBox vbox5;
private global::Gtk.HBox hbox5;
private global::Gtk.Label labelOutputHist;
private global::Gtk.HSeparator hseparator4;
private global::Pinta.Gui.Widgets.HistogramWidget histogramOutput;
private global::Gtk.HBox hboxBottom;
private global::Gtk.Button buttonAuto;
private global::Gtk.Button buttonReset;
private global::Gtk.CheckButton checkRed;
private global::Gtk.CheckButton checkGreen;
private global::Gtk.Button buttonOk;
private global::Gtk.Button buttonCancel;
private global::Gtk.CheckButton checkBlue;
private global::Gtk.Button buttonDummy;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget Pinta.Effects.LevelsDialog
this.Events = ((global::Gdk.EventMask)(260));
this.Name = "Pinta.Effects.LevelsDialog";
this.Title = global::Mono.Unix.Catalog.GetString ("Levels Adjustment");
this.TypeHint = ((global::Gdk.WindowTypeHint)(1));
this.WindowPosition = ((global::Gtk.WindowPosition)(4));
this.Resizable = false;
this.AllowGrow = false;
this.SkipTaskbarHint = true;
// Internal child Pinta.Effects.LevelsDialog.VBox
global::Gtk.VBox w1 = this.VBox;
w1.Events = ((global::Gdk.EventMask)(1534));
w1.Name = "dialog1_VBox";
w1.BorderWidth = ((uint)(2));
// Container child dialog1_VBox.Gtk.Box+BoxChild
this.hbox1 = new global::Gtk.HBox ();
this.hbox1.Events = ((global::Gdk.EventMask)(260));
this.hbox1.Name = "hbox1";
this.hbox1.Spacing = 6;
// Container child hbox1.Gtk.Box+BoxChild
this.vbox2 = new global::Gtk.VBox ();
this.vbox2.Name = "vbox2";
this.vbox2.Spacing = 6;
// Container child vbox2.Gtk.Box+BoxChild
this.hbox2 = new global::Gtk.HBox ();
this.hbox2.Name = "hbox2";
this.hbox2.Spacing = 6;
// Container child hbox2.Gtk.Box+BoxChild
this.labelInputHist = new global::Gtk.Label ();
this.labelInputHist.Name = "labelInputHist";
this.labelInputHist.LabelProp = global::Mono.Unix.Catalog.GetString ("Input Histogram");
this.hbox2.Add (this.labelInputHist);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.labelInputHist]));
w2.Position = 0;
w2.Expand = false;
w2.Fill = false;
// Container child hbox2.Gtk.Box+BoxChild
this.hseparator1 = new global::Gtk.HSeparator ();
this.hseparator1.Name = "hseparator1";
this.hbox2.Add (this.hseparator1);
global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.hseparator1]));
w3.Position = 1;
this.vbox2.Add (this.hbox2);
global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.hbox2]));
w4.Position = 0;
w4.Expand = false;
w4.Fill = false;
// Container child vbox2.Gtk.Box+BoxChild
this.histogramInput = new global::Pinta.Gui.Widgets.HistogramWidget ();
this.histogramInput.WidthRequest = 130;
this.histogramInput.Events = ((global::Gdk.EventMask)(256));
this.histogramInput.Name = "histogramInput";
this.histogramInput.FlipHorizontal = true;
this.histogramInput.FlipVertical = false;
this.vbox2.Add (this.histogramInput);
global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.histogramInput]));
w5.Position = 1;
this.hbox1.Add (this.vbox2);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.vbox2]));
w6.Position = 0;
// Container child hbox1.Gtk.Box+BoxChild
this.vbox3 = new global::Gtk.VBox ();
this.vbox3.Events = ((global::Gdk.EventMask)(36));
this.vbox3.Name = "vbox3";
this.vbox3.Spacing = 6;
// Container child vbox3.Gtk.Box+BoxChild
this.hbox3 = new global::Gtk.HBox ();
this.hbox3.Name = "hbox3";
this.hbox3.Spacing = 6;
// Container child hbox3.Gtk.Box+BoxChild
this.labelInput = new global::Gtk.Label ();
this.labelInput.Name = "labelInput";
this.labelInput.LabelProp = global::Mono.Unix.Catalog.GetString ("Input");
this.hbox3.Add (this.labelInput);
global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.labelInput]));
w7.Position = 0;
w7.Expand = false;
w7.Fill = false;
// Container child hbox3.Gtk.Box+BoxChild
this.hseparator2 = new global::Gtk.HSeparator ();
this.hseparator2.Name = "hseparator2";
this.hbox3.Add (this.hseparator2);
global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.hseparator2]));
w8.Position = 1;
this.vbox3.Add (this.hbox3);
global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.hbox3]));
w9.Position = 0;
w9.Expand = false;
w9.Fill = false;
// Container child vbox3.Gtk.Box+BoxChild
this.hbox8 = new global::Gtk.HBox ();
this.hbox8.Events = ((global::Gdk.EventMask)(260));
this.hbox8.Name = "hbox8";
this.hbox8.Spacing = 6;
// Container child hbox8.Gtk.Box+BoxChild
this.vboxInputSpin = new global::Gtk.VBox ();
this.vboxInputSpin.Name = "vboxInputSpin";
this.vboxInputSpin.Spacing = 6;
// Container child vboxInputSpin.Gtk.Box+BoxChild
this.spinInHigh = new global::Gtk.SpinButton (1, 255, 1);
this.spinInHigh.CanFocus = true;
this.spinInHigh.Name = "spinInHigh";
this.spinInHigh.Adjustment.PageIncrement = 10;
this.spinInHigh.ClimbRate = 1;
this.spinInHigh.Numeric = true;
this.spinInHigh.Value = 255;
this.vboxInputSpin.Add (this.spinInHigh);
global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(this.vboxInputSpin [this.spinInHigh]));
w10.Position = 0;
w10.Expand = false;
w10.Fill = false;
// Container child vboxInputSpin.Gtk.Box+BoxChild
this.colorpanelInHigh = new global::Pinta.Gui.Widgets.ColorPanelWidget ();
this.colorpanelInHigh.HeightRequest = 24;
this.colorpanelInHigh.Events = ((global::Gdk.EventMask)(256));
this.colorpanelInHigh.Name = "colorpanelInHigh";
this.vboxInputSpin.Add (this.colorpanelInHigh);
global::Gtk.Box.BoxChild w11 = ((global::Gtk.Box.BoxChild)(this.vboxInputSpin [this.colorpanelInHigh]));
w11.Position = 1;
w11.Expand = false;
w11.Fill = false;
// Container child vboxInputSpin.Gtk.Box+BoxChild
this.alignment1 = new global::Gtk.Alignment (0.5F, 0.5F, 1F, 1F);
this.alignment1.Name = "alignment1";
this.vboxInputSpin.Add (this.alignment1);
global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.vboxInputSpin [this.alignment1]));
w12.Position = 2;
// Container child vboxInputSpin.Gtk.Box+BoxChild
this.colorpanelInLow = new global::Pinta.Gui.Widgets.ColorPanelWidget ();
this.colorpanelInLow.HeightRequest = 24;
this.colorpanelInLow.Events = ((global::Gdk.EventMask)(256));
this.colorpanelInLow.Name = "colorpanelInLow";
this.vboxInputSpin.Add (this.colorpanelInLow);
global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.vboxInputSpin [this.colorpanelInLow]));
w13.Position = 3;
w13.Expand = false;
w13.Fill = false;
// Container child vboxInputSpin.Gtk.Box+BoxChild
this.spinInLow = new global::Gtk.SpinButton (0, 254, 1);
this.spinInLow.CanFocus = true;
this.spinInLow.Name = "spinInLow";
this.spinInLow.Adjustment.PageIncrement = 10;
this.spinInLow.ClimbRate = 1;
this.spinInLow.Numeric = true;
this.vboxInputSpin.Add (this.spinInLow);
global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.vboxInputSpin [this.spinInLow]));
w14.Position = 4;
w14.Expand = false;
w14.Fill = false;
this.hbox8.Add (this.vboxInputSpin);
global::Gtk.Box.BoxChild w15 = ((global::Gtk.Box.BoxChild)(this.hbox8 [this.vboxInputSpin]));
w15.Position = 0;
w15.Expand = false;
w15.Fill = false;
// Container child hbox8.Gtk.Box+BoxChild
this.gradientInput = new global::Pinta.Gui.Widgets.ColorGradientWidget ();
this.gradientInput.WidthRequest = 40;
this.gradientInput.CanFocus = true;
this.gradientInput.Events = ((global::Gdk.EventMask)(510));
this.gradientInput.ExtensionEvents = ((global::Gdk.ExtensionMode)(1));
this.gradientInput.Name = "gradientInput";
this.gradientInput.Count = 2;
this.hbox8.Add (this.gradientInput);
global::Gtk.Box.BoxChild w16 = ((global::Gtk.Box.BoxChild)(this.hbox8 [this.gradientInput]));
w16.Position = 1;
w16.Expand = false;
w16.Fill = false;
this.vbox3.Add (this.hbox8);
global::Gtk.Box.BoxChild w17 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.hbox8]));
w17.Position = 1;
this.hbox1.Add (this.vbox3);
global::Gtk.Box.BoxChild w18 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.vbox3]));
w18.Position = 1;
w18.Expand = false;
// Container child hbox1.Gtk.Box+BoxChild
this.vbox4 = new global::Gtk.VBox ();
this.vbox4.Name = "vbox4";
this.vbox4.Spacing = 6;
// Container child vbox4.Gtk.Box+BoxChild
this.hbox4 = new global::Gtk.HBox ();
this.hbox4.Name = "hbox4";
this.hbox4.Spacing = 6;
// Container child hbox4.Gtk.Box+BoxChild
this.labelOutput = new global::Gtk.Label ();
this.labelOutput.Name = "labelOutput";
this.labelOutput.LabelProp = global::Mono.Unix.Catalog.GetString ("Output");
this.hbox4.Add (this.labelOutput);
global::Gtk.Box.BoxChild w19 = ((global::Gtk.Box.BoxChild)(this.hbox4 [this.labelOutput]));
w19.Position = 0;
w19.Expand = false;
w19.Fill = false;
// Container child hbox4.Gtk.Box+BoxChild
this.hseparator3 = new global::Gtk.HSeparator ();
this.hseparator3.Name = "hseparator3";
this.hbox4.Add (this.hseparator3);
global::Gtk.Box.BoxChild w20 = ((global::Gtk.Box.BoxChild)(this.hbox4 [this.hseparator3]));
w20.Position = 1;
this.vbox4.Add (this.hbox4);
global::Gtk.Box.BoxChild w21 = ((global::Gtk.Box.BoxChild)(this.vbox4 [this.hbox4]));
w21.Position = 0;
w21.Expand = false;
w21.Fill = false;
// Container child vbox4.Gtk.Box+BoxChild
this.hbox9 = new global::Gtk.HBox ();
this.hbox9.Name = "hbox9";
this.hbox9.Spacing = 6;
// Container child hbox9.Gtk.Box+BoxChild
this.gradientOutput = new global::Pinta.Gui.Widgets.ColorGradientWidget ();
this.gradientOutput.WidthRequest = 40;
this.gradientOutput.Events = ((global::Gdk.EventMask)(256));
this.gradientOutput.Name = "gradientOutput";
this.gradientOutput.Count = 3;
this.hbox9.Add (this.gradientOutput);
global::Gtk.Box.BoxChild w22 = ((global::Gtk.Box.BoxChild)(this.hbox9 [this.gradientOutput]));
w22.Position = 1;
w22.Expand = false;
w22.Fill = false;
// Container child hbox9.Gtk.Box+BoxChild
this.vboxOutputSpin = new global::Gtk.VBox ();
this.vboxOutputSpin.Name = "vboxOutputSpin";
this.vboxOutputSpin.Spacing = 6;
// Container child vboxOutputSpin.Gtk.Box+BoxChild
this.spinOutHigh = new global::Gtk.SpinButton (2, 255, 1);
this.spinOutHigh.CanFocus = true;
this.spinOutHigh.Name = "spinOutHigh";
this.spinOutHigh.Adjustment.PageIncrement = 10;
this.spinOutHigh.ClimbRate = 1;
this.spinOutHigh.Numeric = true;
this.spinOutHigh.Value = 255;
this.vboxOutputSpin.Add (this.spinOutHigh);
global::Gtk.Box.BoxChild w23 = ((global::Gtk.Box.BoxChild)(this.vboxOutputSpin [this.spinOutHigh]));
w23.Position = 0;
w23.Expand = false;
w23.Fill = false;
// Container child vboxOutputSpin.Gtk.Box+BoxChild
this.colorpanelOutHigh = new global::Pinta.Gui.Widgets.ColorPanelWidget ();
this.colorpanelOutHigh.HeightRequest = 24;
this.colorpanelOutHigh.Events = ((global::Gdk.EventMask)(256));
this.colorpanelOutHigh.Name = "colorpanelOutHigh";
this.vboxOutputSpin.Add (this.colorpanelOutHigh);
global::Gtk.Box.BoxChild w24 = ((global::Gtk.Box.BoxChild)(this.vboxOutputSpin [this.colorpanelOutHigh]));
w24.Position = 1;
w24.Expand = false;
w24.Fill = false;
// Container child vboxOutputSpin.Gtk.Box+BoxChild
this.spinOutGamma = new global::Gtk.SpinButton (0, 100, 0.1);
this.spinOutGamma.CanFocus = true;
this.spinOutGamma.Name = "spinOutGamma";
this.spinOutGamma.Adjustment.PageIncrement = 10;
this.spinOutGamma.ClimbRate = 1;
this.spinOutGamma.Numeric = true;
this.spinOutGamma.Value = 1;
this.vboxOutputSpin.Add (this.spinOutGamma);
global::Gtk.Box.BoxChild w25 = ((global::Gtk.Box.BoxChild)(this.vboxOutputSpin [this.spinOutGamma]));
w25.Position = 2;
w25.Expand = false;
w25.Fill = false;
// Container child vboxOutputSpin.Gtk.Box+BoxChild
this.colorpanelOutMid = new global::Pinta.Gui.Widgets.ColorPanelWidget ();
this.colorpanelOutMid.HeightRequest = 24;
this.colorpanelOutMid.Events = ((global::Gdk.EventMask)(256));
this.colorpanelOutMid.Name = "colorpanelOutMid";
this.vboxOutputSpin.Add (this.colorpanelOutMid);
global::Gtk.Box.BoxChild w26 = ((global::Gtk.Box.BoxChild)(this.vboxOutputSpin [this.colorpanelOutMid]));
w26.Position = 3;
w26.Expand = false;
w26.Fill = false;
// Container child vboxOutputSpin.Gtk.Box+BoxChild
this.colorpanelOutLow = new global::Pinta.Gui.Widgets.ColorPanelWidget ();
this.colorpanelOutLow.HeightRequest = 24;
this.colorpanelOutLow.Events = ((global::Gdk.EventMask)(256));
this.colorpanelOutLow.Name = "colorpanelOutLow";
this.vboxOutputSpin.Add (this.colorpanelOutLow);
global::Gtk.Box.BoxChild w27 = ((global::Gtk.Box.BoxChild)(this.vboxOutputSpin [this.colorpanelOutLow]));
w27.Position = 4;
w27.Expand = false;
w27.Fill = false;
// Container child vboxOutputSpin.Gtk.Box+BoxChild
this.spinOutLow = new global::Gtk.SpinButton (0, 252, 1);
this.spinOutLow.CanFocus = true;
this.spinOutLow.Name = "spinOutLow";
this.spinOutLow.Adjustment.PageIncrement = 10;
this.spinOutLow.ClimbRate = 1;
this.spinOutLow.Numeric = true;
this.vboxOutputSpin.Add (this.spinOutLow);
global::Gtk.Box.BoxChild w28 = ((global::Gtk.Box.BoxChild)(this.vboxOutputSpin [this.spinOutLow]));
w28.Position = 5;
w28.Expand = false;
w28.Fill = false;
this.hbox9.Add (this.vboxOutputSpin);
global::Gtk.Box.BoxChild w29 = ((global::Gtk.Box.BoxChild)(this.hbox9 [this.vboxOutputSpin]));
w29.Position = 2;
w29.Expand = false;
w29.Fill = false;
this.vbox4.Add (this.hbox9);
global::Gtk.Box.BoxChild w30 = ((global::Gtk.Box.BoxChild)(this.vbox4 [this.hbox9]));
w30.Position = 1;
this.hbox1.Add (this.vbox4);
global::Gtk.Box.BoxChild w31 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.vbox4]));
w31.Position = 2;
w31.Expand = false;
w31.Fill = false;
// Container child hbox1.Gtk.Box+BoxChild
this.vbox5 = new global::Gtk.VBox ();
this.vbox5.Name = "vbox5";
this.vbox5.Spacing = 6;
// Container child vbox5.Gtk.Box+BoxChild
this.hbox5 = new global::Gtk.HBox ();
this.hbox5.Name = "hbox5";
this.hbox5.Spacing = 6;
// Container child hbox5.Gtk.Box+BoxChild
this.labelOutputHist = new global::Gtk.Label ();
this.labelOutputHist.Name = "labelOutputHist";
this.labelOutputHist.LabelProp = global::Mono.Unix.Catalog.GetString ("Output Histogram");
this.hbox5.Add (this.labelOutputHist);
global::Gtk.Box.BoxChild w32 = ((global::Gtk.Box.BoxChild)(this.hbox5 [this.labelOutputHist]));
w32.Position = 0;
w32.Expand = false;
w32.Fill = false;
// Container child hbox5.Gtk.Box+BoxChild
this.hseparator4 = new global::Gtk.HSeparator ();
this.hseparator4.Name = "hseparator4";
this.hbox5.Add (this.hseparator4);
global::Gtk.Box.BoxChild w33 = ((global::Gtk.Box.BoxChild)(this.hbox5 [this.hseparator4]));
w33.Position = 1;
this.vbox5.Add (this.hbox5);
global::Gtk.Box.BoxChild w34 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.hbox5]));
w34.Position = 0;
w34.Expand = false;
w34.Fill = false;
// Container child vbox5.Gtk.Box+BoxChild
this.histogramOutput = new global::Pinta.Gui.Widgets.HistogramWidget ();
this.histogramOutput.WidthRequest = 130;
this.histogramOutput.Events = ((global::Gdk.EventMask)(256));
this.histogramOutput.Name = "histogramOutput";
this.histogramOutput.FlipHorizontal = false;
this.histogramOutput.FlipVertical = false;
this.vbox5.Add (this.histogramOutput);
global::Gtk.Box.BoxChild w35 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.histogramOutput]));
w35.Position = 1;
this.hbox1.Add (this.vbox5);
global::Gtk.Box.BoxChild w36 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.vbox5]));
w36.Position = 3;
w1.Add (this.hbox1);
global::Gtk.Box.BoxChild w37 = ((global::Gtk.Box.BoxChild)(w1 [this.hbox1]));
w37.Position = 0;
// Container child dialog1_VBox.Gtk.Box+BoxChild
this.hboxBottom = new global::Gtk.HBox ();
this.hboxBottom.Name = "hboxBottom";
this.hboxBottom.Spacing = 6;
// Container child hboxBottom.Gtk.Box+BoxChild
this.buttonAuto = new global::Gtk.Button ();
this.buttonAuto.WidthRequest = 80;
this.buttonAuto.CanFocus = true;
this.buttonAuto.Name = "buttonAuto";
this.buttonAuto.UseUnderline = true;
this.buttonAuto.Label = global::Mono.Unix.Catalog.GetString ("Auto");
this.hboxBottom.Add (this.buttonAuto);
global::Gtk.Box.BoxChild w38 = ((global::Gtk.Box.BoxChild)(this.hboxBottom [this.buttonAuto]));
w38.Position = 0;
w38.Expand = false;
w38.Fill = false;
// Container child hboxBottom.Gtk.Box+BoxChild
this.buttonReset = new global::Gtk.Button ();
this.buttonReset.WidthRequest = 80;
this.buttonReset.CanFocus = true;
this.buttonReset.Name = "buttonReset";
this.buttonReset.UseUnderline = true;
this.buttonReset.Label = global::Mono.Unix.Catalog.GetString ("Reset");
this.hboxBottom.Add (this.buttonReset);
global::Gtk.Box.BoxChild w39 = ((global::Gtk.Box.BoxChild)(this.hboxBottom [this.buttonReset]));
w39.Position = 1;
w39.Expand = false;
w39.Fill = false;
// Container child hboxBottom.Gtk.Box+BoxChild
this.checkRed = new global::Gtk.CheckButton ();
this.checkRed.CanFocus = true;
this.checkRed.Name = "checkRed";
this.checkRed.Label = global::Mono.Unix.Catalog.GetString ("Red");
this.checkRed.Active = true;
this.checkRed.DrawIndicator = true;
this.checkRed.UseUnderline = true;
this.hboxBottom.Add (this.checkRed);
global::Gtk.Box.BoxChild w40 = ((global::Gtk.Box.BoxChild)(this.hboxBottom [this.checkRed]));
w40.Position = 2;
// Container child hboxBottom.Gtk.Box+BoxChild
this.checkGreen = new global::Gtk.CheckButton ();
this.checkGreen.CanFocus = true;
this.checkGreen.Name = "checkGreen";
this.checkGreen.Label = global::Mono.Unix.Catalog.GetString ("Green");
this.checkGreen.Active = true;
this.checkGreen.DrawIndicator = true;
this.checkGreen.UseUnderline = true;
this.hboxBottom.Add (this.checkGreen);
global::Gtk.Box.BoxChild w41 = ((global::Gtk.Box.BoxChild)(this.hboxBottom [this.checkGreen]));
w41.Position = 3;
// Container child hboxBottom.Gtk.Box+BoxChild
this.buttonOk = new global::Gtk.Button ();
this.buttonOk.WidthRequest = 80;
this.buttonOk.CanFocus = true;
this.buttonOk.Name = "buttonOk";
this.buttonOk.UseStock = true;
this.buttonOk.UseUnderline = true;
this.buttonOk.Label = "gtk-ok";
this.hboxBottom.Add (this.buttonOk);
global::Gtk.Box.BoxChild w42 = ((global::Gtk.Box.BoxChild)(this.hboxBottom [this.buttonOk]));
w42.PackType = ((global::Gtk.PackType)(1));
w42.Position = 4;
w42.Expand = false;
w42.Fill = false;
// Container child hboxBottom.Gtk.Box+BoxChild
this.buttonCancel = new global::Gtk.Button ();
this.buttonCancel.WidthRequest = 80;
this.buttonCancel.CanFocus = true;
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.UseStock = true;
this.buttonCancel.UseUnderline = true;
this.buttonCancel.Label = "gtk-cancel";
this.hboxBottom.Add (this.buttonCancel);
global::Gtk.Box.BoxChild w43 = ((global::Gtk.Box.BoxChild)(this.hboxBottom [this.buttonCancel]));
w43.PackType = ((global::Gtk.PackType)(1));
w43.Position = 5;
w43.Expand = false;
w43.Fill = false;
// Container child hboxBottom.Gtk.Box+BoxChild
this.checkBlue = new global::Gtk.CheckButton ();
this.checkBlue.CanFocus = true;
this.checkBlue.Name = "checkBlue";
this.checkBlue.Label = global::Mono.Unix.Catalog.GetString ("Blue");
this.checkBlue.Active = true;
this.checkBlue.DrawIndicator = true;
this.checkBlue.UseUnderline = true;
this.hboxBottom.Add (this.checkBlue);
global::Gtk.Box.BoxChild w44 = ((global::Gtk.Box.BoxChild)(this.hboxBottom [this.checkBlue]));
w44.PackType = ((global::Gtk.PackType)(1));
w44.Position = 6;
w1.Add (this.hboxBottom);
global::Gtk.Box.BoxChild w45 = ((global::Gtk.Box.BoxChild)(w1 [this.hboxBottom]));
w45.PackType = ((global::Gtk.PackType)(1));
w45.Position = 4;
w45.Expand = false;
w45.Fill = false;
// Internal child Pinta.Effects.LevelsDialog.ActionArea
global::Gtk.HButtonBox w46 = this.ActionArea;
w46.Name = "__gtksharp_58_Stetic_TopLevelDialog_ActionArea";
w46.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4));
// Container child __gtksharp_58_Stetic_TopLevelDialog_ActionArea.Gtk.ButtonBox+ButtonBoxChild
this.buttonDummy = new global::Gtk.Button ();
this.buttonDummy.Sensitive = false;
this.buttonDummy.CanFocus = true;
this.buttonDummy.Name = "buttonDummy";
this.buttonDummy.UseUnderline = true;
this.buttonDummy.Label = "In stetic action button box cannot be empty";
this.AddActionWidget (this.buttonDummy, -5);
global::Gtk.ButtonBox.ButtonBoxChild w47 = ((global::Gtk.ButtonBox.ButtonBoxChild)(w46 [this.buttonDummy]));
w47.Expand = false;
w47.Fill = false;
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.DefaultWidth = 1754;
this.DefaultHeight = 326;
this.buttonDummy.Hide ();
this.Show ();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Orleans;
using Orleans.CodeGenerator;
using Orleans.CodeGeneration;
using Orleans.CodeGenerator.Compatibility;
using Orleans.Runtime;
using Orleans.Utilities;
using Xunit;
using Xunit.Abstractions;
using Orleans.CodeGenerator.Model;
using System.Text;
using Orleans.Serialization;
[assembly: System.Reflection.AssemblyCompanyAttribute("Microsoft")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("2.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("2.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Microsoft Orleans")]
[assembly: System.Reflection.AssemblyTitleAttribute("CodeGenerator.Tests")]
[assembly: System.Reflection.AssemblyVersionAttribute("2.0.0.0")]
namespace CodeGenerator.Tests
{
/// <summary>
/// Tests for <see cref="RoslynTypeNameFormatter"/>.
/// </summary>
[Trait("Category", "BVT")]
public class RoslynTypeNameFormatterTests
{
private readonly ITestOutputHelper output;
private static readonly Type[] Types =
{
typeof(int),
typeof(int[]),
typeof(int**[]),
typeof(List<>),
typeof(Dictionary<string, Dictionary<int, bool>>),
typeof(Dictionary<,>),
typeof(List<int>),
typeof(List<int*[]>),
typeof(List<int*[]>.Enumerator),
typeof(List<>.Enumerator),
typeof(Generic<>),
typeof(Generic<>.Nested),
typeof(Generic<>.NestedGeneric<>),
typeof(Generic<>.NestedMultiGeneric<,>),
typeof(Generic<int>.Nested),
typeof(Generic<int>.NestedGeneric<bool>),
typeof(Generic<int>.NestedMultiGeneric<Generic<int>.NestedGeneric<bool>, double>)
};
private static readonly Type[] Grains =
{
typeof(IMyGenericGrainInterface3<,>),
typeof(IMyGenericGrainInterface3<int,int>),
typeof(IMyGenericGrainInterface2<>),
typeof(IMyGenericGrainInterface2<int>),
typeof(IMyGrainInterface),
typeof(IMyGrainInterfaceWithNamedTuple),
typeof(IMyGenericGrainInterface<int>),
typeof(IMyGrainInterfaceWithTypeCodeOverride),
typeof(MyGrainClass),
typeof(MyGenericGrainClass<int>),
typeof(MyGenericGrainClass<>),
typeof(MyGrainClassWithTypeCodeOverride),
typeof(NotNested.IMyGrainInterface),
typeof(NotNested.IMyGenericGrainInterface<int>),
typeof(NotNested.MyGrainClass),
typeof(NotNested.MyGenericGrainClass<int>),
typeof(NotNested.IMyGenericGrainInterface<>),
typeof(NotNested.MyGenericGrainClass<>),
};
private readonly CSharpCompilation compilation;
public RoslynTypeNameFormatterTests(ITestOutputHelper output)
{
this.output = output;
// Read the source code of this file and parse that with Roslyn.
var testCode = GetSource();
var metas = new[]
{
typeof(int).Assembly,
typeof(IGrain).Assembly,
typeof(Attribute).Assembly,
typeof(System.Net.IPAddress).Assembly,
typeof(ExcludeFromCodeCoverageAttribute).Assembly,
}.Select(a => MetadataReference.CreateFromFile(a.Location, MetadataReferenceProperties.Assembly));
var metadataReferences = metas.Concat(GetGlobalReferences()).ToArray();
var syntaxTrees = new[] { CSharpSyntaxTree.ParseText(testCode, path: "TestProgram.cs") };
var assemblyName = typeof(RoslynTypeNameFormatterTests).Assembly.GetName().Name;
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithMetadataImportOptions(MetadataImportOptions.All);
this.compilation = CSharpCompilation.Create(assemblyName, syntaxTrees, metadataReferences, options);
IEnumerable<MetadataReference> GetGlobalReferences()
{
// The location of the .NET assemblies
var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
return new List<MetadataReference>
{
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "netstandard.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.Serialization.Formatters.dll"))
};
}
}
private string GetSource()
{
var type = typeof(RoslynTypeNameFormatterTests);
using (var stream = type.Assembly.GetManifestResourceStream($"{type.Namespace}.{type.Name}.cs"))
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
/// <summary>
/// Tests that various strings formatted with <see cref="RoslynTypeNameFormatter"/> match their corresponding <see cref="Type.FullName"/> values.
/// </summary>
[Fact]
public void FullNameMatchesClr()
{
foreach (var (type, symbol) in GetTypeSymbolPairs(nameof(Types)))
{
this.output.WriteLine($"Type: {RuntimeTypeNameFormatter.Format(type)}");
var expected = type.FullName;
var actual = RoslynTypeNameFormatter.Format(symbol, RoslynTypeNameFormatter.Style.FullName);
this.output.WriteLine($"Expected FullName: {expected}\nActual FullName: {actual}");
Assert.Equal(expected, actual);
}
}
[Fact]
public void TypeKeyMatchesRuntimeTypeKey()
{
foreach (var (type, symbol) in GetTypeSymbolPairs(nameof(Types)))
{
var expectedTypeKey = TypeUtilities.OrleansTypeKeyString(type);
var actualTypeKey = OrleansLegacyCompat.OrleansTypeKeyString(symbol);
this.output.WriteLine($"Type: {RuntimeTypeNameFormatter.Format(type)}");
Assert.Equal(expectedTypeKey, actualTypeKey);
}
}
/// <summary>
/// Tests that the ITypeSymbol id generation algorithm generates ids which match the Type-based generator.
/// </summary>
[Fact]
public void TypeCodesMatch()
{
var wellKnownTypes = new WellKnownTypes(this.compilation);
foreach (var (type, symbol) in GetTypeSymbolPairs(nameof(Grains)))
{
this.output.WriteLine($"Type: {RuntimeTypeNameFormatter.Format(type)}");
{
// First check Type.FullName matches.
var expected = type.FullName;
var actual = RoslynTypeNameFormatter.Format(symbol, RoslynTypeNameFormatter.Style.FullName);
this.output.WriteLine($"Expected FullName: {expected}\nActual FullName: {actual}");
Assert.Equal(expected, actual);
}
{
var expected = TypeUtils.GetTemplatedName(
TypeUtils.GetFullName(type),
type,
type.GetGenericArgumentsSafe(),
t => false);
var named = Assert.IsAssignableFrom<INamedTypeSymbol>(symbol);
var actual = OrleansLegacyCompat.FormatTypeForIdComputation(named);
this.output.WriteLine($"Expected format: {expected}\nActual format: {actual}");
Assert.Equal(expected, actual);
}
{
var expected = GrainInterfaceUtils.GetGrainInterfaceId(type);
var named = Assert.IsAssignableFrom<INamedTypeSymbol>(symbol);
var actual = wellKnownTypes.GetTypeId(named);
this.output.WriteLine($"Expected Id: 0x{expected:X}\nActual Id: 0x{actual:X}");
Assert.Equal(expected, actual);
}
}
}
/// <summary>
/// Tests that the IMethodSymbol id generation algorithm generates ids which match the MethodInfo-based generator.
/// </summary>
[Fact]
public void MethodIdsMatch()
{
var wellKnownTypes = new WellKnownTypes(this.compilation);
foreach (var (type, typeSymbol) in GetTypeSymbolPairs(nameof(Grains)))
{
this.output.WriteLine($"Type: {RuntimeTypeNameFormatter.Format(type)}");
var methods = type.GetMethods();
var methodSymbols = methods.Select(m => typeSymbol.GetMembers(m.Name).SingleOrDefault()).OfType<IMethodSymbol>();
foreach (var (method, methodSymbol) in methods.Zip(methodSymbols, ValueTuple.Create))
{
this.output.WriteLine($"IMethodSymbol: {methodSymbol}, MethodInfo: {method}");
Assert.NotNull(methodSymbol);
{
var expected = GrainInterfaceUtils.FormatMethodForIdComputation(method);
var actual = OrleansLegacyCompat.FormatMethodForMethodIdComputation(methodSymbol);
this.output.WriteLine($"Expected format: {expected}\nActual format: {actual}");
Assert.Equal(expected, actual);
}
{
var expected = GrainInterfaceUtils.ComputeMethodId(method);
var actual = wellKnownTypes.GetMethodId(methodSymbol);
this.output.WriteLine($"Expected Id: 0x{expected:X}\nActual Id: 0x{actual:X}");
Assert.Equal(expected, actual);
}
}
}
}
private IEnumerable<(Type, ITypeSymbol)> GetTypeSymbolPairs(string fieldName)
{
var typesMember = compilation.Assembly.GlobalNamespace
.GetMembers("CodeGenerator")
.First()
.GetMembers("Tests")
.Cast<INamespaceOrTypeSymbol>()
.First()
.GetTypeMembers("RoslynTypeNameFormatterTests")
.First()
.GetMembers(fieldName)
.First();
var declaratorSyntax = Assert.IsType<VariableDeclaratorSyntax>(typesMember.DeclaringSyntaxReferences.First().GetSyntax());
var creationExpressionSyntax = Assert.IsType<InitializerExpressionSyntax>(declaratorSyntax.Initializer.Value);
var expressions = creationExpressionSyntax.Expressions;
var typeSymbols = new List<ITypeSymbol>();
var model = compilation.GetSemanticModel(declaratorSyntax.SyntaxTree);
foreach (var expr in expressions.ToList().OfType<TypeOfExpressionSyntax>())
{
var info = model.GetTypeInfo(expr.Type);
Assert.NotNull(info.Type);
typeSymbols.Add(info.Type);
}
var types = (Type[])this.GetType().GetField(fieldName, BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
var pairs = types.Zip(typeSymbols, ValueTuple.Create);
return pairs;
}
public interface IMyGrainInterface : IGrainWithGuidKey
{
Task One(int a, int b, int c);
Task<int> Two();
}
public class MyGrainClass : Grain, IMyGrainInterface
{
public Task One(int a, int b, int c) => throw new NotImplementedException();
public Task<int> Two() => throw new NotImplementedException();
}
public interface IMyGrainInterfaceWithNamedTuple : IGrainWithGuidKey
{
Task<string> SomeMethod(IEnumerable<(string name, object obj)> list);
}
public class MyGrainInterfaceWithNamedTuple : Grain, IMyGrainInterfaceWithNamedTuple
{
public Task<string> SomeMethod(IEnumerable<(string name, object obj)> list) => throw new NotImplementedException();
}
public interface IMyGenericGrainInterface<T> : IGrainWithGuidKey
{
Task One(T a, int b, int c);
Task<T> Two();
}
public interface IMyGenericGrainInterface2<in T> : IGrainWithGuidKey
{
Task One(T a, int b, int c);
}
public interface IMyGenericGrainInterface3<TOne, TTwo> : IGrainWithGuidKey
{
Task One(TOne a, TTwo b, int c);
}
public class MyGenericGrainClass<TOne> : Grain, IMyGenericGrainInterface<TOne>
{
public Task One(TOne a, int b, int c) => throw new NotImplementedException();
public Task<TOne> Two() => throw new NotImplementedException();
}
[TypeCodeOverride(1)]
public interface IMyGrainInterfaceWithTypeCodeOverride : IGrainWithGuidKey
{
[MethodId(1)]
Task One(int a, int b, int c);
[MethodId(2)]
Task<int> Two();
}
[TypeCodeOverride(2)]
public class MyGrainClassWithTypeCodeOverride : Grain, IMyGrainInterfaceWithTypeCodeOverride
{
[MethodId(12234)]
public Task One(int a, int b, int c) => throw new NotImplementedException();
[MethodId(-41243)]
public Task<int> Two() => throw new NotImplementedException();
}
}
namespace NotNested
{
public interface IMyGrainInterface : IGrainWithGuidKey
{
Task One(int a, int b, int c);
Task<int> Two();
}
public class MyGrainClass : Grain, IMyGrainInterface
{
public Task One(int a, int b, int c) => throw new NotImplementedException();
public Task<int> Two() => throw new NotImplementedException();
}
public interface IMyGenericGrainInterface<T> : IGrainWithGuidKey
{
Task One(T a, int b, int c);
Task<T> Two(T val);
Task<TU> Three<TU>(TU val);
}
public class MyGenericGrainClass<T> : Grain, IMyGenericGrainInterface<T>
{
public Task One(T a, int b, int c) => throw new NotImplementedException();
public Task<T> Two(T val) => throw new NotImplementedException();
public Task<TU> Three<TU>(TU val) => throw new NotImplementedException();
}
}
}
namespace System
{
public class Generic<T>
{
public class Nested { }
public class NestedGeneric<TU> { }
public class NestedMultiGeneric<TU, TV> { }
}
}
| |
// Engine r29
#define RunUo2_0
using System;
using Server;
using Server.Gumps;
using Server.Network;
using Server.Commands;
namespace Server.Gumps
{
public class PremiumSpawnerMainGump : Gump
{
Mobile caller;
public static void Initialize()
{
#if(RunUo2_0)
CommandSystem.Register("PremiumSpawner", AccessLevel.Administrator, new CommandEventHandler(PremiumSpawner_OnCommand));
CommandSystem.Register("Spawner", AccessLevel.Administrator, new CommandEventHandler(PremiumSpawner_OnCommand));
#else
Register("PremiumSpawner", AccessLevel.Administrator, new CommandEventHandler(PremiumSpawner_OnCommand));
Register("Spawner", AccessLevel.Administrator, new CommandEventHandler(PremiumSpawner_OnCommand));
#endif
}
[Usage("PremiumSpawner")]
[Aliases( "Spawner" )]
[Description("PremiumSpawner main gump.")]
public static void PremiumSpawner_OnCommand(CommandEventArgs e)
{
Mobile from = e.Mobile;
if (from.HasGump(typeof(PremiumSpawnerMainGump)))
from.CloseGump(typeof(PremiumSpawnerMainGump));
from.SendGump(new PremiumSpawnerMainGump(from));
}
public PremiumSpawnerMainGump(Mobile from) : this()
{
caller = from;
}
public void AddBlackAlpha( int x, int y, int width, int height )
{
AddImageTiled( x, y, width, height, 2624 );
AddAlphaRegion( x, y, width, height );
}
public PremiumSpawnerMainGump() : base( 0, 0 )
{
this.Closable=true;
this.Disposable=true;
this.Dragable=true;
//PAGE 1
AddPage(1);
AddBackground(93, 68, 256, 423, 9200);
AddHtml( 98, 75, 244, 44, " PREMIUM SPAWNER<BR>" + "by Nerun Rev.89", (bool)true, (bool)false);
AddBlackAlpha(100, 124, 241, 71);
AddLabel(109, 126, 52, @"WORLD CREATION");
AddLabel(126, 148, 52, @"Let there be light (Create World)");
AddLabel(126, 170, 52, @"Apocalypse now (Clear All Facets)");
AddButton(109, 151, 1210, 1209, 101, GumpButtonType.Reply, 0);
AddButton(109, 173, 1210, 1209, 102, GumpButtonType.Reply, 0);
AddBlackAlpha(100, 200, 241, 89);
AddLabel(109, 202, 52, @"SELECT SPAWNS BY EXPANSION");
AddLabel(126, 224, 52, @"UO Classic spawns (pre-T2A)");
AddLabel(126, 244, 52, @"UO Mondain's Legacy spawns");
AddLabel(126, 264, 52, @"UO KR, SA and HS spawns");
//AddLabel(238, 224, 52, @"UO:ML spawns");
//AddLabel(238, 244, 52, @"UO:KR, SA and HS spawns");
//AddLabel(238, 264, 52, @"teste");
AddButton(109, 227, 1210, 1209, 103, GumpButtonType.Reply, 0);
AddButton(109, 247, 1210, 1209, 104, GumpButtonType.Reply, 0);
AddButton(109, 267, 1210, 1209, 105, GumpButtonType.Reply, 0);
//AddButton(221, 227, 1210, 1209, 106, GumpButtonType.Reply, 0);
//AddButton(221, 247, 1210, 1209, 107, GumpButtonType.Reply, 0);
//AddButton(221, 267, 1210, 1209, 108, GumpButtonType.Reply, 0);
AddBlackAlpha(100, 294, 241, 89);
AddLabel(109, 296, 52, @"REMOVE SPAWNS BY EXPANSION");
AddLabel(126, 318, 52, @"UO Classic spawns (pre-T2A)");
AddLabel(126, 338, 52, @"UO Mondain's Legacy spawns");
AddLabel(126, 358, 52, @"UO KR, SA and HS spawns");
//AddLabel(238, 318, 52, @"Ter Mur");
//AddLabel(238, 338, 52, @"Tokuno");
//AddLabel(238, 358, 52, @"Trammel");
AddButton(109, 321, 1210, 1209, 109, GumpButtonType.Reply, 0);
AddButton(109, 341, 1210, 1209, 110, GumpButtonType.Reply, 0);
AddButton(109, 361, 1210, 1209, 111, GumpButtonType.Reply, 0);
//AddButton(221, 321, 1210, 1209, 112, GumpButtonType.Reply, 0);
//AddButton(221, 341, 1210, 1209, 113, GumpButtonType.Reply, 0);
//AddButton(221, 361, 1210, 1209, 114, GumpButtonType.Reply, 0);
AddBlackAlpha(100, 388, 241, 68);
AddLabel(109, 391, 52, @"SMART PLAYER RANGE SENSITIVE");
AddLabel(126, 413, 52, @"Generate Spawns' Overseer");
AddLabel(126, 432, 52, @"Remove Spawns' Overseer");
AddButton(109, 416, 1210, 1209, 115, GumpButtonType.Reply, 0);
AddButton(109, 435, 1210, 1209, 116, GumpButtonType.Reply, 0);
//Page change
AddLabel(207, 463, 200, @"1/3");
AddButton(235, 465, 5601, 5605, 0, GumpButtonType.Page, 2); //advance
// PAGE 2
AddPage(2);
AddBackground(93, 68, 256, 423, 9200);
AddHtml( 98, 75, 244, 44, " PREMIUM SPAWNER<BR>" + "by Nerun Rev.89", (bool)true, (bool)false);
AddBlackAlpha(100, 124, 241, 114);
AddLabel(109, 126, 52, @"SAVE SPAWNERS");
AddLabel(126, 148, 52, @"All spawns (spawns.map)");
AddLabel(126, 170, 52, @"'By hand' spawns (byhand.map)");
AddLabel(126, 192, 52, @"Spawns inside region (region.map)");
AddLabel(126, 214, 52, @"Spawns inside coordinates");
AddButton(109, 151, 1210, 1209, 117, GumpButtonType.Reply, 0);
AddButton(109, 173, 1210, 1209, 118, GumpButtonType.Reply, 0);
AddButton(109, 195, 1210, 1209, 119, GumpButtonType.Reply, 0);
AddButton(109, 217, 1210, 1209, 120, GumpButtonType.Reply, 0);
AddBlackAlpha(100, 244, 241, 134);
AddLabel(109, 246, 52, @"REMOVE SPAWNERS");
AddLabel(126, 268, 52, @"All spawners in ALL facets");
AddLabel(126, 290, 52, @"All spawners in THIS facet");
AddLabel(126, 312, 52, @"Remove spawners by SpawnID");
AddLabel(126, 334, 52, @"Remove inside coordinates");
AddLabel(126, 355, 52, @"Remove spawners inside region");
AddButton(109, 271, 1210, 1209, 121, GumpButtonType.Reply, 0);
AddButton(109, 293, 1210, 1209, 122, GumpButtonType.Reply, 0);
AddButton(109, 315, 1210, 1209, 123, GumpButtonType.Reply, 0);
AddButton(109, 337, 1210, 1209, 124, GumpButtonType.Reply, 0);
AddButton(109, 358, 1210, 1209, 125, GumpButtonType.Reply, 0);
AddBlackAlpha(100, 385, 241, 71);
AddLabel(109, 387, 52, @"EDITOR");
AddLabel(126, 408, 52, @"Spawn Editor (edit, find and list");
AddLabel(126, 427, 52, @"all PremiumSpawners in the world)");
AddButton(109, 411, 1210, 1209, 126, GumpButtonType.Reply, 0);
//Page change
AddLabel(207, 463, 200, @"2/3");
AddButton(189, 465, 5603, 5607, 0, GumpButtonType.Page, 1); //back
AddButton(235, 465, 5601, 5605, 0, GumpButtonType.Page, 3); //advance
//PAGE 3
AddPage(3);
AddBackground(93, 68, 256, 423, 9200);
AddHtml( 98, 75, 244, 44, " PREMIUM SPAWNER<BR>" + "by Nerun Rev.89", (bool)true, (bool)false);
AddBlackAlpha(101, 124, 241, 47);
AddLabel(109, 126, 52, @"CONVERSION UTILITY");
AddLabel(127, 148, 52, @"RunUO Spawners to Premium");
AddButton(110, 151, 1210, 1209, 127, GumpButtonType.Reply, 0);
AddBlackAlpha(101, 177, 241, 134);
AddLabel(109, 179, 52, @"CUSTOM REGIONS IN A BOX");
AddLabel(127, 201, 52, @"Add a Region Controler");
AddLabel(127, 222, 52, @"(double-click the Region");
AddLabel(127, 243, 52, @"Controller to configure it region.");
AddLabel(127, 264, 52, @"Every Controller control one");
AddLabel(127, 286, 52, @"region. Don't forget to prop)");
AddButton(110, 204, 1210, 1209, 128, GumpButtonType.Reply, 0);
//Page change
AddLabel(207, 463, 200, @"3/3");
AddButton(189, 465, 5603, 5607, 0, GumpButtonType.Page, 2); //back
}
public static void DoThis( Mobile from, string command)
{
string prefix = Server.Commands.CommandSystem.Prefix;
CommandSystem.Handle( from, String.Format( "{0}{1}", prefix, command ) );
CommandSystem.Handle( from, String.Format( "{0}spawner", prefix ) );
}
public override void OnResponse(NetState sender, RelayInfo info)
{
Mobile from = sender.Mobile;
switch(info.ButtonID)
{
case 0:
{
//Quit
break;
}
case 101:
{
DoThis( from, "createworld" );
break;
}
case 102:
{
DoThis( from, "clearall" );
break;
}
case 103:
{
from.Say( "SPAWNING UO Classic..." );
DoThis( from, "spawngen uoclassic/UOClassic.map" );
break;
}
case 104:
{
DoThis( from, "SpawnUOML" );
break;
}
case 105:
{
DoThis( from, "SpawnCurrent" );
break;
}
//DoThis( from106, "" );
//DoThis( from107, "" );
//DoThis( from108, "" );
case 109:
{
DoThis( from, "spawngen unload 1000" );
break;
}
case 110:
{
DoThis( from, "UnloadUOML" );
break;
}
case 111:
{
DoThis( from, "UnloadCurrent" );
break;
}
//DoThis( from112, "" );
//DoThis( from113, "" );
//DoThis( from114, "" );
case 115:
{
DoThis( from, "GenSeers" );
break;
}
case 116:
{
DoThis( from, "RemSeers" );
break;
}
case 117:
{
DoThis( from, "spawngen save" );
break;
}
case 118:
{
DoThis( from, "spawngen savebyhand" );
break;
}
case 119:
{
DoThis( from, "GumpSaveRegion" );
break;
}
case 120:
{
DoThis( from, "GumpSaveCoordinate" );
break;
}
case 121:
{
DoThis( from, "spawngen remove" );
break;
}
case 122:
{
DoThis( from, "spawngen cleanfacet" );
break;
}
case 123:
{
DoThis( from, "GumpRemoveID" );
break;
}
case 124:
{
DoThis( from, "GumpRemoveCoordinate" );
break;
}
case 125:
{
DoThis( from, "GumpRemoveRegion" );
break;
}
case 126:
{
DoThis( from, "SpawnEditor" );
break;
}
case 127:
{
DoThis( from, "RunUOSpawnerExporter" );
break;
}
case 128:
{
DoThis( from, "Add RegionControl" );
break;
}
}
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - [email protected])
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.3.5.1. Information about a request for supplies. COMPLETE
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(EntityID))]
[XmlInclude(typeof(SupplyQuantity))]
public partial class ServiceRequestPdu : LogisticsFamilyPdu, IEquatable<ServiceRequestPdu>
{
/// <summary>
/// Entity that is requesting service
/// </summary>
private EntityID _requestingEntityID = new EntityID();
/// <summary>
/// Entity that is providing the service
/// </summary>
private EntityID _servicingEntityID = new EntityID();
/// <summary>
/// type of service requested
/// </summary>
private byte _serviceTypeRequested;
/// <summary>
/// How many requested
/// </summary>
private byte _numberOfSupplyTypes;
/// <summary>
/// padding
/// </summary>
private short _serviceRequestPadding;
private List<SupplyQuantity> _supplies = new List<SupplyQuantity>();
/// <summary>
/// Initializes a new instance of the <see cref="ServiceRequestPdu"/> class.
/// </summary>
public ServiceRequestPdu()
{
PduType = (byte)5;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(ServiceRequestPdu left, ServiceRequestPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(ServiceRequestPdu left, ServiceRequestPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._requestingEntityID.GetMarshalledSize(); // this._requestingEntityID
marshalSize += this._servicingEntityID.GetMarshalledSize(); // this._servicingEntityID
marshalSize += 1; // this._serviceTypeRequested
marshalSize += 1; // this._numberOfSupplyTypes
marshalSize += 2; // this._serviceRequestPadding
for (int idx = 0; idx < this._supplies.Count; idx++)
{
SupplyQuantity listElement = (SupplyQuantity)this._supplies[idx];
marshalSize += listElement.GetMarshalledSize();
}
return marshalSize;
}
/// <summary>
/// Gets or sets the Entity that is requesting service
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "requestingEntityID")]
public EntityID RequestingEntityID
{
get
{
return this._requestingEntityID;
}
set
{
this._requestingEntityID = value;
}
}
/// <summary>
/// Gets or sets the Entity that is providing the service
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "servicingEntityID")]
public EntityID ServicingEntityID
{
get
{
return this._servicingEntityID;
}
set
{
this._servicingEntityID = value;
}
}
/// <summary>
/// Gets or sets the type of service requested
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "serviceTypeRequested")]
public byte ServiceTypeRequested
{
get
{
return this._serviceTypeRequested;
}
set
{
this._serviceTypeRequested = value;
}
}
/// <summary>
/// Gets or sets the How many requested
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getnumberOfSupplyTypes method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(byte), ElementName = "numberOfSupplyTypes")]
public byte NumberOfSupplyTypes
{
get
{
return this._numberOfSupplyTypes;
}
set
{
this._numberOfSupplyTypes = value;
}
}
/// <summary>
/// Gets or sets the padding
/// </summary>
[XmlElement(Type = typeof(short), ElementName = "serviceRequestPadding")]
public short ServiceRequestPadding
{
get
{
return this._serviceRequestPadding;
}
set
{
this._serviceRequestPadding = value;
}
}
/// <summary>
/// Gets the supplies
/// </summary>
[XmlElement(ElementName = "suppliesList", Type = typeof(List<SupplyQuantity>))]
public List<SupplyQuantity> Supplies
{
get
{
return this._supplies;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._requestingEntityID.Marshal(dos);
this._servicingEntityID.Marshal(dos);
dos.WriteUnsignedByte((byte)this._serviceTypeRequested);
dos.WriteUnsignedByte((byte)this._supplies.Count);
dos.WriteShort((short)this._serviceRequestPadding);
for (int idx = 0; idx < this._supplies.Count; idx++)
{
SupplyQuantity aSupplyQuantity = (SupplyQuantity)this._supplies[idx];
aSupplyQuantity.Marshal(dos);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._requestingEntityID.Unmarshal(dis);
this._servicingEntityID.Unmarshal(dis);
this._serviceTypeRequested = dis.ReadUnsignedByte();
this._numberOfSupplyTypes = dis.ReadUnsignedByte();
this._serviceRequestPadding = dis.ReadShort();
for (int idx = 0; idx < this.NumberOfSupplyTypes; idx++)
{
SupplyQuantity anX = new SupplyQuantity();
anX.Unmarshal(dis);
this._supplies.Add(anX);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<ServiceRequestPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<requestingEntityID>");
this._requestingEntityID.Reflection(sb);
sb.AppendLine("</requestingEntityID>");
sb.AppendLine("<servicingEntityID>");
this._servicingEntityID.Reflection(sb);
sb.AppendLine("</servicingEntityID>");
sb.AppendLine("<serviceTypeRequested type=\"byte\">" + this._serviceTypeRequested.ToString(CultureInfo.InvariantCulture) + "</serviceTypeRequested>");
sb.AppendLine("<supplies type=\"byte\">" + this._supplies.Count.ToString(CultureInfo.InvariantCulture) + "</supplies>");
sb.AppendLine("<serviceRequestPadding type=\"short\">" + this._serviceRequestPadding.ToString(CultureInfo.InvariantCulture) + "</serviceRequestPadding>");
for (int idx = 0; idx < this._supplies.Count; idx++)
{
sb.AppendLine("<supplies" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"SupplyQuantity\">");
SupplyQuantity aSupplyQuantity = (SupplyQuantity)this._supplies[idx];
aSupplyQuantity.Reflection(sb);
sb.AppendLine("</supplies" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
sb.AppendLine("</ServiceRequestPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as ServiceRequestPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(ServiceRequestPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._requestingEntityID.Equals(obj._requestingEntityID))
{
ivarsEqual = false;
}
if (!this._servicingEntityID.Equals(obj._servicingEntityID))
{
ivarsEqual = false;
}
if (this._serviceTypeRequested != obj._serviceTypeRequested)
{
ivarsEqual = false;
}
if (this._numberOfSupplyTypes != obj._numberOfSupplyTypes)
{
ivarsEqual = false;
}
if (this._serviceRequestPadding != obj._serviceRequestPadding)
{
ivarsEqual = false;
}
if (this._supplies.Count != obj._supplies.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._supplies.Count; idx++)
{
if (!this._supplies[idx].Equals(obj._supplies[idx]))
{
ivarsEqual = false;
}
}
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._requestingEntityID.GetHashCode();
result = GenerateHash(result) ^ this._servicingEntityID.GetHashCode();
result = GenerateHash(result) ^ this._serviceTypeRequested.GetHashCode();
result = GenerateHash(result) ^ this._numberOfSupplyTypes.GetHashCode();
result = GenerateHash(result) ^ this._serviceRequestPadding.GetHashCode();
if (this._supplies.Count > 0)
{
for (int idx = 0; idx < this._supplies.Count; idx++)
{
result = GenerateHash(result) ^ this._supplies[idx].GetHashCode();
}
}
return result;
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.SPOT.Hardware;
namespace Microsoft.SPOT.Net.NetworkInformation
{
public enum NetworkInterfaceType
{
Unknown = 1,
Ethernet = 6,
Wireless80211 = 71,
}
public class NetworkInterface
{
//set update flags...
private const int UPDATE_FLAGS_DNS = 0x1;
private const int UPDATE_FLAGS_DHCP = 0x2;
private const int UPDATE_FLAGS_DHCP_RENEW = 0x4;
private const int UPDATE_FLAGS_DHCP_RELEASE = 0x8;
private const int UPDATE_FLAGS_MAC = 0x10;
private const uint FLAGS_DHCP = 0x1;
private const uint FLAGS_DYNAMIC_DNS = 0x2;
[FieldNoReflection]
private readonly int _interfaceIndex;
private uint _flags;
private uint _ipAddress;
private uint _gatewayAddress;
private uint _subnetMask;
private uint _dnsAddress1;
private uint _dnsAddress2;
private NetworkInterfaceType _networkInterfaceType;
private byte[] _macAddress;
protected NetworkInterface(int interfaceIndex)
{
this._interfaceIndex = interfaceIndex;
_networkInterfaceType = NetworkInterfaceType.Unknown;
}
public static NetworkInterface[] GetAllNetworkInterfaces()
{
int count = GetNetworkInterfaceCount();
NetworkInterface[] ifaces = new NetworkInterface[count];
for (uint i = 0; i < count; i++)
{
ifaces[i] = GetNetworkInterface(i);
}
return ifaces;
}
private static int GetNetworkInterfaceCount()
{
//return Netduino.IP.Interop.NetworkInterface.GetNetworkInterfaceCount();
MethodInfo methodInfo = Type.GetType("Netduino.IP.Interop.NetworkInterface, Netduino.IP.Interop").GetMethod("GetNetworkInterfaceCount", BindingFlags.Public | BindingFlags.Static);
return (int)methodInfo.Invoke(null, new object[] { });
}
private static NetworkInterface GetNetworkInterface(uint interfaceIndex)
{
//return (NetworkInterface)Netduino.IP.Interop.NetworkInterface.GetNetworkInterface(interfaceIndex);
MethodInfo methodInfo = Type.GetType("Netduino.IP.Interop.NetworkInterface, Netduino.IP.Interop").GetMethod("GetNetworkInterface", BindingFlags.Public | BindingFlags.Static);
return (NetworkInterface)methodInfo.Invoke(null, new object[] { interfaceIndex });
}
private void InitializeNetworkInterfaceSettings()
{
throw new NotImplementedException();
}
private void UpdateConfiguration(int updateType)
{
throw new NotImplementedException();
}
private static uint IPAddressFromString(string ipAddress)
{
/* NOTE: this code is copy-and-pasted from System.Net.IPAddress.Parse */
if (ipAddress == null)
throw new ArgumentNullException();
ulong ipAddressValue = 0;
int lastIndex = 0;
int shiftIndex = 0;
ulong mask = 0x00000000000000FF;
ulong octet = 0L;
int length = ipAddress.Length;
for (int i = 0; i < length; ++i)
{
// Parse to '.' or end of IP address
if (ipAddress[i] == '.' || i == length - 1)
// If the IP starts with a '.'
// or a segment is longer than 3 characters or shiftIndex > last bit position throw.
if (i == 0 || i - lastIndex > 3 || shiftIndex > 24)
{
throw new ArgumentException();
}
else
{
i = i == length - 1 ? ++i : i;
// Int32 stoi32 = Netduino.IP.IPv4Layer.ConvertStringToInt32(ipAddress.Substring(lastIndex, i - lastIndex)
Int32 stoi32 = (Int32)(Type.GetType("Netduino.IP.IPv4Layer, Netduino.IP").GetMethod("ConvertStringToInt32", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, new object[] { lastIndex, i - lastIndex }));
octet = (ulong)(stoi32 & 0x00000000000000FF);
ipAddressValue = ipAddressValue + (ulong)((octet << shiftIndex) & mask);
lastIndex = i + 1;
shiftIndex = shiftIndex + 8;
mask = (mask << 8);
}
}
return (uint)ipAddressValue;
}
private string IPAddressToString(uint ipAddress)
{
if(SystemInfo.IsBigEndian)
{
return string.Concat(
((ipAddress >> 24) & 0xFF).ToString(),
".",
((ipAddress >> 16) & 0xFF).ToString(),
".",
((ipAddress >> 8) & 0xFF).ToString(),
".",
((ipAddress >> 0) & 0xFF).ToString()
);
}
else
{
return string.Concat(
((ipAddress >> 0) & 0xFF).ToString(),
".",
((ipAddress >> 8) & 0xFF).ToString(),
".",
((ipAddress >> 16) & 0xFF).ToString(),
".",
((ipAddress >> 24) & 0xFF).ToString()
);
}
}
public void EnableStaticIP(string ipAddress, string subnetMask, string gatewayAddress)
{
/* TODO: DELETE THESE NEXT THERE LINES; THEY ARE ONLY HERE TO SUPRESS A WARNING */
_ipAddress = IPAddressFromString(ipAddress);
_subnetMask = IPAddressFromString(subnetMask);
_gatewayAddress = IPAddressFromString(gatewayAddress);
/* NOTE: see CC3100 driver for details */
throw new NotImplementedException();
//try
//{
// _ipAddress = IPAddressFromString(ipAddress);
// _subnetMask = IPAddressFromString(subnetMask);
// _gatewayAddress = IPAddressFromString(gatewayAddress);
// _flags &= ~FLAGS_DHCP;
// UpdateConfiguration(UPDATE_FLAGS_DHCP);
//}
//finally
//{
// ReloadSettings();
//}
}
public void EnableDhcp()
{
/* NOTE: see CC3100 driver for details */
throw new NotImplementedException();
//try
//{
// _flags |= FLAGS_DHCP;
// UpdateConfiguration(UPDATE_FLAGS_DHCP);
//}
//finally
//{
// ReloadSettings();
//}
}
public void EnableStaticDns(string[] dnsAddresses)
{
if (dnsAddresses == null || dnsAddresses.Length == 0 || dnsAddresses.Length > 2)
{
throw new ArgumentException();
}
uint[] addresses = new uint[2];
int iAddress = 0;
for (int i = 0; i < dnsAddresses.Length; i++)
{
uint address = IPAddressFromString(dnsAddresses[i]);
addresses[iAddress] = address;
if (address != 0)
{
iAddress++;
}
}
try
{
_dnsAddress1 = addresses[0];
_dnsAddress2 = addresses[1];
_flags &= ~FLAGS_DYNAMIC_DNS;
UpdateConfiguration(UPDATE_FLAGS_DNS);
}
finally
{
ReloadSettings();
}
}
public void EnableDynamicDns()
{
try
{
_flags |= FLAGS_DYNAMIC_DNS;
UpdateConfiguration(UPDATE_FLAGS_DNS);
}
finally
{
ReloadSettings();
}
}
public string IPAddress
{
get
{
if (IsDhcpEnabled)
{
var ipv4Layer = Type.GetType("Netduino.IP.SocketsInterface, Netduino.IP").GetField("_ipv4Layer", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
UInt32 ipAddress = (ipv4Layer == null ? 0 : (UInt32)ipv4Layer.GetType().GetField("_ipv4configIPAddress", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(ipv4Layer));
if (SystemInfo.IsBigEndian == false)
{
// reverse bytes
ipAddress = (
(((ipAddress >> 24) & 0xFF) << 0) +
(((ipAddress >> 16) & 0xFF) << 8) +
(((ipAddress >> 8) & 0xFF) << 16) +
(((ipAddress >> 0) & 0xFF) << 24)
);
}
return IPAddressToString(ipAddress);
}
else
{
return IPAddressToString(_ipAddress);
}
}
}
public string GatewayAddress
{
get
{
if (IsDhcpEnabled)
{
var ipv4Layer = Type.GetType("Netduino.IP.SocketsInterface, Netduino.IP").GetField("_ipv4Layer", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
UInt32 gatewayAddress = (ipv4Layer == null ? 0 : (UInt32)ipv4Layer.GetType().GetField("_ipv4configGatewayAddress", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(ipv4Layer));
if (SystemInfo.IsBigEndian == false)
{
// reverse bytes
gatewayAddress = (
(((gatewayAddress >> 24) & 0xFF) << 0) +
(((gatewayAddress >> 16) & 0xFF) << 8) +
(((gatewayAddress >> 8) & 0xFF) << 16) +
(((gatewayAddress >> 0) & 0xFF) << 24)
);
}
return IPAddressToString(gatewayAddress);
}
else
{
return IPAddressToString(_gatewayAddress);
}
}
}
public string SubnetMask
{
get
{
if (IsDhcpEnabled)
{
var ipv4Layer = Type.GetType("Netduino.IP.SocketsInterface, Netduino.IP").GetField("_ipv4Layer", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
UInt32 subnetMask = (ipv4Layer == null ? 0 : (UInt32)ipv4Layer.GetType().GetField("_ipv4configSubnetMask", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(ipv4Layer));
if (SystemInfo.IsBigEndian == false)
{
// reverse bytes
subnetMask = (
(((subnetMask >> 24) & 0xFF) << 0) +
(((subnetMask >> 16) & 0xFF) << 8) +
(((subnetMask >> 8) & 0xFF) << 16) +
(((subnetMask >> 0) & 0xFF) << 24)
);
}
return IPAddressToString(subnetMask);
}
else
{
return IPAddressToString(_subnetMask);
}
}
}
public bool IsDhcpEnabled
{
get { return (_flags & FLAGS_DHCP) != 0; }
}
public bool IsDynamicDnsEnabled
{
get
{
return (_flags & FLAGS_DYNAMIC_DNS) != 0;
}
}
public string[] DnsAddresses
{
get
{
ArrayList list = new ArrayList();
if (IsDynamicDnsEnabled)
{
var ipv4Layer = Type.GetType("Netduino.IP.SocketsInterface, Netduino.IP").GetField("_ipv4Layer", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
UInt32[] dnsAddreses = (ipv4Layer == null ? new UInt32[0] : (UInt32[])ipv4Layer.GetType().GetField("_ipv4configDnsAddresses", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(ipv4Layer));
for (int iDnsAddress = 0; iDnsAddress < dnsAddreses.Length; iDnsAddress++ )
{
if (SystemInfo.IsBigEndian == false)
{
// reverse bytes
dnsAddreses[iDnsAddress] = (
(((dnsAddreses[iDnsAddress] >> 24) & 0xFF) << 0) +
(((dnsAddreses[iDnsAddress] >> 16) & 0xFF) << 8) +
(((dnsAddreses[iDnsAddress] >> 8) & 0xFF) << 16) +
(((dnsAddreses[iDnsAddress] >> 0) & 0xFF) << 24)
);
}
list.Add(IPAddressToString(dnsAddreses[iDnsAddress]));
}
}
else
{
if (_dnsAddress1 != 0)
{
list.Add(IPAddressToString(_dnsAddress1));
}
if (_dnsAddress2 != 0)
{
list.Add(IPAddressToString(_dnsAddress2));
}
}
return (string[])list.ToArray(typeof(string));
}
}
private void ReloadSettings()
{
Thread.Sleep(100);
InitializeNetworkInterfaceSettings();
}
public void ReleaseDhcpLease()
{
try
{
UpdateConfiguration(UPDATE_FLAGS_DHCP_RELEASE);
}
finally
{
ReloadSettings();
}
}
public void RenewDhcpLease()
{
try
{
UpdateConfiguration(UPDATE_FLAGS_DHCP_RELEASE | UPDATE_FLAGS_DHCP_RENEW);
}
finally
{
ReloadSettings();
}
}
public byte[] PhysicalAddress
{
get { return _macAddress; }
set
{
try
{
_macAddress = value;
UpdateConfiguration(UPDATE_FLAGS_MAC);
}
finally
{
ReloadSettings();
}
}
}
public NetworkInterfaceType NetworkInterfaceType
{
get { return _networkInterfaceType; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
// DateTimeFormatInfoScanner
//
// Scan a specified DateTimeFormatInfo to search for data used in DateTime.Parse()
//
// The data includes:
//
// DateWords: such as "de" used in es-ES (Spanish) LongDatePattern.
// Postfix: such as "ta" used in fi-FI after the month name.
//
// This class is shared among mscorlib.dll and sysglobl.dll.
// Use conditional CULTURE_AND_REGIONINFO_BUILDER_ONLY to differentiate between
// methods for mscorlib.dll and sysglobl.dll.
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace System.Globalization
{
#if CORECLR
using StringStringDictionary = Dictionary<string, string>;
using StringList = List<string>;
#else
using StringStringDictionary = LowLevelDictionary<string, string>;
using StringList = LowLevelList<string>;
#endif
//
// from LocaleEx.txt header
//
//; IFORMATFLAGS
//; Parsing/formatting flags.
internal enum FORMATFLAGS
{
None = 0x00000000,
UseGenitiveMonth = 0x00000001,
UseLeapYearMonth = 0x00000002,
UseSpacesInMonthNames = 0x00000004,
UseHebrewParsing = 0x00000008,
UseSpacesInDayNames = 0x00000010, // Has spaces or non-breaking space in the day names.
UseDigitPrefixInTokens = 0x00000020, // Has token starting with numbers.
}
internal enum CalendarId : ushort
{
UNINITIALIZED_VALUE = 0,
GREGORIAN = 1, // Gregorian (localized) calendar
GREGORIAN_US = 2, // Gregorian (U.S.) calendar
JAPAN = 3, // Japanese Emperor Era calendar
/* SSS_WARNINGS_OFF */
TAIWAN = 4, // Taiwan Era calendar /* SSS_WARNINGS_ON */
KOREA = 5, // Korean Tangun Era calendar
HIJRI = 6, // Hijri (Arabic Lunar) calendar
THAI = 7, // Thai calendar
HEBREW = 8, // Hebrew (Lunar) calendar
GREGORIAN_ME_FRENCH = 9, // Gregorian Middle East French calendar
GREGORIAN_ARABIC = 10, // Gregorian Arabic calendar
GREGORIAN_XLIT_ENGLISH = 11, // Gregorian Transliterated English calendar
GREGORIAN_XLIT_FRENCH = 12,
// Note that all calendars after this point are MANAGED ONLY for now.
JULIAN = 13,
JAPANESELUNISOLAR = 14,
CHINESELUNISOLAR = 15,
SAKA = 16, // reserved to match Office but not implemented in our code
LUNAR_ETO_CHN = 17, // reserved to match Office but not implemented in our code
LUNAR_ETO_KOR = 18, // reserved to match Office but not implemented in our code
LUNAR_ETO_ROKUYOU = 19, // reserved to match Office but not implemented in our code
KOREANLUNISOLAR = 20,
TAIWANLUNISOLAR = 21,
PERSIAN = 22,
UMALQURA = 23,
LAST_CALENDAR = 23 // Last calendar ID
}
internal class DateTimeFormatInfoScanner
{
// Special prefix-like flag char in DateWord array.
// Use char in PUA area since we won't be using them in real data.
// The char used to tell a read date word or a month postfix. A month postfix
// is "ta" in the long date pattern like "d. MMMM'ta 'yyyy" for fi-FI.
// In this case, it will be stored as "\xfffeta" in the date word array.
internal const char MonthPostfixChar = '\xe000';
// Add ignorable symbol in a DateWord array.
// hu-HU has:
// shrot date pattern: yyyy. MM. dd.;yyyy-MM-dd;yy-MM-dd
// long date pattern: yyyy. MMMM d.
// Here, "." is the date separator (derived from short date pattern). However,
// "." also appear at the end of long date pattern. In this case, we just
// "." as ignorable symbol so that the DateTime.Parse() state machine will not
// treat the additional date separator at the end of y,m,d pattern as an error
// condition.
internal const char IgnorableSymbolChar = '\xe001';
// Known CJK suffix
internal const String CJKYearSuff = "\u5e74";
internal const String CJKMonthSuff = "\u6708";
internal const String CJKDaySuff = "\u65e5";
internal const String KoreanYearSuff = "\ub144";
internal const String KoreanMonthSuff = "\uc6d4";
internal const String KoreanDaySuff = "\uc77c";
internal const String KoreanHourSuff = "\uc2dc";
internal const String KoreanMinuteSuff = "\ubd84";
internal const String KoreanSecondSuff = "\ucd08";
internal const String CJKHourSuff = "\u6642";
internal const String ChineseHourSuff = "\u65f6";
internal const String CJKMinuteSuff = "\u5206";
internal const String CJKSecondSuff = "\u79d2";
// The collection fo date words & postfix.
internal StringList m_dateWords = new StringList();
// Hashtable for the known words.
private static volatile StringStringDictionary s_knownWords;
static StringStringDictionary KnownWords
{
get
{
if (s_knownWords == null)
{
StringStringDictionary temp = new StringStringDictionary();
// Add known words into the hash table.
// Skip these special symbols.
temp.Add("/", String.Empty);
temp.Add("-", String.Empty);
temp.Add(".", String.Empty);
// Skip known CJK suffixes.
temp.Add(CJKYearSuff, String.Empty);
temp.Add(CJKMonthSuff, String.Empty);
temp.Add(CJKDaySuff, String.Empty);
temp.Add(KoreanYearSuff, String.Empty);
temp.Add(KoreanMonthSuff, String.Empty);
temp.Add(KoreanDaySuff, String.Empty);
temp.Add(KoreanHourSuff, String.Empty);
temp.Add(KoreanMinuteSuff, String.Empty);
temp.Add(KoreanSecondSuff, String.Empty);
temp.Add(CJKHourSuff, String.Empty);
temp.Add(ChineseHourSuff, String.Empty);
temp.Add(CJKMinuteSuff, String.Empty);
temp.Add(CJKSecondSuff, String.Empty);
s_knownWords = temp;
}
return (s_knownWords);
}
}
////////////////////////////////////////////////////////////////////////////
//
// Parameters:
// pattern: The pattern to be scanned.
// currentIndex: the current index to start the scan.
//
// Returns:
// Return the index with the first character that is a letter, which will
// be the start of a date word.
// Note that the index can be pattern.Length if we reach the end of the string.
//
////////////////////////////////////////////////////////////////////////////
internal static int SkipWhiteSpacesAndNonLetter(String pattern, int currentIndex)
{
while (currentIndex < pattern.Length)
{
char ch = pattern[currentIndex];
if (ch == '\\')
{
// Escaped character. Look ahead one character.
currentIndex++;
if (currentIndex < pattern.Length)
{
ch = pattern[currentIndex];
if (ch == '\'')
{
// Skip the leading single quote. We will
// stop at the first letter.
continue;
}
// Fall thru to check if this is a letter.
}
else
{
// End of string
break;
}
}
if (Char.IsLetter(ch) || ch == '\'' || ch == '.')
{
break;
}
// Skip the current char since it is not a letter.
currentIndex++;
}
return (currentIndex);
}
////////////////////////////////////////////////////////////////////////////
//
// A helper to add the found date word or month postfix into ArrayList for date words.
//
// Parameters:
// formatPostfix: What kind of postfix this is.
// Possible values:
// null: This is a regular date word
// "MMMM": month postfix
// word: The date word or postfix to be added.
//
////////////////////////////////////////////////////////////////////////////
internal void AddDateWordOrPostfix(String formatPostfix, String str)
{
if (str.Length > 0)
{
// Some cultures use . like an abbreviation
if (str.Equals("."))
{
AddIgnorableSymbols(".");
return;
}
String words;
if (KnownWords.TryGetValue(str, out words) == false)
{
if (m_dateWords == null)
{
m_dateWords = new StringList();
}
if (formatPostfix == "MMMM")
{
// Add the word into the ArrayList as "\xfffe" + real month postfix.
String temp = MonthPostfixChar + str;
if (!m_dateWords.Contains(temp))
{
m_dateWords.Add(temp);
}
}
else
{
if (!m_dateWords.Contains(str))
{
m_dateWords.Add(str);
}
if (str[str.Length - 1] == '.')
{
// Old version ignore the trialing dot in the date words. Support this as well.
String strWithoutDot = str.Substring(0, str.Length - 1);
if (!m_dateWords.Contains(strWithoutDot))
{
m_dateWords.Add(strWithoutDot);
}
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the pattern from the specified index and add the date word/postfix
// when appropriate.
//
// Parameters:
// pattern: The pattern to be scanned.
// index: The starting index to be scanned.
// formatPostfix: The kind of postfix to be scanned.
// Possible values:
// null: This is a regular date word
// "MMMM": month postfix
//
//
////////////////////////////////////////////////////////////////////////////
internal int AddDateWords(String pattern, int index, String formatPostfix)
{
// Skip any whitespaces so we will start from a letter.
int newIndex = SkipWhiteSpacesAndNonLetter(pattern, index);
if (newIndex != index && formatPostfix != null)
{
// There are whitespaces. This will not be a postfix.
formatPostfix = null;
}
index = newIndex;
// This is the first char added into dateWord.
// Skip all non-letter character. We will add the first letter into DateWord.
StringBuilder dateWord = new StringBuilder();
// We assume that date words should start with a letter.
// Skip anything until we see a letter.
while (index < pattern.Length)
{
char ch = pattern[index];
if (ch == '\'')
{
// We have seen the end of quote. Add the word if we do not see it before,
// and break the while loop.
AddDateWordOrPostfix(formatPostfix, dateWord.ToString());
index++;
break;
}
else if (ch == '\\')
{
//
// Escaped character. Look ahead one character
//
// Skip escaped backslash.
index++;
if (index < pattern.Length)
{
dateWord.Append(pattern[index]);
index++;
}
}
else if (Char.IsWhiteSpace(ch))
{
// Found a whitespace. We have to add the current date word/postfix.
AddDateWordOrPostfix(formatPostfix, dateWord.ToString());
if (formatPostfix != null)
{
// Done with postfix. The rest will be regular date word.
formatPostfix = null;
}
// Reset the dateWord.
dateWord.Length = 0;
index++;
}
else
{
dateWord.Append(ch);
index++;
}
}
return (index);
}
////////////////////////////////////////////////////////////////////////////
//
// A simple helper to find the repeat count for a specified char.
//
////////////////////////////////////////////////////////////////////////////
internal static int ScanRepeatChar(String pattern, char ch, int index, out int count)
{
count = 1;
while (++index < pattern.Length && pattern[index] == ch)
{
count++;
}
// Return the updated position.
return (index);
}
////////////////////////////////////////////////////////////////////////////
//
// Add the text that is a date separator but is treated like ignroable symbol.
// E.g.
// hu-HU has:
// shrot date pattern: yyyy. MM. dd.;yyyy-MM-dd;yy-MM-dd
// long date pattern: yyyy. MMMM d.
// Here, "." is the date separator (derived from short date pattern). However,
// "." also appear at the end of long date pattern. In this case, we just
// "." as ignorable symbol so that the DateTime.Parse() state machine will not
// treat the additional date separator at the end of y,m,d pattern as an error
// condition.
//
////////////////////////////////////////////////////////////////////////////
internal void AddIgnorableSymbols(String text)
{
if (m_dateWords == null)
{
// Create the date word array.
m_dateWords = new StringList();
}
// Add the ignorable symbol into the ArrayList.
String temp = IgnorableSymbolChar + text;
if (!m_dateWords.Contains(temp))
{
m_dateWords.Add(temp);
}
}
//
// Flag used to trace the date patterns (yy/yyyyy/M/MM/MMM/MMM/d/dd) that we have seen.
//
private enum FoundDatePattern
{
None = 0x0000,
FoundYearPatternFlag = 0x0001,
FoundMonthPatternFlag = 0x0002,
FoundDayPatternFlag = 0x0004,
FoundYMDPatternFlag = 0x0007, // FoundYearPatternFlag | FoundMonthPatternFlag | FoundDayPatternFlag;
}
// Check if we have found all of the year/month/day pattern.
private FoundDatePattern _ymdFlags = FoundDatePattern.None;
////////////////////////////////////////////////////////////////////////////
//
// Given a date format pattern, scan for date word or postfix.
//
// A date word should be always put in a single quoted string. And it will
// start from a letter, so whitespace and symbols will be ignored before
// the first letter.
//
// Examples of date word:
// 'de' in es-SP: dddd, dd' de 'MMMM' de 'yyyy
// "\x0443." in bg-BG: dd.M.yyyy '\x0433.'
//
// Example of postfix:
// month postfix:
// "ta" in fi-FI: d. MMMM'ta 'yyyy
// Currently, only month postfix is supported.
//
// Usage:
// Always call this with Framework-style pattern, instead of Windows style pattern.
// Windows style pattern uses '' for single quote, while .NET uses \'
//
////////////////////////////////////////////////////////////////////////////
internal void ScanDateWord(String pattern)
{
// Check if we have found all of the year/month/day pattern.
_ymdFlags = FoundDatePattern.None;
int i = 0;
while (i < pattern.Length)
{
char ch = pattern[i];
int chCount;
switch (ch)
{
case '\'':
// Find a beginning quote. Search until the end quote.
i = AddDateWords(pattern, i + 1, null);
break;
case 'M':
i = ScanRepeatChar(pattern, 'M', i, out chCount);
if (chCount >= 4)
{
if (i < pattern.Length && pattern[i] == '\'')
{
i = AddDateWords(pattern, i + 1, "MMMM");
}
}
_ymdFlags |= FoundDatePattern.FoundMonthPatternFlag;
break;
case 'y':
i = ScanRepeatChar(pattern, 'y', i, out chCount);
_ymdFlags |= FoundDatePattern.FoundYearPatternFlag;
break;
case 'd':
i = ScanRepeatChar(pattern, 'd', i, out chCount);
if (chCount <= 2)
{
// Only count "d" & "dd".
// ddd, dddd are day names. Do not count them.
_ymdFlags |= FoundDatePattern.FoundDayPatternFlag;
}
break;
case '\\':
// Found a escaped char not in a quoted string. Skip the current backslash
// and its next character.
i += 2;
break;
case '.':
if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag)
{
// If we find a dot immediately after the we have seen all of the y, m, d pattern.
// treat it as a ignroable symbol. Check for comments in AddIgnorableSymbols for
// more details.
AddIgnorableSymbols(".");
_ymdFlags = FoundDatePattern.None;
}
i++;
break;
default:
if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag && !Char.IsWhiteSpace(ch))
{
// We are not seeing "." after YMD. Clear the flag.
_ymdFlags = FoundDatePattern.None;
}
// We are not in quote. Skip the current character.
i++;
break;
}
}
}
////////////////////////////////////////////////////////////////////////////
//
// Given a DTFI, get all of the date words from date patterns and time patterns.
//
////////////////////////////////////////////////////////////////////////////
internal String[] GetDateWordsOfDTFI(DateTimeFormatInfo dtfi)
{
// Enumarate all LongDatePatterns, and get the DateWords and scan for month postfix.
String[] datePatterns = dtfi.GetAllDateTimePatterns('D');
int i;
// Scan the long date patterns
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the short date patterns
datePatterns = dtfi.GetAllDateTimePatterns('d');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the YearMonth patterns.
datePatterns = dtfi.GetAllDateTimePatterns('y');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the month/day pattern
ScanDateWord(dtfi.MonthDayPattern);
// Scan the long time patterns.
datePatterns = dtfi.GetAllDateTimePatterns('T');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the short time patterns.
datePatterns = dtfi.GetAllDateTimePatterns('t');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
String[] result = null;
if (m_dateWords != null && m_dateWords.Count > 0)
{
result = new String[m_dateWords.Count];
for (i = 0; i < m_dateWords.Count; i++)
{
result[i] = m_dateWords[i];
}
}
return (result);
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the month names to see if genitive month names are used, and return
// the format flag.
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagGenitiveMonth(String[] monthNames, String[] genitveMonthNames, String[] abbrevMonthNames, String[] genetiveAbbrevMonthNames)
{
// If we have different names in regular and genitive month names, use genitive month flag.
return ((!EqualStringArrays(monthNames, genitveMonthNames) || !EqualStringArrays(abbrevMonthNames, genetiveAbbrevMonthNames))
? FORMATFLAGS.UseGenitiveMonth : 0);
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the month names to see if spaces are used or start with a digit, and return the format flag
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagUseSpaceInMonthNames(String[] monthNames, String[] genitveMonthNames, String[] abbrevMonthNames, String[] genetiveAbbrevMonthNames)
{
FORMATFLAGS formatFlags = 0;
formatFlags |= (ArrayElementsBeginWithDigit(monthNames) ||
ArrayElementsBeginWithDigit(genitveMonthNames) ||
ArrayElementsBeginWithDigit(abbrevMonthNames) ||
ArrayElementsBeginWithDigit(genetiveAbbrevMonthNames)
? FORMATFLAGS.UseDigitPrefixInTokens : 0);
formatFlags |= (ArrayElementsHaveSpace(monthNames) ||
ArrayElementsHaveSpace(genitveMonthNames) ||
ArrayElementsHaveSpace(abbrevMonthNames) ||
ArrayElementsHaveSpace(genetiveAbbrevMonthNames)
? FORMATFLAGS.UseSpacesInMonthNames : 0);
return (formatFlags);
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the day names and set the correct format flag.
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagUseSpaceInDayNames(String[] dayNames, String[] abbrevDayNames)
{
return ((ArrayElementsHaveSpace(dayNames) ||
ArrayElementsHaveSpace(abbrevDayNames))
? FORMATFLAGS.UseSpacesInDayNames : 0);
}
////////////////////////////////////////////////////////////////////////////
//
// Check the calendar to see if it is HebrewCalendar and set the Hebrew format flag if necessary.
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagUseHebrewCalendar(int calID)
{
return (calID == (int)CalendarId.HEBREW ?
FORMATFLAGS.UseHebrewParsing | FORMATFLAGS.UseLeapYearMonth : 0);
}
//-----------------------------------------------------------------------------
// EqualStringArrays
// compares two string arrays and return true if all elements of the first
// array equals to all elmentsof the second array.
// otherwise it returns false.
//-----------------------------------------------------------------------------
private static bool EqualStringArrays(string[] array1, string[] array2)
{
// Shortcut if they're the same array
if (array1 == array2)
{
return true;
}
// This is effectively impossible
if (array1.Length != array2.Length)
{
return false;
}
// Check each string
for (int i = 0; i < array1.Length; i++)
{
if (!array1[i].Equals(array2[i]))
{
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
// ArrayElementsHaveSpace
// It checks all input array elements if any of them has space character
// returns true if found space character in one of the array elements.
// otherwise returns false.
//-----------------------------------------------------------------------------
private static bool ArrayElementsHaveSpace(string[] array)
{
for (int i = 0; i < array.Length; i++)
{
// it is faster to check for space character manually instead of calling IndexOf
// so we don't have to go to native code side.
for (int j = 0; j < array[i].Length; j++)
{
if (Char.IsWhiteSpace(array[i][j]))
{
return true;
}
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////
//
// Check if any element of the array start with a digit.
//
////////////////////////////////////////////////////////////////////////////
private static bool ArrayElementsBeginWithDigit(string[] array)
{
for (int i = 0; i < array.Length; i++)
{
// it is faster to check for space character manually instead of calling IndexOf
// so we don't have to go to native code side.
if (array[i].Length > 0 &&
array[i][0] >= '0' && array[i][0] <= '9')
{
int index = 1;
while (index < array[i].Length && array[i][index] >= '0' && array[i][index] <= '9')
{
// Skip other digits.
index++;
}
if (index == array[i].Length)
{
return (false);
}
if (index == array[i].Length - 1)
{
// Skip known CJK month suffix.
// CJK uses month name like "1\x6708", since \x6708 is a known month suffix,
// we don't need the UseDigitPrefixInTokens since it is slower.
switch (array[i][index])
{
case '\x6708': // CJKMonthSuff
case '\xc6d4': // KoreanMonthSuff
return (false);
}
}
if (index == array[i].Length - 4)
{
// Skip known CJK month suffix.
// Starting with Windows 8, the CJK months for some cultures looks like: "1' \x6708'"
// instead of just "1\x6708"
if (array[i][index] == '\'' && array[i][index + 1] == ' ' &&
array[i][index + 2] == '\x6708' && array[i][index + 3] == '\'')
{
return (false);
}
}
return (true);
}
}
return false;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.VisualStudio.CodeTools
{
using System;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
/// <summary>
/// Maintains "Location"s: an abstraction of a text span, a file name
/// and an associated project. It tracks renames etc. to keep the location up-to-date.
///
/// A location works with just a textspan and a filename. However, if a project name
/// is supplied, the association with a specific project and item in the project is
/// maintained. This way, we can track renames and deletions in the project. Furthermore,
/// we can ensure only to show squiggles in those sourcefiles that were opened by the
/// project that caused the errors in the first place.
///
/// The code is complicated a bit by the <c>dirty</c> flag: this is to update
/// the associated <c>project</c> and <c>itemId</c>, only when requested.
/// They can not be updated immediately since some methods are called during an
/// event (like <c>OnRename</c>) when the associated project is still in an
/// inconsistent state.
/// </summary>
internal class Location : IDisposable
{
#region Private fields
private const uint E_FILENOTFOUND = 0x80070002;
public const uint Nil = VSConstants.VSITEMID_NIL;
private int startLine;
private int startColumn;
private int endLine;
private int endColumn;
private IVsProject project;
private uint itemId;
private string projectName;
private string filePath; // full path name
#endregion
#region Validation
private bool dirty;
/// <summary>
/// Update the associated project and itemId if necessary.
/// </summary>
private void Validate()
{
if (dirty)
{
// get project interface
if (project == null &&
projectName != null &&
projectName.Length > 0)
{
project = Common.GetProjectByName(projectName) as IVsProject;
}
if (project != null)
{
// get projectName from project
IVsHierarchy projHier = project as IVsHierarchy;
string projname = Common.GetProjectName(projHier);
// project.GetMkDocument(VSConstants.VSITEMID_ROOT, out projname);
if (projname != null && projname.Length > 0)
{
projectName = projname;
}
// get itemId
if (itemId == Nil &&
filePath != null && filePath.Length > 0)
{
int found;
uint item;
VSDOCUMENTPRIORITY[] prs = { 0 };
project.IsDocumentInProject(filePath, out found, prs, out item);
if (found != 0)
{
itemId = item;
}
}
// get filePath from project
if (itemId != Nil)
{
string name;
project.GetMkDocument(itemId, out name);
if (name != null && name.Length > 0)
{
filePath = System.IO.Path.GetFullPath(name);
}
}
}
}
}
private bool ValidProject()
{
Validate();
return (project != null && itemId != Nil);
}
#endregion
#region Properties
public string FilePath
{
get
{
Validate();
return filePath;
}
set
{
string s;
if (value == null)
{
s = "";
}
else
{
s = value.Trim();
}
if (s.Length > 0)
{
string fpath = System.IO.Path.GetFullPath(s);
if (String.Compare(filePath, fpath, StringComparison.OrdinalIgnoreCase) != 0)
{
filePath = fpath;
project = null;
itemId = Nil;
dirty = true;
}
}
else
{
filePath = s;
itemId = Nil;
dirty = true;
// leave project as is.
}
}
}
public string ProjectName
{
get
{
Validate();
return projectName;
}
}
public int iStartLine
{
get { return (startLine - 1); }
}
public int iStartIndex
{
get { return (startColumn - 1); }
}
public int StartLine
{
get { return startLine; }
}
public int StartColumn
{
get { return startColumn; }
}
public int EndLine
{
get { return endLine; }
}
public int EndColumn
{
get { return endColumn; }
}
#endregion
#region Constructing
public void Dispose()
{
project = null;
}
public Location()
{
SetFileSpan(null, null, 1, 1, 1, 1);
}
public Location(string projectName, string fname)
{
SetFileSpan(projectName, fname, 1, 1, 1, 1);
}
public Location(string projectName, string fname, int startLine, int startColumn, int endLine, int endColumn)
{
SetFileSpan(projectName, fname, startLine, startColumn, endLine, endColumn);
}
public Location Clone()
{
if (ValidProject())
{
return new Location(project, itemId, ProjectName, FilePath, startLine, startColumn, endLine, endColumn);
}
else
{
return new Location(ProjectName, FilePath, startLine, startColumn, endLine, endColumn);
}
}
public Location(IVsProject project, uint itemId, string pname, string fname, int startLine, int startColumn, int endLine, int endColumn)
{
if (fname == null || fname.Length == 0)
{
fname = "<Unknown>";
}
FilePath = fname;
projectName = pname;
this.project = project;
this.itemId = itemId;
SetSpan(startLine, startColumn, endLine, endColumn);
dirty = true;
}
private void SetFileSpan(string pname, string fname, int startLine, int startColumn, int endLine, int endColumn)
{
if (fname == null)
{
fname = "";
}
FilePath = fname;
projectName = pname;
SetSpan(startLine, startColumn, endLine, endColumn);
}
private void SetSpan(int startLine, int startColumn, int endLine, int endColumn)
{
this.startLine = startLine;
this.startColumn = startColumn;
this.endLine = endLine;
this.endColumn = endColumn;
Normalize();
}
private void Normalize()
{
if (startLine <= 0) startLine = 1;
if (endLine <= 0) endLine = 1;
if (startColumn <= 0) startColumn = 1;
if (endColumn <= 0) endColumn = 1;
if (endLine < startLine)
{
int temp = startLine;
startLine = endLine;
endLine = temp;
}
if (endLine == startLine && endColumn < startColumn)
{
int temp = startColumn;
startColumn = endColumn;
endColumn = temp;
}
}
#endregion
#region Document related methods
/// <summary>
/// Call this method if a buffer has been saved under a different file name.
/// This allows the location to update the itemid of the associated project.
/// </summary>
/// <param name="newFileName">The new file name</param>
public void OnRename(string newFileName)
{
FilePath = newFileName; // this sets the 'dirty' flag.
}
public void OnPotentialRename(IVsHierarchy docHier, uint docItemId, string fname)
{
// if the project+itemid matches, the given filename is an improvement
if (ValidProject())
{
if (project == docHier && docItemId == itemId)
{
OnRename(fname);
}
}
}
/// <summary>
/// Get the window frame associated with this location.
/// </summary>
/// <param name="openIfClosed">Should the frame be opened if it is not yet open?</param>
/// <returns></returns>
public IVsWindowFrame GetWindowFrame(bool openIfClosed)
{
Validate();
IVsWindowFrame windowFrame = null;
IVsUIShellOpenDocument doc = Common.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
if (doc != null)
{
IVsUIHierarchy uihier = project as IVsUIHierarchy; // also works if project==null
Guid textViewGuid = new Guid(LogicalViewID.TextView);
IVsWindowFrame frame;
IVsUIHierarchy uiHierOpen;
uint[] itemIds = { 0 };
int open;
//note: we explicitly only look at a *text* views belonging to the correct project
// we do not want a designer form, or a view opened from another project that might
// have been build using different settings. However, this code also works if the
// project and itemid are unknown, but in that case we just pick the first best text
// view.
int hr = doc.IsDocumentOpen(uihier, itemId, FilePath, ref textViewGuid
, 0, out uiHierOpen, itemIds, out frame, out open);
//success
if ((open != 0) && (frame != null) &&
(project == null || uihier == uiHierOpen) &&
(itemId == Nil || itemId == itemIds[0]))
{
windowFrame = frame;
}
// failure: try to open it.
else if (openIfClosed)
{
if (ValidProject())
{
hr = project.OpenItem(itemId, ref textViewGuid, IntPtr.Zero, out frame);
if (hr == 0 && frame != null)
{
windowFrame = frame;
}
}
else
{
Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp;
uint item;
hr = doc.OpenDocumentViaProject(FilePath, ref textViewGuid, out sp, out uiHierOpen, out item, out frame);
if (hr == 0 && frame != null)
{
project = uiHierOpen as IVsProject;
if (project != null)
{
itemId = item;
}
windowFrame = frame;
}
}
}
}
return windowFrame;
}
/// <summary>
/// Get the text buffer associated with the location.
/// </summary>
/// <param name="openIfClosed">Should we open the buffer if it is not yet open?</param>
/// <returns></returns>
internal IVsTextLines GetTextLines(bool openIfClosed)
{
return GetTextLines(GetWindowFrame(openIfClosed));
}
internal static IVsTextLines GetTextLines(IVsWindowFrame windowFrame)
{
if (windowFrame != null)
{
object docData;
windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData);
return docData as IVsTextLines;
}
else
{
return null;
}
}
internal static IVsTextView GetTextView(IVsWindowFrame windowFrame)
{
if (windowFrame != null)
{
object docView;
windowFrame.Show();
windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out docView);
if (docView != null)
{
IVsTextView textView = docView as IVsTextView;
if (textView == null)
{
IVsCodeWindow codeWindow = docView as IVsCodeWindow;
if (codeWindow != null)
{
codeWindow.GetPrimaryView(out textView);
}
}
return textView;
}
}
return null;
}
/// <summary>
/// Open and activate the window that holds the location and highlight
/// the corresponding span.
/// </summary>
/// <param name="highlight">Highlight the selection.</param>
/// <returns>A <c>HRESULT</c>.</returns>
public int NavigateTo(bool highlight)
{
IVsTextView textView = GetTextView(GetWindowFrame(true));
if (textView != null)
{
TextSpan ts = TextSpan;
textView.SetCaretPos(ts.iStartLine, ts.iStartIndex);
if (highlight)
{
textView.SetSelection(ts.iStartLine, ts.iStartIndex, ts.iEndLine, ts.iEndIndex);
}
textView.EnsureSpanVisible(ts);
return 0;
}
else
{
return unchecked((int)E_FILENOTFOUND); // the system can not find the file specified
}
}
/// <summary>
/// Does the location correspond to a certain document?
/// </summary>
/// <param name="docHier">The associated project (can be null)</param>
/// <param name="docItemId">The item id (can be VSITEMID_NIL)</param>
/// <param name="fpath">The file name</param>
/// <returns><c>true</c> if the location is in this document</returns>
public bool IsSameDocument(IVsHierarchy docHier, uint docItemId, string fpath)
{
Validate();
// compare file names if we have no project info
if (project == null || docHier == null)
{
return IsSameFile(fpath);
}
// otherwise compare the projects
if (project == docHier || (projectName != null && Common.GetProjectName(docHier) == projectName))
{
// compare file names if the itemid's are nil
if (docItemId == Nil || itemId == Nil)
{
return IsSameFile(fpath);
}
// otherwise compare the itemids
else
{
return (itemId == docItemId);
}
}
else
{
return false;
}
}
public bool IsSameHierarchy(IVsHierarchy hier)
{
// Validate();
return (hier != null && GetAssociatedHierarchy() == hier);
}
public IVsHierarchy GetAssociatedHierarchy()
{
Validate();
if (project != null)
{
return project as IVsHierarchy;
}
else
{
// make a good guess..
foreach (IVsHierarchy hier in Common.GetProjects())
{
IVsProject proj = hier as IVsProject;
if (proj != null)
{
int found;
uint item;
VSDOCUMENTPRIORITY[] ps = { 0 };
proj.IsDocumentInProject(filePath, out found, ps, out item);
if (found != 0)
{
return hier;
}
}
}
return null;
}
}
public void GetHierarchy(out object hierarchy, out uint hierarchyItem)
{
if (ValidProject())
{
hierarchy = project;
hierarchyItem = itemId;
}
else
{
hierarchy = null;
hierarchyItem = Nil;
}
}
#endregion
#region Span related methods
/// <summary>
/// Convert to a string that can be used in error messages
/// </summary>
/// <returns>An error message location</returns>
public override string ToString()
{
return (FilePath + "(" + startLine + "," + startColumn + ")");
}
/// <summary>
/// Compare to a file name/
/// </summary>
/// <param name="fname">A (relative) file name</param>
/// <returns><c>true</c> if this location is in the same file</returns>
public bool IsSameFile(string fname)
{
if (fname != null && fname.Length > 0)
{
string fpath = System.IO.Path.GetFullPath(fname);
if (fpath != null && fpath.Length > 0)
{
return (string.Compare(FilePath, fpath, StringComparison.OrdinalIgnoreCase) == 0);
}
}
return false;
}
/// <summary>
/// Do two locations overlap?
/// </summary>
public bool Overlaps(Location span)
{
// do the files match
if (span == null) return false;
if (!IsSameFile(span.FilePath)) return false;
// are they line-overlapping?
if (startLine > span.endLine ||
endLine < span.startLine)
return false;
// are they line/column-overlapping?
if ((startLine == span.endLine && startColumn > span.endColumn) ||
(endLine == span.startLine && endColumn < span.startColumn))
return false;
// they overlap
return true;
}
/// <summary>
/// Get the textspan of a location.
/// </summary>
/// <returns></returns>
public TextSpan TextSpan
{
get
{
TextSpan ts = new TextSpan();
ts.iStartLine = startLine - 1;
ts.iStartIndex = startColumn - 1;
ts.iEndLine = endLine - 1;
ts.iEndIndex = endColumn - 1;
return ts;
}
set
{
SetSpan(value.iStartLine + 1, value.iStartIndex + 1, value.iEndLine + 1, value.iEndIndex + 1);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using LogShark.Plugins.Backgrounder;
using LogShark.Plugins.Backgrounder.Model;
using LogShark.Tests.Plugins.Helpers;
using Xunit;
namespace LogShark.Tests.Plugins.Backgrounder
{
public class BackgrounderEventPersisterTests : InvariantCultureTestsBase
{
private const string TestFileName = "testfile.log";
private readonly TestWriterFactory _writerFactory;
private readonly IBackgrounderEventPersister _persister;
public BackgrounderEventPersisterTests()
{
_writerFactory = new TestWriterFactory();
_persister = new BackgrounderEventPersister(_writerFactory);
}
[Fact]
public void ErrorEvent()
{
_persister.AddErrorEvent(_errorEvent);
_persister.Dispose();
var writer = _writerFactory.GetOneWriterAndVerifyOthersAreEmptyAndDisposed<BackgrounderJobError>("BackgrounderJobErrors", 4);
writer.ReceivedObjects.Count.Should().Be(1);
writer.ReceivedObjects[0].Should().BeEquivalentTo(_errorEvent);
}
[Fact]
public void SimpleEventsAndPersistingRightAway()
{
var startEvent1 = GetStartEvent(1);
var endEvent1 = GetEndEvent(1);
_persister.AddStartEvent(startEvent1);
_persister.AddEndEvent(endEvent1); // This is complete event and should be persisted right away
var startEvent2 = GetStartEvent(2);
startEvent2.StartFile = "some_other_file.log";
var endEvent2 = GetEndEvent(2);
_persister.AddStartEvent(startEvent2);
_persister.AddEndEvent(endEvent2); // This is complete, but should not be merged right away because file paths are different
var startEvent3 = GetStartEvent(3);
_persister.AddStartEvent(startEvent3); // This is incomplete event, so it will be persisted only after drain
var jobWriter = _writerFactory.GetOneWriterAndVerifyOthersAreEmpty<BackgrounderJob>("BackgrounderJobs", 4);
jobWriter.ReceivedObjects.Count.Should().Be(1);
var fullEvent1 = (BackgrounderJob) jobWriter.ReceivedObjects[0];
var combinedEvent1 = CopyValues(startEvent1, endEvent1);
fullEvent1.Should().BeEquivalentTo(combinedEvent1);
_persister.DrainEvents();
jobWriter.ReceivedObjects.Count.Should().Be(3);
var fullEvent2 = (BackgrounderJob) jobWriter.ReceivedObjects[1];
var combinedEvent2 = CopyValues(startEvent2, endEvent2);
fullEvent2.Should().BeEquivalentTo(combinedEvent2);
var partialEvent = (BackgrounderJob) jobWriter.ReceivedObjects[2];
partialEvent.Should().BeEquivalentTo(startEvent3);
}
[Fact]
public void WatermarkTest()
{
var startEvent1 = GetStartEvent(1);
var startEvent2 = GetStartEvent(2);
startEvent2.StartTime = startEvent2.StartTime.Add(TimeSpan.FromSeconds(10));
_persister.AddStartEvent(startEvent1);
_persister.AddStartEvent(startEvent2);
_persister.DrainEvents();
var jobWriter = _writerFactory.GetOneWriterAndVerifyOthersAreEmpty<BackgrounderJob>("BackgrounderJobs", 4);
jobWriter.ReceivedObjects.Count.Should().Be(2);
startEvent1.MarkAsTimedOut();
jobWriter.ReceivedObjects[0].Should().BeEquivalentTo(startEvent1);
startEvent2.MarkAsUnknown();
jobWriter.ReceivedObjects[1].Should().BeEquivalentTo(startEvent2);
}
[Fact]
public void ExtractDetails()
{
var startEvent1 = GetStartEvent(1, "refresh_extracts"); // Extract refresh with details
startEvent1.Args = "[TestyTest, blah, Datasource]";
var startEvent2 = GetStartEvent(2, "refresh_extracts"); // Extract refresh without details
var startEvent3 = GetStartEvent(3, "increment_extracts"); // Incremental refresh
var startEvent4 = GetStartEvent(4, "some_other_job"); // Some other job type
var endEvent1 = GetEndEvent(1);
var endEvent2 = GetEndEvent(2);
var endEvent3 = GetEndEvent(3);
var endEvent4 = GetEndEvent(4);
var detail1 = GetExtractJobDetail(1);
var detail2 = new BackgrounderExtractJobDetail()
{
BackgrounderJobId = 2,
ResourceType = "testArgument"
};
var detail3 = GetExtractJobDetail(3);
var detail4 = GetExtractJobDetail(4);
_persister.AddStartEvent(startEvent1);
_persister.AddStartEvent(startEvent2);
_persister.AddStartEvent(startEvent3);
_persister.AddStartEvent(startEvent4);
_persister.AddExtractJobDetails(detail1);
_persister.AddExtractJobDetails(detail3);
_persister.AddExtractJobDetails(detail4);
_persister.AddEndEvent(endEvent1);
_persister.AddEndEvent(endEvent2);
_persister.AddEndEvent(endEvent3);
_persister.AddEndEvent(endEvent4);
var jobWriter = _writerFactory.GetWriterByName<BackgrounderJob>("BackgrounderJobs");
jobWriter.ReceivedObjects.Count.Should().Be(4);
var extractJobDetailWriter = _writerFactory.GetWriterByName<BackgrounderExtractJobDetail>("BackgrounderExtractJobDetails");
extractJobDetailWriter.ReceivedObjects.Count.Should().Be(3);
var actualDetail1 = extractJobDetailWriter.ReceivedObjects[0] as BackgrounderExtractJobDetail;
var actualDetail2 = extractJobDetailWriter.ReceivedObjects[1] as BackgrounderExtractJobDetail;
var actualDetail3 = extractJobDetailWriter.ReceivedObjects[2] as BackgrounderExtractJobDetail;
detail1.ResourceName = "TestyTest";
detail1.ResourceType = "Datasource";
actualDetail1.Should().BeEquivalentTo(detail1);
actualDetail2.Should().BeEquivalentTo(detail2);
actualDetail3.Should().BeEquivalentTo(detail3);
}
[Fact]
public void SubscriptionDetails()
{
var startEvent1 = GetStartEvent(1, "single_subscription_notify"); // Subscription job with details
var startEvent2 = GetStartEvent(2, "single_subscription_notify"); // Subscription job without details
var startEvent3 = GetStartEvent(3, "some_other_job_type"); // Non-subscription job with details
var endEvent1 = GetEndEvent(1);
var endEvent2 = GetEndEvent(2);
var endEvent3 = GetEndEvent(3);
var detail1 = GetSubscriptionDetails(1);
var detail3 = GetSubscriptionDetails(3);
_persister.AddStartEvent(startEvent1);
_persister.AddStartEvent(startEvent2);
_persister.AddStartEvent(startEvent3);
foreach (var detail in detail1)
{
_persister.AddSubscriptionJobDetails(detail);
}
foreach (var detail in detail3)
{
_persister.AddSubscriptionJobDetails(detail);
}
_persister.AddEndEvent(endEvent1);
_persister.AddEndEvent(endEvent2);
_persister.AddEndEvent(endEvent3);
var jobWriter = _writerFactory.GetWriterByName<BackgrounderJob>("BackgrounderJobs");
jobWriter.ReceivedObjects.Count.Should().Be(3);
var subscriptionJobDetailWriter = _writerFactory.GetWriterByName<BackgrounderSubscriptionJobDetail>("BackgrounderSubscriptionJobDetails");
subscriptionJobDetailWriter.ReceivedObjects.Count.Should().Be(1);
var actualDetail1 = subscriptionJobDetailWriter.ReceivedObjects[0] as BackgrounderSubscriptionJobDetail;
var twoCombined = CopyValues(detail1[0], detail1[1]);
var expectedDetail = CopyValues(twoCombined, detail1[2]);
actualDetail1.Should().BeEquivalentTo(expectedDetail);
}
private static BackgrounderJob GetStartEvent(long jobId, string jobType = "purge_expired_wgsessions")
{
return new BackgrounderJob
{
Args = "testArgument",
BackgrounderId = 1,
JobId = jobId,
JobType = jobType,
Priority = 0,
StartFile = TestFileName,
StartLine = 123,
StartTime = new DateTime(2018, 8, 8, 11, 17, 13, 491),
Timeout = 9000,
WorkerId = "worker0",
};
}
private static BackgrounderJob GetEndEvent(long jobId)
{
return new BackgrounderJob
{
EndFile = TestFileName,
EndLine = 130,
EndTime = new DateTime(2018, 8, 8, 11, 17, 13, 402),
ErrorMessage = null,
JobId = jobId,
Notes = "test notes",
RunTime = 3,
Success = true,
TotalTime = 5,
};
}
private static BackgrounderExtractJobDetail GetExtractJobDetail(long jobId)
{
return new BackgrounderExtractJobDetail
{
BackgrounderJobId = jobId,
ExtractGuid = "5EEC2CCA-6F82-4EFF-9DBC-FDB471269B06",
ExtractId = "bd5c5cc4-1c35-443f-bac7-3a4acac54a4b",
ExtractSize = 1048641536L,
ExtractUrl = "MDAPP2018_1_2",
ResourceName = null,
ResourceType = null,
TotalSize = 1048713414L,
TwbSize = 71878L,
VizqlSessionId = "D7A2D1F664E5466B87C4637ABBC31D63",
};
}
private static List<BackgrounderSubscriptionJobDetail> GetSubscriptionDetails(long jobId)
{
return new List<BackgrounderSubscriptionJobDetail>
{
new BackgrounderSubscriptionJobDetail
{
BackgrounderJobId = jobId,
RecipientEmail = null,
SenderEmail = null,
SmtpServer = null,
SubscriptionName = null,
VizqlSessionId = "FA88A9BC626A40A29228ECE09F04A76B",
},
new BackgrounderSubscriptionJobDetail
{
BackgrounderJobId = jobId,
RecipientEmail = null,
SenderEmail = null,
SmtpServer = null,
SubscriptionName = "Weekly Report",
VizqlSessionId = null,
},
new BackgrounderSubscriptionJobDetail
{
BackgrounderJobId = jobId,
RecipientEmail = "[email protected]",
SenderEmail = "[email protected]",
SmtpServer = "mail.test.com",
SubscriptionName = null,
VizqlSessionId = null,
}
};
}
private static T CopyValues<T>(T target, T source)
{
var type = typeof(T);
var properties = type.GetProperties().Where(prop => prop.CanRead && prop.CanWrite);
foreach (var prop in properties)
{
var value = prop.GetValue(source, null);
if (value != null)
prop.SetValue(target, value, null);
}
return target;
}
private readonly BackgrounderJobError _errorEvent = new BackgrounderJobError
{
BackgrounderJobId = 1369448,
Class = "com.tableausoftware.core.configuration.ConfigurationSupportService",
File = TestFileName,
Line = 123,
Message = "unable to convert site id string: to integer for extract refresh time out overrides list skipping this site, will continue with the remainder.",
Severity = "ERROR",
Site = "Default",
Thread = "pool-4-thread-1",
Timestamp = new DateTime(2018, 7, 12, 23, 37, 17, 201)
};
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
namespace Fungus
{
/// <summary>
/// Writes text in a dialog box.
/// </summary>
[CommandInfo("Narrative",
"Say",
"Writes text in a dialog box.")]
[AddComponentMenu("")]
public class Say : Command, ILocalizable
{
// Removed this tooltip as users's reported it obscures the text box
[TextArea(5,10)]
[SerializeField] protected string storyText = "";
[Tooltip("Notes about this story text for other authors, localization, etc.")]
[SerializeField] protected string description = "";
[Tooltip("Character that is speaking")]
[SerializeField] protected Character character;
[Tooltip("Portrait that represents speaking character")]
[SerializeField] protected Sprite portrait;
[Tooltip("Voiceover audio to play when writing the text")]
[SerializeField] protected AudioClip voiceOverClip;
[Tooltip("Always show this Say text when the command is executed multiple times")]
[SerializeField] protected bool showAlways = true;
[Tooltip("Number of times to show this Say text when the command is executed multiple times")]
[SerializeField] protected int showCount = 1;
[Tooltip("Type this text in the previous dialog box.")]
[SerializeField] protected bool extendPrevious = false;
[Tooltip("Fade out the dialog box when writing has finished and not waiting for input.")]
[SerializeField] protected bool fadeWhenDone = true;
[Tooltip("Wait for player to click before continuing.")]
[SerializeField] protected bool waitForClick = true;
[Tooltip("Stop playing voiceover when text finishes writing.")]
[SerializeField] protected bool stopVoiceover = true;
[Tooltip("Wait for the Voice Over to complete before continuing")]
[SerializeField] protected bool waitForVO = false;
//add wait for vo that overrides stopvo
[Tooltip("Sets the active Say dialog with a reference to a Say Dialog object in the scene. All story text will now display using this Say Dialog.")]
[SerializeField] protected SayDialog setSayDialog;
protected int executionCount;
#region Public members
/// <summary>
/// Character that is speaking.
/// </summary>
public virtual Character _Character { get { return character; } }
/// <summary>
/// Portrait that represents speaking character.
/// </summary>
public virtual Sprite Portrait { get { return portrait; } set { portrait = value; } }
/// <summary>
/// Type this text in the previous dialog box.
/// </summary>
public virtual bool ExtendPrevious { get { return extendPrevious; } }
public override void OnEnter()
{
if (!showAlways && executionCount >= showCount)
{
Continue();
return;
}
executionCount++;
// Override the active say dialog if needed
if (character != null && character.SetSayDialog != null)
{
SayDialog.ActiveSayDialog = character.SetSayDialog;
}
if (setSayDialog != null)
{
SayDialog.ActiveSayDialog = setSayDialog;
}
var sayDialog = SayDialog.GetSayDialog();
if (sayDialog == null)
{
Continue();
return;
}
var flowchart = GetFlowchart();
sayDialog.SetActive(true);
sayDialog.SetCharacter(character);
sayDialog.SetCharacterImage(portrait);
string displayText = storyText;
var activeCustomTags = CustomTag.activeCustomTags;
for (int i = 0; i < activeCustomTags.Count; i++)
{
var ct = activeCustomTags[i];
displayText = displayText.Replace(ct.TagStartSymbol, ct.ReplaceTagStartWith);
if (ct.TagEndSymbol != "" && ct.ReplaceTagEndWith != "")
{
displayText = displayText.Replace(ct.TagEndSymbol, ct.ReplaceTagEndWith);
}
}
string subbedText = flowchart.SubstituteVariables(displayText);
sayDialog.Say(subbedText, !extendPrevious, waitForClick, fadeWhenDone, stopVoiceover, waitForVO, voiceOverClip, delegate {
Continue();
});
}
public override string GetSummary()
{
string namePrefix = "";
if (character != null)
{
namePrefix = character.NameText + ": ";
}
if (extendPrevious)
{
namePrefix = "EXTEND" + ": ";
}
return namePrefix + "\"" + storyText + "\"";
}
public override Color GetButtonColor()
{
return new Color32(184, 210, 235, 255);
}
public override void OnReset()
{
executionCount = 0;
}
public override void OnStopExecuting()
{
var sayDialog = SayDialog.GetSayDialog();
if (sayDialog == null)
{
return;
}
sayDialog.Stop();
}
#endregion
#region ILocalizable implementation
public virtual string GetStandardText()
{
return storyText;
}
public virtual void SetStandardText(string standardText)
{
storyText = standardText;
}
public virtual string GetDescription()
{
return description;
}
public virtual string GetStringId()
{
// String id for Say commands is SAY.<Localization Id>.<Command id>.[Character Name]
string stringId = "SAY." + GetFlowchartLocalizationId() + "." + itemId + ".";
if (character != null)
{
stringId += character.NameText;
}
return stringId;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Http.Features;
#nullable enable
namespace Microsoft.AspNetCore.Connections
{
internal partial class TransportMultiplexedConnection : IFeatureCollection,
IConnectionIdFeature,
IConnectionItemsFeature,
IMemoryPoolFeature,
IConnectionLifetimeFeature
{
// Implemented features
internal protected IConnectionIdFeature? _currentIConnectionIdFeature;
internal protected IConnectionItemsFeature? _currentIConnectionItemsFeature;
internal protected IMemoryPoolFeature? _currentIMemoryPoolFeature;
internal protected IConnectionLifetimeFeature? _currentIConnectionLifetimeFeature;
// Other reserved feature slots
internal protected IConnectionTransportFeature? _currentIConnectionTransportFeature;
internal protected IProtocolErrorCodeFeature? _currentIProtocolErrorCodeFeature;
internal protected ITlsConnectionFeature? _currentITlsConnectionFeature;
private int _featureRevision;
private List<KeyValuePair<Type, object>>? MaybeExtra;
private void FastReset()
{
_currentIConnectionIdFeature = this;
_currentIConnectionItemsFeature = this;
_currentIMemoryPoolFeature = this;
_currentIConnectionLifetimeFeature = this;
_currentIConnectionTransportFeature = null;
_currentIProtocolErrorCodeFeature = null;
_currentITlsConnectionFeature = null;
}
// Internal for testing
internal void ResetFeatureCollection()
{
FastReset();
MaybeExtra?.Clear();
_featureRevision++;
}
private object? ExtraFeatureGet(Type key)
{
if (MaybeExtra == null)
{
return null;
}
for (var i = 0; i < MaybeExtra.Count; i++)
{
var kv = MaybeExtra[i];
if (kv.Key == key)
{
return kv.Value;
}
}
return null;
}
private void ExtraFeatureSet(Type key, object? value)
{
if (value == null)
{
if (MaybeExtra == null)
{
return;
}
for (var i = 0; i < MaybeExtra.Count; i++)
{
if (MaybeExtra[i].Key == key)
{
MaybeExtra.RemoveAt(i);
return;
}
}
}
else
{
if (MaybeExtra == null)
{
MaybeExtra = new List<KeyValuePair<Type, object>>(2);
}
for (var i = 0; i < MaybeExtra.Count; i++)
{
if (MaybeExtra[i].Key == key)
{
MaybeExtra[i] = new KeyValuePair<Type, object>(key, value);
return;
}
}
MaybeExtra.Add(new KeyValuePair<Type, object>(key, value));
}
}
bool IFeatureCollection.IsReadOnly => false;
int IFeatureCollection.Revision => _featureRevision;
object? IFeatureCollection.this[Type key]
{
get
{
object? feature = null;
if (key == typeof(IConnectionIdFeature))
{
feature = _currentIConnectionIdFeature;
}
else if (key == typeof(IConnectionTransportFeature))
{
feature = _currentIConnectionTransportFeature;
}
else if (key == typeof(IConnectionItemsFeature))
{
feature = _currentIConnectionItemsFeature;
}
else if (key == typeof(IMemoryPoolFeature))
{
feature = _currentIMemoryPoolFeature;
}
else if (key == typeof(IConnectionLifetimeFeature))
{
feature = _currentIConnectionLifetimeFeature;
}
else if (key == typeof(IProtocolErrorCodeFeature))
{
feature = _currentIProtocolErrorCodeFeature;
}
else if (key == typeof(ITlsConnectionFeature))
{
feature = _currentITlsConnectionFeature;
}
else if (MaybeExtra != null)
{
feature = ExtraFeatureGet(key);
}
return feature;
}
set
{
_featureRevision++;
if (key == typeof(IConnectionIdFeature))
{
_currentIConnectionIdFeature = (IConnectionIdFeature?)value;
}
else if (key == typeof(IConnectionTransportFeature))
{
_currentIConnectionTransportFeature = (IConnectionTransportFeature?)value;
}
else if (key == typeof(IConnectionItemsFeature))
{
_currentIConnectionItemsFeature = (IConnectionItemsFeature?)value;
}
else if (key == typeof(IMemoryPoolFeature))
{
_currentIMemoryPoolFeature = (IMemoryPoolFeature?)value;
}
else if (key == typeof(IConnectionLifetimeFeature))
{
_currentIConnectionLifetimeFeature = (IConnectionLifetimeFeature?)value;
}
else if (key == typeof(IProtocolErrorCodeFeature))
{
_currentIProtocolErrorCodeFeature = (IProtocolErrorCodeFeature?)value;
}
else if (key == typeof(ITlsConnectionFeature))
{
_currentITlsConnectionFeature = (ITlsConnectionFeature?)value;
}
else
{
ExtraFeatureSet(key, value);
}
}
}
TFeature? IFeatureCollection.Get<TFeature>() where TFeature : default
{
// Using Unsafe.As for the cast due to https://github.com/dotnet/runtime/issues/49614
// The type of TFeature is confirmed by the typeof() check and the As cast only accepts
// that type; however the Jit does not eliminate a regular cast in a shared generic.
TFeature? feature = default;
if (typeof(TFeature) == typeof(IConnectionIdFeature))
{
feature = Unsafe.As<IConnectionIdFeature?, TFeature?>(ref _currentIConnectionIdFeature);
}
else if (typeof(TFeature) == typeof(IConnectionTransportFeature))
{
feature = Unsafe.As<IConnectionTransportFeature?, TFeature?>(ref _currentIConnectionTransportFeature);
}
else if (typeof(TFeature) == typeof(IConnectionItemsFeature))
{
feature = Unsafe.As<IConnectionItemsFeature?, TFeature?>(ref _currentIConnectionItemsFeature);
}
else if (typeof(TFeature) == typeof(IMemoryPoolFeature))
{
feature = Unsafe.As<IMemoryPoolFeature?, TFeature?>(ref _currentIMemoryPoolFeature);
}
else if (typeof(TFeature) == typeof(IConnectionLifetimeFeature))
{
feature = Unsafe.As<IConnectionLifetimeFeature?, TFeature?>(ref _currentIConnectionLifetimeFeature);
}
else if (typeof(TFeature) == typeof(IProtocolErrorCodeFeature))
{
feature = Unsafe.As<IProtocolErrorCodeFeature?, TFeature?>(ref _currentIProtocolErrorCodeFeature);
}
else if (typeof(TFeature) == typeof(ITlsConnectionFeature))
{
feature = Unsafe.As<ITlsConnectionFeature?, TFeature?>(ref _currentITlsConnectionFeature);
}
else if (MaybeExtra != null)
{
feature = (TFeature?)(ExtraFeatureGet(typeof(TFeature)));
}
return feature;
}
void IFeatureCollection.Set<TFeature>(TFeature? feature) where TFeature : default
{
// Using Unsafe.As for the cast due to https://github.com/dotnet/runtime/issues/49614
// The type of TFeature is confirmed by the typeof() check and the As cast only accepts
// that type; however the Jit does not eliminate a regular cast in a shared generic.
_featureRevision++;
if (typeof(TFeature) == typeof(IConnectionIdFeature))
{
_currentIConnectionIdFeature = Unsafe.As<TFeature?, IConnectionIdFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IConnectionTransportFeature))
{
_currentIConnectionTransportFeature = Unsafe.As<TFeature?, IConnectionTransportFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IConnectionItemsFeature))
{
_currentIConnectionItemsFeature = Unsafe.As<TFeature?, IConnectionItemsFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IMemoryPoolFeature))
{
_currentIMemoryPoolFeature = Unsafe.As<TFeature?, IMemoryPoolFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IConnectionLifetimeFeature))
{
_currentIConnectionLifetimeFeature = Unsafe.As<TFeature?, IConnectionLifetimeFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IProtocolErrorCodeFeature))
{
_currentIProtocolErrorCodeFeature = Unsafe.As<TFeature?, IProtocolErrorCodeFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(ITlsConnectionFeature))
{
_currentITlsConnectionFeature = Unsafe.As<TFeature?, ITlsConnectionFeature?>(ref feature);
}
else
{
ExtraFeatureSet(typeof(TFeature), feature);
}
}
private IEnumerable<KeyValuePair<Type, object>> FastEnumerable()
{
if (_currentIConnectionIdFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IConnectionIdFeature), _currentIConnectionIdFeature);
}
if (_currentIConnectionTransportFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IConnectionTransportFeature), _currentIConnectionTransportFeature);
}
if (_currentIConnectionItemsFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IConnectionItemsFeature), _currentIConnectionItemsFeature);
}
if (_currentIMemoryPoolFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IMemoryPoolFeature), _currentIMemoryPoolFeature);
}
if (_currentIConnectionLifetimeFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IConnectionLifetimeFeature), _currentIConnectionLifetimeFeature);
}
if (_currentIProtocolErrorCodeFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IProtocolErrorCodeFeature), _currentIProtocolErrorCodeFeature);
}
if (_currentITlsConnectionFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(ITlsConnectionFeature), _currentITlsConnectionFeature);
}
if (MaybeExtra != null)
{
foreach (var item in MaybeExtra)
{
yield return item;
}
}
}
IEnumerator<KeyValuePair<Type, object>> IEnumerable<KeyValuePair<Type, object>>.GetEnumerator() => FastEnumerable().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => FastEnumerable().GetEnumerator();
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.UnitTests;
using Moq;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class TextBoxTests
{
[Fact]
public void Opening_Context_Menu_Does_not_Lose_Selection()
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234",
ContextMenu = new TestContextMenu()
};
var target2 = new TextBox
{
Template = CreateTemplate(),
Text = "5678"
};
var sp = new StackPanel();
sp.Children.Add(target1);
sp.Children.Add(target2);
target1.ApplyTemplate();
target2.ApplyTemplate();
var root = new TestRoot() { Child = sp };
target1.SelectionStart = 0;
target1.SelectionEnd = 3;
target1.Focus();
Assert.False(target2.IsFocused);
Assert.True(target1.IsFocused);
target2.Focus();
Assert.Equal("123", target1.SelectedText);
}
}
[Fact]
public void Opening_Context_Flyout_Does_not_Lose_Selection()
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234",
ContextFlyout = new MenuFlyout
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Item 1" },
new MenuItem {Header = "Item 2" },
new MenuItem {Header = "Item 3" }
}
}
};
target1.ApplyTemplate();
var root = new TestRoot() { Child = target1 };
target1.SelectionStart = 0;
target1.SelectionEnd = 3;
target1.Focus();
Assert.True(target1.IsFocused);
target1.ContextFlyout.ShowAt(target1);
Assert.Equal("123", target1.SelectedText);
}
}
[Fact]
public void DefaultBindingMode_Should_Be_TwoWay()
{
Assert.Equal(
BindingMode.TwoWay,
TextBox.TextProperty.GetMetadata(typeof(TextBox)).DefaultBindingMode);
}
[Fact]
public void CaretIndex_Can_Moved_To_Position_After_The_End_Of_Text_With_Arrow_Key()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
target.CaretIndex = 3;
RaiseKeyEvent(target, Key.Right, 0);
Assert.Equal(4, target.CaretIndex);
}
}
[Fact]
public void Press_Ctrl_A_Select_All_Text()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
RaiseKeyEvent(target, Key.A, KeyModifiers.Control);
Assert.Equal(0, target.SelectionStart);
Assert.Equal(4, target.SelectionEnd);
}
}
[Fact]
public void Press_Ctrl_A_Select_All_Null_Text()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate()
};
RaiseKeyEvent(target, Key.A, KeyModifiers.Control);
Assert.Equal(0, target.SelectionStart);
Assert.Equal(0, target.SelectionEnd);
}
}
[Fact]
public void Press_Ctrl_Z_Will_Not_Modify_Text()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
RaiseKeyEvent(target, Key.Z, KeyModifiers.Control);
Assert.Equal("1234", target.Text);
}
}
[Fact]
public void Typing_Beginning_With_0_Should_Not_Modify_Text_When_Bound_To_Int()
{
using (UnitTestApplication.Start(Services))
{
var source = new Class1();
var target = new TextBox
{
DataContext = source,
Template = CreateTemplate(),
};
target.ApplyTemplate();
target.Bind(TextBox.TextProperty, new Binding(nameof(Class1.Foo), BindingMode.TwoWay));
Assert.Equal("0", target.Text);
target.CaretIndex = 1;
target.RaiseEvent(new TextInputEventArgs
{
RoutedEvent = InputElement.TextInputEvent,
Text = "2",
});
Assert.Equal("02", target.Text);
}
}
[Fact]
public void Control_Backspace_Should_Remove_The_Word_Before_The_Caret_If_There_Is_No_Selection()
{
using (UnitTestApplication.Start(Services))
{
TextBox textBox = new TextBox
{
Text = "First Second Third Fourth",
CaretIndex = 5
};
// (First| Second Third Fourth)
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal(" Second Third Fourth", textBox.Text);
// ( Second |Third Fourth)
textBox.CaretIndex = 8;
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal(" Third Fourth", textBox.Text);
// ( Thi|rd Fourth)
textBox.CaretIndex = 4;
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal(" rd Fourth", textBox.Text);
// ( rd F[ou]rth)
textBox.SelectionStart = 5;
textBox.SelectionEnd = 7;
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal(" rd Frth", textBox.Text);
// ( |rd Frth)
textBox.CaretIndex = 1;
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal("rd Frth", textBox.Text);
}
}
[Fact]
public void Control_Delete_Should_Remove_The_Word_After_The_Caret_If_There_Is_No_Selection()
{
using (UnitTestApplication.Start(Services))
{
TextBox textBox = new TextBox
{
Text = "First Second Third Fourth",
CaretIndex = 19
};
// (First Second Third |Fourth)
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("First Second Third ", textBox.Text);
// (First Second |Third )
textBox.CaretIndex = 13;
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("First Second ", textBox.Text);
// (First Sec|ond )
textBox.CaretIndex = 9;
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("First Sec", textBox.Text);
// (Fi[rs]t Sec )
textBox.SelectionStart = 2;
textBox.SelectionEnd = 4;
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("Fit Sec", textBox.Text);
// (Fit Sec| )
textBox.Text += " ";
textBox.CaretIndex = 7;
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("Fit Sec", textBox.Text);
}
}
[Fact]
public void Setting_SelectionStart_To_SelectionEnd_Sets_CaretPosition_To_SelectionStart()
{
using (UnitTestApplication.Start(Services))
{
var textBox = new TextBox
{
Text = "0123456789"
};
textBox.SelectionStart = 2;
textBox.SelectionEnd = 2;
Assert.Equal(2, textBox.CaretIndex);
}
}
[Fact]
public void Setting_Text_Updates_CaretPosition()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Text = "Initial Text",
CaretIndex = 11
};
var invoked = false;
target.GetObservable(TextBox.TextProperty).Skip(1).Subscribe(_ =>
{
// Caret index should be set before Text changed notification, as we don't want
// to notify with an invalid CaretIndex.
Assert.Equal(7, target.CaretIndex);
invoked = true;
});
target.Text = "Changed";
Assert.True(invoked);
}
}
[Fact]
public void Press_Enter_Does_Not_Accept_Return()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
AcceptsReturn = false,
Text = "1234"
};
RaiseKeyEvent(target, Key.Enter, 0);
Assert.Equal("1234", target.Text);
}
}
[Fact]
public void Press_Enter_Add_Default_Newline()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
AcceptsReturn = true
};
RaiseKeyEvent(target, Key.Enter, 0);
Assert.Equal(Environment.NewLine, target.Text);
}
}
[Fact]
public void Press_Enter_Add_Custom_Newline()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
AcceptsReturn = true,
NewLine = "Test"
};
RaiseKeyEvent(target, Key.Enter, 0);
Assert.Equal("Test", target.Text);
}
}
[Theory]
[InlineData(new object[] { false, TextWrapping.NoWrap, ScrollBarVisibility.Hidden })]
[InlineData(new object[] { false, TextWrapping.Wrap, ScrollBarVisibility.Disabled })]
[InlineData(new object[] { true, TextWrapping.NoWrap, ScrollBarVisibility.Auto })]
[InlineData(new object[] { true, TextWrapping.Wrap, ScrollBarVisibility.Disabled })]
public void Has_Correct_Horizontal_ScrollBar_Visibility(
bool acceptsReturn,
TextWrapping wrapping,
ScrollBarVisibility expected)
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
AcceptsReturn = acceptsReturn,
TextWrapping = wrapping,
};
Assert.Equal(expected, ScrollViewer.GetHorizontalScrollBarVisibility(target));
}
}
[Fact]
public void SelectionEnd_Doesnt_Cause_Exception()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789"
};
target.SelectionStart = 0;
target.SelectionEnd = 9;
target.Text = "123";
RaiseTextEvent(target, "456");
Assert.True(true);
}
}
[Fact]
public void SelectionStart_Doesnt_Cause_Exception()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789"
};
target.SelectionStart = 8;
target.SelectionEnd = 9;
target.Text = "123";
RaiseTextEvent(target, "456");
Assert.True(true);
}
}
[Fact]
public void SelectionStartEnd_Are_Valid_AterTextChange()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789"
};
target.SelectionStart = 8;
target.SelectionEnd = 9;
target.Text = "123";
Assert.True(target.SelectionStart <= "123".Length);
Assert.True(target.SelectionEnd <= "123".Length);
}
}
[Fact]
public void SelectedText_Changes_OnSelectionChange()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789"
};
Assert.True(target.SelectedText == "");
target.SelectionStart = 2;
target.SelectionEnd = 4;
Assert.True(target.SelectedText == "23");
}
}
[Fact]
public void SelectedText_EditsText()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123"
};
target.SelectedText = "AA";
Assert.True(target.Text == "AA0123");
target.SelectionStart = 1;
target.SelectionEnd = 3;
target.SelectedText = "BB";
Assert.True(target.Text == "ABB123");
}
}
[Fact]
public void SelectedText_CanClearText()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123"
};
target.SelectionStart = 1;
target.SelectionEnd = 3;
target.SelectedText = "";
Assert.True(target.Text == "03");
}
}
[Fact]
public void SelectedText_NullClearsText()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123"
};
target.SelectionStart = 1;
target.SelectionEnd = 3;
target.SelectedText = null;
Assert.True(target.Text == "03");
}
}
[Fact]
public void CoerceCaretIndex_Doesnt_Cause_Exception_with_malformed_line_ending()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789\r"
};
target.CaretIndex = 11;
Assert.True(true);
}
}
[Theory]
[InlineData(Key.Up)]
[InlineData(Key.Down)]
[InlineData(Key.Home)]
[InlineData(Key.End)]
public void Textbox_doesnt_crash_when_Receives_input_and_template_not_applied(Key key)
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234",
IsVisible = false
};
var root = new TestRoot { Child = target1 };
target1.Focus();
Assert.True(target1.IsFocused);
RaiseKeyEvent(target1, key, KeyModifiers.None);
}
}
[Fact]
public void TextBox_GotFocus_And_LostFocus_Work_Properly()
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
var target2 = new TextBox
{
Template = CreateTemplate(),
Text = "5678"
};
var sp = new StackPanel();
sp.Children.Add(target1);
sp.Children.Add(target2);
target1.ApplyTemplate();
target2.ApplyTemplate();
var root = new TestRoot { Child = sp };
var gfcount = 0;
var lfcount = 0;
target1.GotFocus += (s, e) => gfcount++;
target2.LostFocus += (s, e) => lfcount++;
target2.Focus();
Assert.False(target1.IsFocused);
Assert.True(target2.IsFocused);
target1.Focus();
Assert.False(target2.IsFocused);
Assert.True(target1.IsFocused);
Assert.Equal(1, gfcount);
Assert.Equal(1, lfcount);
}
}
[Fact]
public void TextBox_CaretIndex_Persists_When_Focus_Lost()
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
var target2 = new TextBox
{
Template = CreateTemplate(),
Text = "5678"
};
var sp = new StackPanel();
sp.Children.Add(target1);
sp.Children.Add(target2);
target1.ApplyTemplate();
target2.ApplyTemplate();
var root = new TestRoot { Child = sp };
target2.Focus();
target2.CaretIndex = 2;
Assert.False(target1.IsFocused);
Assert.True(target2.IsFocused);
target1.Focus();
Assert.Equal(2, target2.CaretIndex);
}
}
[Fact]
public void TextBox_Reveal_Password_Reset_When_Lost_Focus()
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234",
PasswordChar = '*'
};
var target2 = new TextBox
{
Template = CreateTemplate(),
Text = "5678"
};
var sp = new StackPanel();
sp.Children.Add(target1);
sp.Children.Add(target2);
target1.ApplyTemplate();
target2.ApplyTemplate();
var root = new TestRoot { Child = sp };
target1.Focus();
target1.RevealPassword = true;
target2.Focus();
Assert.False(target1.RevealPassword);
}
}
[Fact]
public void Setting_Bound_Text_To_Null_Works()
{
using (UnitTestApplication.Start(Services))
{
var source = new Class1 { Bar = "bar" };
var target = new TextBox { DataContext = source };
target.Bind(TextBox.TextProperty, new Binding("Bar"));
Assert.Equal("bar", target.Text);
source.Bar = null;
Assert.Null(target.Text);
}
}
[Theory]
[InlineData("abc", "d", 3, 0, 0, false, "abc")]
[InlineData("abc", "dd", 4, 3, 3, false, "abcd")]
[InlineData("abc", "ddd", 3, 0, 2, true, "ddc")]
[InlineData("abc", "dddd", 4, 1, 3, true, "addd")]
[InlineData("abc", "ddddd", 5, 3, 3, true, "abcdd")]
public void MaxLength_Works_Properly(
string initalText,
string textInput,
int maxLength,
int selectionStart,
int selectionEnd,
bool fromClipboard,
string expected)
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = initalText,
MaxLength = maxLength,
SelectionStart = selectionStart,
SelectionEnd = selectionEnd
};
if (fromClipboard)
{
AvaloniaLocator.CurrentMutable.Bind<IClipboard>().ToSingleton<ClipboardStub>();
var clipboard = AvaloniaLocator.CurrentMutable.GetService<IClipboard>();
clipboard.SetTextAsync(textInput).GetAwaiter().GetResult();
RaiseKeyEvent(target, Key.V, KeyModifiers.Control);
clipboard.ClearAsync().GetAwaiter().GetResult();
}
else
{
RaiseTextEvent(target, textInput);
}
Assert.Equal(expected, target.Text);
}
}
[Theory]
[InlineData(Key.X, KeyModifiers.Control)]
[InlineData(Key.Back, KeyModifiers.None)]
[InlineData(Key.Delete, KeyModifiers.None)]
[InlineData(Key.Tab, KeyModifiers.None)]
[InlineData(Key.Enter, KeyModifiers.None)]
public void Keys_Allow_Undo(Key key, KeyModifiers modifiers)
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123",
AcceptsReturn = true,
AcceptsTab = true
};
target.SelectionStart = 1;
target.SelectionEnd = 3;
AvaloniaLocator.CurrentMutable
.Bind<Input.Platform.IClipboard>().ToSingleton<ClipboardStub>();
RaiseKeyEvent(target, key, modifiers);
RaiseKeyEvent(target, Key.Z, KeyModifiers.Control); // undo
Assert.True(target.Text == "0123");
}
}
[Fact]
public void Setting_SelectedText_Should_Fire_Single_Text_Changed_Notification()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123",
AcceptsReturn = true,
AcceptsTab = true,
SelectionStart = 1,
SelectionEnd = 3,
};
var values = new List<string>();
target.GetObservable(TextBox.TextProperty).Subscribe(x => values.Add(x));
target.SelectedText = "A";
Assert.Equal(new[] { "0123", "0A3" }, values);
}
}
[Fact]
public void Entering_Text_With_SelectedText_Should_Fire_Single_Text_Changed_Notification()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123",
AcceptsReturn = true,
AcceptsTab = true,
SelectionStart = 1,
SelectionEnd = 3,
};
var values = new List<string>();
target.GetObservable(TextBox.TextProperty).Subscribe(x => values.Add(x));
RaiseTextEvent(target, "A");
Assert.Equal(new[] { "0123", "0A3" }, values);
}
}
private static TestServices FocusServices => TestServices.MockThreadingInterface.With(
focusManager: new FocusManager(),
keyboardDevice: () => new KeyboardDevice(),
keyboardNavigation: new KeyboardNavigationHandler(),
inputManager: new InputManager(),
renderInterface: new MockPlatformRenderInterface(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl(),
standardCursorFactory: Mock.Of<ICursorFactory>());
private static TestServices Services => TestServices.MockThreadingInterface.With(
standardCursorFactory: Mock.Of<ICursorFactory>());
private IControlTemplate CreateTemplate()
{
return new FuncControlTemplate<TextBox>((control, scope) =>
new TextPresenter
{
Name = "PART_TextPresenter",
[!!TextPresenter.TextProperty] = new Binding
{
Path = "Text",
Mode = BindingMode.TwoWay,
Priority = BindingPriority.TemplatedParent,
RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent),
},
}.RegisterInNameScope(scope));
}
private void RaiseKeyEvent(TextBox textBox, Key key, KeyModifiers inputModifiers)
{
textBox.RaiseEvent(new KeyEventArgs
{
RoutedEvent = InputElement.KeyDownEvent,
KeyModifiers = inputModifiers,
Key = key
});
}
private void RaiseTextEvent(TextBox textBox, string text)
{
textBox.RaiseEvent(new TextInputEventArgs
{
RoutedEvent = InputElement.TextInputEvent,
Text = text
});
}
private class Class1 : NotifyingBase
{
private int _foo;
private string _bar;
public int Foo
{
get { return _foo; }
set { _foo = value; RaisePropertyChanged(); }
}
public string Bar
{
get { return _bar; }
set { _bar = value; RaisePropertyChanged(); }
}
}
private class ClipboardStub : IClipboard // in order to get tests working that use the clipboard
{
private string _text;
public Task<string> GetTextAsync() => Task.FromResult(_text);
public Task SetTextAsync(string text)
{
_text = text;
return Task.CompletedTask;
}
public Task ClearAsync()
{
_text = null;
return Task.CompletedTask;
}
public Task SetDataObjectAsync(IDataObject data) => Task.CompletedTask;
public Task<string[]> GetFormatsAsync() => Task.FromResult(Array.Empty<string>());
public Task<object> GetDataAsync(string format) => Task.FromResult((object)null);
}
private class TestContextMenu : ContextMenu
{
public TestContextMenu()
{
IsOpen = true;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using NextBus.Logging.Appenders;
namespace NextBus.Logging
{
/// <summary>
/// Shared log provider to write info/warning/errors to all listening log appenders
/// </summary>
public static class LogHelper
{
public static List<ILogAppender> Appenders { get; set; } = new List<ILogAppender>();
#region Info
public static void Info(string title)
{
Write(new LogEntry
{
Type = LogType.Info,
Title = title
});
}
public static void Info(string title, string message)
{
Write(new LogEntry
{
Type = LogType.Info,
Title = title,
Message = message
});
}
public static void Info<TType>(string title, string message)
{
Write(new LogEntry
{
Type = LogType.Info,
Title = title,
Message = message,
Source = typeof(TType).FullName
});
}
public static void Info(string title, Type source)
{
Write(new LogEntry
{
Type = LogType.Info,
Title = title,
Source = source.FullName
});
}
public static void Info(string title, string message, Type source)
{
Write(new LogEntry
{
Type = LogType.Info,
Title = title,
Message = message,
Source = source.FullName
});
}
#endregion
#region Warn
public static void Warn(string title)
{
Write(new LogEntry
{
Type = LogType.Warn,
Title = title
});
}
public static void Warn(string title, string message)
{
Write(new LogEntry
{
Type = LogType.Warn,
Title = title,
Message = message
});
}
public static void Warn<TType>(string title, string message)
{
Write(new LogEntry
{
Type = LogType.Warn,
Title = title,
Message = message,
Source = typeof(TType).FullName
});
}
public static void Warn(string title, Type source)
{
Write(new LogEntry
{
Type = LogType.Warn,
Title = title,
Source = source.FullName
});
}
public static void Warn(string title, string message, Type source)
{
Write(new LogEntry
{
Type = LogType.Warn,
Title = title,
Message = message,
Source = source.FullName
});
}
#endregion
#region Error
public static void Error(string title, string message)
{
Write(new LogEntry
{
Type = LogType.Error,
Title = title,
Message = message
});
}
public static void Error<TType>(string title, string message)
{
Write(new LogEntry
{
Type = LogType.Error,
Title = title,
Message = message,
Source = typeof(TType).FullName
});
}
public static void Error(string title, Exception exception)
{
Write(new LogEntry
{
Type = LogType.Error,
Title = title,
Message = exception.ToString()
});
}
public static void Error<TType>(string title, Exception exception)
{
Write(new LogEntry
{
Type = LogType.Error,
Title = title,
Message = exception.ToString(),
Source = typeof(TType).FullName
});
}
public static void Error<TType>(Exception exception)
{
Write(new LogEntry
{
Type = LogType.Error,
Title = exception.Message,
Message = exception.ToString(),
Source = typeof(TType).FullName
});
}
public static void Error(string title, Exception exception, Type source)
{
Write(new LogEntry
{
Type = LogType.Error,
Title = title,
Message = exception.ToString(),
Source = source.FullName
});
}
#endregion
/// <summary>
/// Writes the log entry to all configured appenders
/// </summary>
public static void Write(LogEntry log)
{
foreach (var logAppender in Appenders)
{
logAppender.Write(log);
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>KeywordPlan</c> resource.</summary>
public sealed partial class KeywordPlanName : gax::IResourceName, sys::IEquatable<KeywordPlanName>
{
/// <summary>The possible contents of <see cref="KeywordPlanName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>.
/// </summary>
CustomerKeywordPlan = 1,
}
private static gax::PathTemplate s_customerKeywordPlan = new gax::PathTemplate("customers/{customer_id}/keywordPlans/{keyword_plan_id}");
/// <summary>Creates a <see cref="KeywordPlanName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="KeywordPlanName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static KeywordPlanName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new KeywordPlanName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="KeywordPlanName"/> with the pattern
/// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanId">The <c>KeywordPlan</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="KeywordPlanName"/> constructed from the provided ids.</returns>
public static KeywordPlanName FromCustomerKeywordPlan(string customerId, string keywordPlanId) =>
new KeywordPlanName(ResourceNameType.CustomerKeywordPlan, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), keywordPlanId: gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanId, nameof(keywordPlanId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KeywordPlanName"/> with pattern
/// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanId">The <c>KeywordPlan</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="KeywordPlanName"/> with pattern
/// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>.
/// </returns>
public static string Format(string customerId, string keywordPlanId) =>
FormatCustomerKeywordPlan(customerId, keywordPlanId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KeywordPlanName"/> with pattern
/// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanId">The <c>KeywordPlan</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="KeywordPlanName"/> with pattern
/// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>.
/// </returns>
public static string FormatCustomerKeywordPlan(string customerId, string keywordPlanId) =>
s_customerKeywordPlan.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanId, nameof(keywordPlanId)));
/// <summary>Parses the given resource name string into a new <see cref="KeywordPlanName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="keywordPlanName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="KeywordPlanName"/> if successful.</returns>
public static KeywordPlanName Parse(string keywordPlanName) => Parse(keywordPlanName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="KeywordPlanName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="keywordPlanName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="KeywordPlanName"/> if successful.</returns>
public static KeywordPlanName Parse(string keywordPlanName, bool allowUnparsed) =>
TryParse(keywordPlanName, allowUnparsed, out KeywordPlanName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="KeywordPlanName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="keywordPlanName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="KeywordPlanName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string keywordPlanName, out KeywordPlanName result) =>
TryParse(keywordPlanName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="KeywordPlanName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="keywordPlanName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="KeywordPlanName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string keywordPlanName, bool allowUnparsed, out KeywordPlanName result)
{
gax::GaxPreconditions.CheckNotNull(keywordPlanName, nameof(keywordPlanName));
gax::TemplatedResourceName resourceName;
if (s_customerKeywordPlan.TryParseName(keywordPlanName, out resourceName))
{
result = FromCustomerKeywordPlan(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(keywordPlanName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private KeywordPlanName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string keywordPlanId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
KeywordPlanId = keywordPlanId;
}
/// <summary>
/// Constructs a new instance of a <see cref="KeywordPlanName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanId">The <c>KeywordPlan</c> ID. Must not be <c>null</c> or empty.</param>
public KeywordPlanName(string customerId, string keywordPlanId) : this(ResourceNameType.CustomerKeywordPlan, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), keywordPlanId: gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanId, nameof(keywordPlanId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>KeywordPlan</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string KeywordPlanId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerKeywordPlan: return s_customerKeywordPlan.Expand(CustomerId, KeywordPlanId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as KeywordPlanName);
/// <inheritdoc/>
public bool Equals(KeywordPlanName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(KeywordPlanName a, KeywordPlanName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(KeywordPlanName a, KeywordPlanName b) => !(a == b);
}
public partial class KeywordPlan
{
/// <summary>
/// <see cref="gagvr::KeywordPlanName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal KeywordPlanName ResourceNameAsKeywordPlanName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::KeywordPlanName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::KeywordPlanName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal KeywordPlanName KeywordPlanName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::KeywordPlanName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// 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.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Text;
namespace Microsoft.Research.DataStructures
{
/// <summary>
/// Subclass this class and define public fields for options
/// </summary>
public abstract class OptionParsing
{
public OptionParsing()
{
requiredOptions = GatherRequiredOptions();
}
/// <summary>
/// The number of errors discovered during command-line option parsing.
/// </summary>
protected int errors = 0;
private bool helpRequested;
/// <summary>
/// True if and only if a question mark was given as a command-line option.
/// </summary>
public bool HelpRequested { get { return helpRequested; } }
/// <summary>
/// True if and only if some command-line option caused a parsing error, or specifies an option
/// that does not exist.
/// </summary>
public bool HasErrors { get { return errors > 0; } }
private List<string> errorMessages = new List<string>();
/// <summary>
/// Allows a client to signal that there is an error in the command-line options.
/// </summary>
public void AddError() { this.errors++; }
/// <summary>
/// Allows a client to signal that there is an error in the command-line options.
/// </summary>
public void AddError(string format, params object[] args)
{
this.AddMessage(format, args);
this.errors++;
}
/// <summary>
/// Allows a client add a message to the output.
/// </summary>
public void AddMessage(string format, params object[] args)
{
errorMessages.Add(String.Format(format, args));
}
protected IEnumerable<string> Messages { get { return errorMessages; } }
/// <summary>
/// Put this on fields if you want a more verbose help description
/// </summary>
protected class OptionDescription : Attribute
{
/// <summary>
/// The text that is shown when the usage is displayed.
/// </summary>
readonly public string Description;
/// <summary>
/// Constructor for creating the information about an option.
/// </summary>
public OptionDescription(string s) { this.Description = s; }
/// <summary>
/// Indicates whether the associated option is required or not.
/// </summary>
public bool Required { get; set; }
/// <summary>
/// Indicates a short form for the option. Very useful for options
/// whose names are reserved keywords.
/// </summary>
public string ShortForm { get; set; }
}
/// <summary>
/// Put this on fields if you want the field to be relevant when hashing an Option object
/// </summary>
protected class OptionWitness : Attribute { }
/// <summary>
/// If a field has this attribute, then its value is inherited by all the family of analyses
/// </summary>
public class OptionValueOverridesFamily : Attribute { }
/// <summary>
/// A way to have a single option be a macro for several options.
/// </summary>
protected class OptionFor : Attribute
{
/// <summary>
/// The field that this option is a macro for.
/// </summary>
readonly public string options;
/// <summary>
/// Constructor for specifying which field this is a macro option for.
/// </summary>
public OptionFor(string options)
{
this.options = options;
}
}
/// <summary>
/// Override and return false if options do not start with '-' or '/'
/// </summary>
protected virtual bool UseDashOptionPrefix { get { return true; } }
protected virtual bool TreatGeneralArgumentsAsUnknown { get { return false; } }
protected virtual bool TreatHelpArgumentAsUnknown { get { return false; } }
/// <summary>
/// This field will hold non-option arguments
/// </summary>
private readonly List<string> generalArguments = new List<string>();
/// <summary>
/// Initialized in constructor
/// </summary>
private IList<string> requiredOptions;
/// <summary>
/// The non-option arguments provided on the command line.
/// </summary>
public List<string> GeneralArguments { get { return generalArguments; } }
#region Parsing and Reflection
/// <summary>
/// Called when reflection based resolution does not find option
/// </summary>
/// <param name="option">option name (no - or /)</param>
/// <param name="args">all args being parsed</param>
/// <param name="index">current index of arg</param>
/// <param name="optionEqualsArgument">null, or the optionArgument when option was option=optionArgument</param>
/// <returns>true if option is recognized, false otherwise</returns>
protected virtual bool ParseUnknown(string option, string[] args, ref int index, string optionEqualsArgument)
{
return false;
}
protected virtual bool ParseGeneralArgument(string arg, string[] args, ref int index)
{
generalArguments.Add(arg);
return true;
}
// Also add '!' as synonim for '=', as cmd.exe performs fuzzy things with '='
private static readonly char[] equalChars = new char[] { ':', '=', '!' };
private static readonly char[] quoteChars = new char[] { '\'', '"' };
/// <summary>
/// Main method called by a client to process the command-line options.
/// </summary>
public void Parse(string[] args, bool parseResponseFile = true)
{
int index = 0;
while (index < args.Length)
{
string arg = args[index];
if (arg == "") { index++; continue; }
if (parseResponseFile && arg[0] == '@')
{
var responseFile = arg.Substring(1);
while (!ParseResponseFile(responseFile))
{
index++;
if (index < args.Length)
{
responseFile = string.Format("{0} {1}", responseFile, args[index]);
}
else
{
AddError("Response file '{0}' does not exist.", responseFile);
break;
}
}
}
else if (!this.UseDashOptionPrefix || arg[0] == '/' || arg[0] == '-')
{
if (this.UseDashOptionPrefix)
{
arg = arg.Remove(0, 1);
}
if (arg == "?" && !this.TreatHelpArgumentAsUnknown)
{
helpRequested = true;
index++;
continue;
}
string equalArgument = null;
int equalIndex = arg.IndexOfAny(equalChars); // use IndexOfAny instead of sequential IndexOf to parse correctly -arg=abc://def
if (equalIndex >= 0)
{
equalArgument = arg.Substring(equalIndex + 1);
arg = arg.Substring(0, equalIndex);
// remove quotes if any
if (equalArgument.Length >= 2 && equalArgument[0] == equalArgument[equalArgument.Length - 1] && quoteChars.Contains(equalArgument[0]))
equalArgument = equalArgument.Substring(1, equalArgument.Length - 2);
}
bool optionOK = this.FindOptionByReflection(arg, args, ref index, equalArgument);
if (!optionOK)
{
optionOK = this.ParseUnknown(arg, args, ref index, equalArgument);
if (!optionOK)
{
AddError("Unknown option '{0}'", arg);
}
}
}
else if (this.TreatGeneralArgumentsAsUnknown)
{
bool optionOK = this.ParseUnknown(arg, args, ref index, null);
if (!optionOK)
{
AddError("Unknown option '{0}'", arg);
}
}
else
{
bool optionOK = this.ParseGeneralArgument(arg, args, ref index);
if (!optionOK)
{
AddError("Unknown option '{0}'", arg);
}
}
index++;
}
if (!helpRequested) CheckRequiredOptions();
}
/// <returns>True, if file exists</returns>
private bool ParseResponseFile(string responseFile)
{
if (!File.Exists(responseFile))
{
return false;
}
try
{
var lines = File.ReadAllLines(responseFile);
for (int i = 0; i < lines.Length; i++)
{
var line = lines[i];
if (line.Length == 0) continue;
if (line[0] == '#')
{
// comment skip
continue;
}
if (ContainsQuote(line))
{
Parse(SplitLineWithQuotes(responseFile, i, line));
}
else
{
// simple splitting
Parse(line.Split(' '));
}
}
}
catch
{
AddError("Failure reading from response file '{0}'.", responseFile);
}
return true;
}
[Pure]
private string[] SplitLineWithQuotes(string responseFileName, int lineNo, string line)
{
var start = 0;
var args = new List<string>();
bool inDoubleQuotes = false;
int escaping = 0; // number of escape characters in sequence
var currentArg = new StringBuilder();
for (var index = 0; index < line.Length; index++)
{
var current = line[index];
if (current == '\\')
{
// escape character
escaping++;
// swallow the escape character for now
// grab everything prior to prior escape character
if (index > start)
{
currentArg.Append(line.Substring(start, index - start));
}
start = index + 1;
continue;
}
if (escaping > 0)
{
if (current == '"')
{
var backslashes = escaping / 2;
for (int i = 0; i < backslashes; i++) { currentArg.Append('\\'); }
if (escaping % 2 == 1)
{
// escapes the "
currentArg.Append('"');
escaping = 0;
start = index + 1;
continue;
}
}
else
{
var backslashes = escaping;
for (int i = 0; i < backslashes; i++) { currentArg.Append('\\'); }
}
escaping = 0;
}
if (inDoubleQuotes)
{
if (current == '"')
{
// ending argument
FinishArgument(line, start, args, currentArg, index, true);
start = index + 1;
inDoubleQuotes = false;
continue;
}
}
else // not in quotes
{
if (Char.IsWhiteSpace(current))
{
// end previous, start new
FinishArgument(line, start, args, currentArg, index, false);
start = index + 1;
continue;
}
if (current == '"')
{
// starting double quote
if (index != start)
{
AddError("Response file '{0}' line {1}, char {2} contains '\"' not starting or ending an argument", responseFileName, lineNo, index);
}
start = index + 1;
inDoubleQuotes = true;
continue;
}
}
}
// add outstanding escape characters
while (escaping > 0) { currentArg.Append('\\'); escaping--; }
FinishArgument(line, start, args, currentArg, line.Length, inDoubleQuotes);
return args.ToArray();
}
[Pure]
static private void FinishArgument(string line, int start, List<string> args, StringBuilder currentArg, int index, bool includeEmpty)
{
currentArg.Append(line.Substring(start, index - start));
if (includeEmpty || currentArg.Length > 0)
{
args.Add(currentArg.ToString());
currentArg.Length = 0;
}
}
[Pure]
static private bool ContainsQuote(string line)
{
var index = line.IndexOf('"');
if (index >= 0) return true;
index = line.IndexOf('\'');
if (index >= 0) return true;
return false;
}
[Pure]
private void CheckRequiredOptions()
{
foreach (var missed in requiredOptions)
{
AddError("Required option '-{0}' was not given.", missed);
}
}
private IList<string> GatherRequiredOptions()
{
List<string> result = new List<string>();
foreach (var field in this.GetType().GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public))
{
var options = field.GetCustomAttributes(typeof(OptionDescription), false);
foreach (OptionDescription attr in options)
{
if (attr.Required)
{
result.Add(field.Name.ToLowerInvariant());
}
}
}
return result;
}
private bool ParseValue<T>(Converter<string, T> parser, string equalArgument, string[] args, ref int index, ref object result)
{
if (equalArgument == null)
{
if (index + 1 < args.Length)
{
equalArgument = args[++index];
}
}
bool success = false;
if (equalArgument != null)
{
try
{
result = parser(equalArgument);
success = true;
}
catch
{
}
}
return success;
}
private bool ParseValue<T>(Converter<string, T> parser, string argument, ref object result)
{
bool success = false;
if (argument != null)
{
try
{
result = parser(argument);
success = true;
}
catch
{
}
}
return success;
}
private object ParseValue(Type type, string argument, string option)
{
object result = null;
if (type == typeof(bool))
{
if (argument != null)
{
// Allow "+/-" to turn on/off boolean options
if (argument.Equals("-"))
{
result = false;
}
else if (argument.Equals("+"))
{
result = true;
}
else if (!ParseValue<bool>(Boolean.Parse, argument, ref result))
{
AddError("option -{0} requires a bool argument", option);
}
}
else
{
result = true;
}
}
else if (type == typeof(string))
{
if (!ParseValue<string>(Identity, argument, ref result))
{
AddError("option -{0} requires a string argument", option);
}
}
else if (type == typeof(int))
{
if (!ParseValue<int>(Int32.Parse, argument, ref result))
{
AddError("option -{0} requires an int argument", option);
}
}
else if (type == typeof(uint))
{
if (!ParseValue<uint>(UInt32.Parse, argument, ref result))
{
AddError("option -{0} requires an unsigned int argument", option);
}
}
else if (type == typeof(long))
{
if (!ParseValue<long>(Int64.Parse, argument, ref result))
{
AddError("option -{0} requires a long argument", option);
}
}
else if (type.IsEnum)
{
if (!ParseValue<object>(ParseEnum(type), argument, ref result))
{
AddError("option -{0} expects one of", option);
foreach (System.Reflection.FieldInfo enumConstant in type.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public))
{
if (enumConstant.IsLiteral)
{
AddMessage(" {0}", enumConstant.Name);
}
}
}
}
return result;
}
[Pure]
private string AdvanceArgumentIfNoExplicitArg(Type type, string explicitArg, string[] args, ref int index)
{
if (explicitArg != null) return explicitArg;
if (type == typeof(bool))
{
// bool args don't grab the next arg
return null;
}
if (index + 1 < args.Length)
{
return args[++index];
}
return null;
}
private bool FindOptionByReflection(string arg, string[] args, ref int index, string explicitArgument)
{
System.Reflection.FieldInfo fi = this.GetType().GetField(arg, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (fi != null)
{
requiredOptions.Remove(arg.ToLowerInvariant());
return ProcessOptionWithMatchingField(arg, args, ref index, explicitArgument, ref fi);
}
else
{
// derived options
fi = this.GetType().GetField(arg, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy);
if (fi != null)
{
object derived = fi.GetValue(this);
if (derived is string)
{
this.Parse(((string)derived).Split(' '));
requiredOptions.Remove(arg.ToLowerInvariant());
return true;
}
}
// Try to see if the arg matches any ShortForm of an option
var allFields = this.GetType().GetFields();
System.Reflection.FieldInfo matchingField = null;
foreach (var f in allFields)
{
matchingField = f;
var options = matchingField.GetCustomAttributes(typeof(OptionDescription), false);
foreach (OptionDescription attr in options)
{
if (attr.ShortForm != null)
{
var lower1 = attr.ShortForm.ToLowerInvariant();
var lower2 = arg.ToLowerInvariant();
if (lower1.Equals(lower2))
{
requiredOptions.Remove(matchingField.Name.ToLowerInvariant());
return ProcessOptionWithMatchingField(arg, args, ref index, explicitArgument, ref matchingField);
}
}
}
}
}
return false;
}
private bool ProcessOptionWithMatchingField(string arg, string[] args, ref int index, string explicitArgument, ref System.Reflection.FieldInfo fi)
{
Type type = fi.FieldType;
bool isList = false;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
{
isList = true;
type = type.GetGenericArguments()[0];
}
if (isList && explicitArgument == "!!")
{
// way to set list to empty
System.Collections.IList listhandle = (System.Collections.IList)fi.GetValue(this);
listhandle.Clear();
return true;
}
string argument = AdvanceArgumentIfNoExplicitArg(type, explicitArgument, args, ref index);
if (isList)
{
if (argument == null)
{
AddError("option -{0} requires an argument", arg);
return true;
}
string[] listargs = argument.Split(';');
for (int i = 0; i < listargs.Length; i++)
{
if (listargs[i].Length == 0) continue; // skip empty values
bool remove = listargs[i][0] == '!';
string listarg = remove ? listargs[i].Substring(1) : listargs[i];
object value = ParseValue(type, listarg, arg);
if (value != null)
{
if (remove)
{
this.GetListField(fi).Remove(value);
}
else
{
this.GetListField(fi).Add(value);
}
}
}
}
else
{
object value = ParseValue(type, argument, arg);
if (value != null)
{
fi.SetValue(this, value);
string argname;
if (value is Int32 && HasOptionForAttribute(fi, out argname))
{
this.Parse(DerivedOptionFor(argname, (Int32)value).Split(' '));
}
}
}
return true;
}
[Pure]
private bool HasOptionForAttribute(System.Reflection.FieldInfo fi, out string argname)
{
var options = fi.GetCustomAttributes(typeof(OptionFor), true);
if (options != null && options.Length == 1)
{
argname = ((OptionFor)options[0]).options;
return true;
}
argname = null;
return false;
}
/// <summary>
/// For the given field, returns the derived option that is indexed by
/// option in the list of derived options.
/// </summary>
[Pure]
protected string DerivedOptionFor(string fieldWithOptions, int option)
{
string[] options;
if (TryGetOptions(fieldWithOptions, out options))
{
if (option < 0 || option >= options.Length)
{
return "";
}
return options[option];
}
return "";
}
/// <summary>
/// Returns the options associated with the field, specified as a string.
/// If there are none, options is set to null and false is returned.
/// </summary>
[Pure]
protected bool TryGetOptions(string fieldWithOptions, out string[] options)
{
var fi = this.GetType().GetField(fieldWithOptions,
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.Public);
if (fi != null)
{
var obj = fi.GetValue(this);
if (obj is string[])
{
options = (string[])obj;
return true;
}
}
options = null;
return false;
}
/// <summary>
/// Use this
/// </summary>
[Pure]
public long GetCheckCode()
{
var res = 0L;
foreach (var f in this.GetType().GetFields())
{
foreach (var a in f.GetCustomAttributes(true))
{
if (a is OptionWitness)
{
res += (f.GetValue(this).GetHashCode()) * f.GetHashCode();
break;
}
}
}
return res;
}
[Pure]
private string Identity(string s) { return s; }
private Converter<string, object> ParseEnum(Type enumType)
{
return delegate (string s) { return Enum.Parse(enumType, s, true); };
}
private System.Collections.IList GetListField(System.Reflection.FieldInfo fi)
{
object obj = fi.GetValue(this);
if (obj != null) { return (System.Collections.IList)obj; }
System.Collections.IList result = (System.Collections.IList)fi.FieldType.GetConstructor(new Type[] { }).Invoke(new object[] { });
fi.SetValue(this, result);
return result;
}
/// <summary>
/// Writes all of the options out to the console.
/// </summary>
[Pure]
public void PrintOptions(string indent, TextWriter output)
{
foreach (System.Reflection.FieldInfo f in this.GetType().GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
System.Type opttype = f.FieldType;
bool isList;
if (opttype.IsGenericType && opttype.GetGenericTypeDefinition() == typeof(List<>))
{
opttype = opttype.GetGenericArguments()[0];
isList = true;
}
else
{
isList = false;
}
string description = GetOptionAttribute(f);
string option = null;
if (opttype == typeof(bool))
{
if (!isList && f.GetValue(this).Equals(true))
{
option = String.Format("{0} (default=true)", f.Name);
}
else
{
option = f.Name;
}
}
else if (opttype == typeof(string))
{
if (!f.IsLiteral)
{
object defaultValue = f.GetValue(this);
if (!isList && defaultValue != null)
{
option = String.Format("{0} <string-arg> (default={1})", f.Name, defaultValue);
}
else
{
option = String.Format("{0} <string-arg>", f.Name);
}
}
}
else if (opttype == typeof(int))
{
if (!isList)
{
option = String.Format("{0} <int-arg> (default={1})", f.Name, f.GetValue(this));
}
else
{
option = String.Format("{0} <int-arg>", f.Name);
}
}
else if (opttype.IsEnum)
{
StringBuilder sb = new StringBuilder();
sb.Append(f.Name).Append(" (");
bool first = true;
foreach (System.Reflection.FieldInfo enumConstant in opttype.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static))
{
if (enumConstant.IsLiteral)
{
if (!first)
{
if (isList)
{
sb.Append(" + ");
}
else
{
sb.Append(" | ");
}
}
else
{
first = false;
}
sb.Append(enumConstant.Name);
}
}
sb.Append(") ");
if (!isList)
{
sb.AppendFormat("(default={0})", f.GetValue(this));
}
else
{
sb.Append("(default=");
bool first2 = true;
foreach (object eval in (System.Collections.IEnumerable)f.GetValue(this))
{
if (!first2)
{
sb.Append(',');
}
else
{
first2 = false;
}
sb.Append(eval.ToString());
}
sb.Append(')');
}
option = sb.ToString();
}
if (option != null)
{
output.Write("{1} -{0,-30}", option, indent);
if (description != null)
{
output.WriteLine(" : {0}", description);
}
else
{
output.WriteLine();
}
}
}
output.WriteLine(Environment.NewLine + "To clear a list, use -<option>=!!");
output.WriteLine(Environment.NewLine + "To remove an item from a list, use -<option> !<item>");
}
/// <summary>
/// Prints all of the derived options to the console.
/// </summary>
public void PrintDerivedOptions(string indent, TextWriter output)
{
foreach (System.Reflection.FieldInfo f in this.GetType().GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public))
{
if (f.IsLiteral)
{
output.WriteLine("{2} -{0} is '{1}'", f.Name, f.GetValue(this), indent);
}
}
}
private string GetOptionAttribute(System.Reflection.FieldInfo f)
{
object[] attrs = f.GetCustomAttributes(typeof(OptionDescription), true);
if (attrs != null && attrs.Length == 1)
{
StringBuilder result = new StringBuilder();
OptionDescription descr = (OptionDescription)attrs[0];
if (descr.Required)
{
result.Append("(required) ");
}
result.Append(descr.Description);
if (descr.ShortForm != null)
{
result.Append("[short form: " + descr.ShortForm + "]");
}
object[] optionsFor = f.GetCustomAttributes(typeof(OptionFor), true);
string[] options;
if (optionsFor != null && optionsFor.Length == 1 && TryGetOptions(((OptionFor)optionsFor[0]).options, out options))
{
result.AppendLine(Environment.NewLine + "Detailed explanation:");
for (int i = 0; i < options.Length; i++)
{
result.Append(string.Format("{0} : {1}" + Environment.NewLine, i, options[i]));
}
}
return result.ToString();
}
return null;
}
#endregion
public void PrintErrors(TextWriter output)
{
foreach (string message in errorMessages)
{
output.WriteLine(message);
}
output.WriteLine();
output.WriteLine(" use /? to see a list of options");
}
public void PrintErrorsAndExit(TextWriter output)
{
this.PrintErrors(output);
Environment.Exit(-1);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using Internal.NativeCrypto;
namespace System.Security.Cryptography
{
public sealed partial class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm
{
private int _keySize;
private CspParameters _parameters;
private bool _randomKeyContainer;
private SafeKeyHandle _safeKeyHandle;
private SafeProvHandle _safeProvHandle;
private static volatile CspProviderFlags s_UseMachineKeyStore = 0;
public RSACryptoServiceProvider()
: this(0, new CspParameters(CapiHelper.DefaultRsaProviderType,
null,
null,
s_UseMachineKeyStore),
true)
{
}
public RSACryptoServiceProvider(int dwKeySize)
: this(dwKeySize,
new CspParameters(CapiHelper.DefaultRsaProviderType,
null,
null,
s_UseMachineKeyStore), false)
{
}
public RSACryptoServiceProvider(int dwKeySize, CspParameters parameters)
: this(dwKeySize, parameters, false)
{
}
public RSACryptoServiceProvider(CspParameters parameters)
: this(0, parameters, true)
{
}
private RSACryptoServiceProvider(int keySize, CspParameters parameters, bool useDefaultKeySize)
{
if (keySize < 0)
{
throw new ArgumentOutOfRangeException("dwKeySize", "ArgumentOutOfRange_NeedNonNegNum");
}
_parameters = CapiHelper.SaveCspParameters(CapiHelper.CspAlgorithmType.Rsa, parameters, s_UseMachineKeyStore, ref _randomKeyContainer);
_keySize = useDefaultKeySize ? 1024 : keySize;
// If this is not a random container we generate, create it eagerly
// in the constructor so we can report any errors now.
if (!_randomKeyContainer)
{
GetKeyPair();
}
}
/// <summary>
/// Retreives the key pair
/// </summary>
private void GetKeyPair()
{
if (_safeKeyHandle == null)
{
lock (this)
{
if (_safeKeyHandle == null)
{
// We only attempt to generate a random key on desktop runtimes because the CoreCLR
// RSA surface area is limited to simply verifying signatures. Since generating a
// random key to verify signatures will always lead to failure (unless we happend to
// win the lottery and randomly generate the signing key ...), there is no need
// to add this functionality to CoreCLR at this point.
CapiHelper.GetKeyPairHelper(CapiHelper.CspAlgorithmType.Rsa, _parameters,
_randomKeyContainer, _keySize, ref _safeProvHandle, ref _safeKeyHandle);
}
}
}
}
/// <summary>
/// CspKeyContainerInfo property
/// </summary>
public CspKeyContainerInfo CspKeyContainerInfo
{
get
{
GetKeyPair();
return new CspKeyContainerInfo(_parameters, _randomKeyContainer);
}
}
/// <summary>
/// _keySize property
/// </summary>
public override int KeySize
{
get
{
GetKeyPair();
byte[] keySize = (byte[])CapiHelper.GetKeyParameter(_safeKeyHandle, Constants.CLR_KEYLEN);
_keySize = (keySize[0] | (keySize[1] << 8) | (keySize[2] << 16) | (keySize[3] << 24));
return _keySize;
}
}
public override KeySizes[] LegalKeySizes
{
get
{
return new[] { new KeySizes(384, 16384, 8) };
}
}
/// <summary>
/// get set Persisted key in CSP
/// </summary>
public bool PersistKeyInCsp
{
get
{
if (_safeProvHandle == null)
{
lock (this)
{
if (_safeProvHandle == null)
{
_safeProvHandle = CapiHelper.CreateProvHandle(_parameters, _randomKeyContainer);
}
}
}
return CapiHelper.GetPersistKeyInCsp(_safeProvHandle);
}
set
{
bool oldPersistKeyInCsp = this.PersistKeyInCsp;
if (value == oldPersistKeyInCsp)
{
return; // Do nothing
}
CapiHelper.SetPersistKeyInCsp(_safeProvHandle, value);
}
}
/// <summary>
/// Gets the information of key if it is a public key
/// </summary>
public bool PublicOnly
{
get
{
GetKeyPair();
byte[] publicKey = (byte[])CapiHelper.GetKeyParameter(_safeKeyHandle, Constants.CLR_PUBLICKEYONLY);
return (publicKey[0] == 1);
}
}
/// <summary>
/// MachineKey store properties
/// </summary>
public static bool UseMachineKeyStore
{
get
{
return (s_UseMachineKeyStore == CspProviderFlags.UseMachineKeyStore);
}
set
{
s_UseMachineKeyStore = (value ? CspProviderFlags.UseMachineKeyStore : 0);
}
}
/// <summary>
/// Decrypt raw data, generally used for decrypting symmetric key material
/// </summary>
/// <param name="rgb">encrypted data</param>
/// <param name="fOAEP">true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding</param>
/// <returns>decrypted data</returns>
public byte[] Decrypt(byte[] rgb, bool fOAEP)
{
if (rgb == null)
{
throw new ArgumentNullException("rgb");
}
GetKeyPair();
// size check -- must be at most the modulus size
if (rgb.Length > (KeySize / 8))
{
throw new CryptographicException(SR.Format(SR.Cryptography_Padding_DecDataTooBig, Convert.ToString(KeySize / 8)));
}
byte[] decryptedKey = null;
CapiHelper.DecryptKey(_safeKeyHandle, rgb, rgb.Length, fOAEP, out decryptedKey);
return decryptedKey;
}
/// <summary>
/// Dispose the key handles
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed)
{
_safeKeyHandle.Dispose();
}
if (_safeProvHandle != null && !_safeProvHandle.IsClosed)
{
_safeProvHandle.Dispose();
}
}
/// <summary>
/// Encrypt raw data, generally used for encrypting symmetric key material.
/// </summary>
/// <remarks>
/// This method can only encrypt (keySize - 88 bits) of data, so should not be used for encrypting
/// arbitrary byte arrays. Instead, encrypt a symmetric key with this method, and use the symmetric
/// key to encrypt the sensitive data.
/// </remarks>
/// <param name="rgb">raw data to encryt</param>
/// <param name="fOAEP">true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding</param>
/// <returns>Encrypted key</returns>
public byte[] Encrypt(byte[] rgb, bool fOAEP)
{
if (rgb == null)
{
throw new ArgumentNullException("rgb");
}
GetKeyPair();
byte[] encryptedKey = null;
CapiHelper.EncryptKey(_safeKeyHandle, rgb, rgb.Length, fOAEP, ref encryptedKey);
return encryptedKey;
}
/// <summary>
///Exports a blob containing the key information associated with an RSACryptoServiceProvider object.
/// </summary>
public byte[] ExportCspBlob(bool includePrivateParameters)
{
GetKeyPair();
return CapiHelper.ExportKeyBlob(includePrivateParameters, _safeKeyHandle);
}
/// <summary>
/// Exports the RSAParameters
/// </summary>
public override RSAParameters ExportParameters(bool includePrivateParameters)
{
GetKeyPair();
byte[] cspBlob = ExportCspBlob(includePrivateParameters);
return cspBlob.ToRSAParameters(includePrivateParameters);
}
/// <summary>
/// This method helps Acquire the default CSP and avoids the need for static SafeProvHandle
/// in CapiHelper class
/// </summary>
/// <param name="safeProvHandle"> SafeProvHandle. Intialized if successful</param>
/// <returns>does not return. AcquireCSP throw exception</returns>
private void AcquireSafeProviderHandle(ref SafeProvHandle safeProvHandle)
{
CapiHelper.AcquireCsp(new CspParameters(CapiHelper.DefaultRsaProviderType), ref safeProvHandle);
}
/// <summary>
/// Imports a blob that represents RSA key information
/// </summary>
/// <param name="keyBlob"></param>
public void ImportCspBlob(byte[] keyBlob)
{
// Free the current key handle
if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed)
{
_safeKeyHandle.Dispose();
_safeKeyHandle = null;
}
_safeKeyHandle = SafeKeyHandle.InvalidHandle;
if (IsPublic(keyBlob))
{
SafeProvHandle safeProvHandleTemp = SafeProvHandle.InvalidHandle;
AcquireSafeProviderHandle(ref safeProvHandleTemp);
CapiHelper.ImportKeyBlob(safeProvHandleTemp, (CspProviderFlags)0, keyBlob, ref _safeKeyHandle);
_safeProvHandle = safeProvHandleTemp;
}
else
{
if (_safeProvHandle == null)
{
_safeProvHandle = CapiHelper.CreateProvHandle(_parameters, _randomKeyContainer);
}
CapiHelper.ImportKeyBlob(_safeProvHandle, _parameters.Flags, keyBlob, ref _safeKeyHandle);
}
}
/// <summary>
/// Imports the specified RSAParameters
/// </summary>
public override void ImportParameters(RSAParameters parameters)
{
// Free the current key handle
if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed)
{
_safeKeyHandle.Dispose();
_safeKeyHandle = null;
}
_safeKeyHandle = SafeKeyHandle.InvalidHandle;
byte[] keyBlob = parameters.ToKeyBlob(CapiHelper.CALG_RSA_KEYX);
ImportCspBlob(keyBlob);
return;
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="buffer">The input data for which to compute the hash</param>
/// <param name="offset">The offset into the array from which to begin using data</param>
/// <param name="count">The number of bytes in the array to use as data. </param>
/// <param name="halg">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
public byte[] SignData(byte[] buffer, int offset, int count, Object halg)
{
int calgHash = CapiHelper.ObjToHashAlgId(halg);
HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(buffer, offset, count);
return SignHash(hashVal, calgHash);
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="buffer">The input data for which to compute the hash</param>
/// <param name="halg">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
public byte[] SignData(byte[] buffer, Object halg)
{
int calgHash = CapiHelper.ObjToHashAlgId(halg);
HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(buffer);
return SignHash(hashVal, calgHash);
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="inputStream">The input data for which to compute the hash</param>
/// <param name="halg">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
public byte[] SignData(Stream inputStream, Object halg)
{
int calgHash = CapiHelper.ObjToHashAlgId(halg);
HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(inputStream);
return SignHash(hashVal, calgHash);
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="rgbHash">The input data for which to compute the hash</param>
/// <param name="str">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
public byte[] SignHash(byte[] rgbHash, string str)
{
if (rgbHash == null)
throw new ArgumentNullException("rgbHash");
if (PublicOnly)
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
int calgHash = CapiHelper.NameOrOidToHashAlgId(str);
return SignHash(rgbHash, calgHash);
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="rgbHash">The input data for which to compute the hash</param>
/// <param name="calgHash">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
private byte[] SignHash(byte[] rgbHash, int calgHash)
{
Debug.Assert(rgbHash != null);
GetKeyPair();
return CapiHelper.SignValue(_safeProvHandle, _safeKeyHandle, _parameters.KeyNumber, CapiHelper.CALG_RSA_SIGN, calgHash, rgbHash);
}
/// <summary>
/// Verifies the signature of a hash value.
/// </summary>
public bool VerifyData(byte[] buffer, object halg, byte[] signature)
{
int calgHash = CapiHelper.ObjToHashAlgId(halg);
HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(buffer);
return VerifyHash(hashVal, calgHash, signature);
}
/// <summary>
/// Verifies the signature of a hash value.
/// </summary>
public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature)
{
if (rgbHash == null)
throw new ArgumentNullException("rgbHash");
if (rgbSignature == null)
throw new ArgumentNullException("rgbSignature");
int calgHash = CapiHelper.NameOrOidToHashAlgId(str);
return VerifyHash(rgbHash, calgHash, rgbSignature);
}
/// <summary>
/// Verifies the signature of a hash value.
/// </summary>
private bool VerifyHash(byte[] rgbHash, int calgHash, byte[] rgbSignature)
{
GetKeyPair();
return CapiHelper.VerifySign(_safeProvHandle, _safeKeyHandle, CapiHelper.CALG_RSA_SIGN, calgHash, rgbHash, rgbSignature);
}
/// <summary>
/// find whether an RSA key blob is public.
/// </summary>
private static bool IsPublic(byte[] keyBlob)
{
if (keyBlob == null)
{
throw new ArgumentNullException("keyBlob");
}
// The CAPI RSA public key representation consists of the following sequence:
// - BLOBHEADER
// - RSAPUBKEY
// The first should be PUBLICKEYBLOB and magic should be RSA_PUB_MAGIC "RSA1"
if (keyBlob[0] != CapiHelper.PUBLICKEYBLOB)
{
return false;
}
if (keyBlob[11] != 0x31 || keyBlob[10] != 0x41 || keyBlob[9] != 0x53 || keyBlob[8] != 0x52)
{
return false;
}
return true;
}
/// <summary>
/// Since P is required, we will assume its presence is synonymous to a private key.
/// </summary>
/// <param name="rsaParams"></param>
/// <returns></returns>
private static bool IsPublic(RSAParameters rsaParams)
{
return (rsaParams.P == null);
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
// we're sealed and the base should have checked this already
Debug.Assert(data != null);
Debug.Assert(count >= 0 && count <= data.Length);
Debug.Assert(offset >= 0 && offset <= data.Length - count);
Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));
using (HashAlgorithm hash = GetHashAlgorithm(hashAlgorithm))
{
return hash.ComputeHash(data, offset, count);
}
}
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
// we're sealed and the base should have checked this already
Debug.Assert(data != null);
Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));
using (HashAlgorithm hash = GetHashAlgorithm(hashAlgorithm))
{
return hash.ComputeHash(data);
}
}
private static HashAlgorithm GetHashAlgorithm(HashAlgorithmName hashAlgorithm)
{
switch (hashAlgorithm.Name)
{
case "MD5":
return MD5.Create();
case "SHA1":
return SHA1.Create();
case "SHA256":
return SHA256.Create();
case "SHA384":
return SHA384.Create();
case "SHA512":
return SHA512.Create();
default:
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name);
}
}
private static int GetAlgorithmId(HashAlgorithmName hashAlgorithm)
{
switch (hashAlgorithm.Name)
{
case "MD5":
return CapiHelper.CALG_MD5;
case "SHA1":
return CapiHelper.CALG_SHA1;
case "SHA256":
return CapiHelper.CALG_SHA_256;
case "SHA384":
return CapiHelper.CALG_SHA_384;
case "SHA512":
return CapiHelper.CALG_SHA_512;
default:
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name);
}
}
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
{
if (data == null)
throw new ArgumentNullException("data");
if (padding == null)
throw new ArgumentNullException("padding");
if (padding == RSAEncryptionPadding.Pkcs1)
{
return Encrypt(data, fOAEP: false);
}
else if (padding == RSAEncryptionPadding.OaepSHA1)
{
return Encrypt(data, fOAEP: true);
}
else
{
throw PaddingModeNotSupported();
}
}
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding)
{
if (data == null)
throw new ArgumentNullException("data");
if (padding == null)
throw new ArgumentNullException("padding");
if (padding == RSAEncryptionPadding.Pkcs1)
{
return Decrypt(data, fOAEP: false);
}
else if (padding == RSAEncryptionPadding.OaepSHA1)
{
return Decrypt(data, fOAEP: true);
}
else
{
throw PaddingModeNotSupported();
}
}
public override byte[] SignHash(
byte[] hash,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
if (hash == null)
throw new ArgumentNullException("hash");
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw HashAlgorithmNameNullOrEmpty();
if (padding == null)
throw new ArgumentNullException("padding");
if (padding != RSASignaturePadding.Pkcs1)
throw PaddingModeNotSupported();
return SignHash(hash, GetAlgorithmId(hashAlgorithm));
}
public override bool VerifyHash(
byte[] hash,
byte[] signature,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
if (hash == null)
throw new ArgumentNullException("hash");
if (signature == null)
throw new ArgumentNullException("signature");
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw HashAlgorithmNameNullOrEmpty();
if (padding == null)
throw new ArgumentNullException("padding");
if (padding != RSASignaturePadding.Pkcs1)
throw PaddingModeNotSupported();
return VerifyHash(hash, GetAlgorithmId(hashAlgorithm), signature);
}
private static Exception PaddingModeNotSupported()
{
return new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
private static Exception HashAlgorithmNameNullOrEmpty()
{
return new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm");
}
}
}
| |
/*
* 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 Mono.Addins;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.InstantMessage;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Server.Handlers.Hypergrid;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGMessageTransferModule")]
public class HGMessageTransferModule : ISharedRegionModule, IMessageTransferModule, IInstantMessageSimConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool m_Enabled = false;
protected List<Scene> m_Scenes = new List<Scene>();
protected IInstantMessage m_IMService;
protected Dictionary<UUID, object> m_UserLocationMap = new Dictionary<UUID, object>();
public event UndeliveredMessage OnUndeliveredMessage;
IUserManagement m_uMan;
IUserManagement UserManagementModule
{
get
{
if (m_uMan == null)
m_uMan = m_Scenes[0].RequestModuleInterface<IUserManagement>();
return m_uMan;
}
}
public virtual void Initialise(IConfigSource config)
{
IConfig cnf = config.Configs["Messaging"];
if (cnf != null && cnf.GetString(
"MessageTransferModule", "MessageTransferModule") != Name)
{
m_log.Debug("[HG MESSAGE TRANSFER]: Disabled by configuration");
return;
}
InstantMessageServerConnector imServer = new InstantMessageServerConnector(config, MainServer.Instance, this);
m_IMService = imServer.GetService();
m_Enabled = true;
}
public virtual void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_Scenes)
{
m_log.DebugFormat("[HG MESSAGE TRANSFER]: Message transfer module {0} active", Name);
scene.RegisterModuleInterface<IMessageTransferModule>(this);
m_Scenes.Add(scene);
}
}
public virtual void PostInitialise()
{
if (!m_Enabled)
return;
}
public virtual void RegionLoaded(Scene scene)
{
}
public virtual void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_Scenes)
{
m_Scenes.Remove(scene);
}
}
public virtual void Close()
{
}
public virtual string Name
{
get { return "HGMessageTransferModule"; }
}
public virtual Type ReplaceableInterface
{
get { return null; }
}
public void SendInstantMessage(GridInstantMessage im, MessageResultNotification result)
{
UUID toAgentID = new UUID(im.toAgentID);
// Try root avatar only first
foreach (Scene scene in m_Scenes)
{
// m_log.DebugFormat(
// "[HG INSTANT MESSAGE]: Looking for root agent {0} in {1}",
// toAgentID.ToString(), scene.RegionInfo.RegionName);
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null && !sp.IsChildAgent)
{
// Local message
// m_log.DebugFormat("[HG INSTANT MESSAGE]: Delivering IM to root agent {0} {1}", user.Name, toAgentID);
sp.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
// try child avatar second
foreach (Scene scene in m_Scenes)
{
// m_log.DebugFormat(
// "[HG INSTANT MESSAGE]: Looking for child of {0} in {1}",
// toAgentID, scene.RegionInfo.RegionName);
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null)
{
// Local message
// m_log.DebugFormat("[HG INSTANT MESSAGE]: Delivering IM to child agent {0} {1}", user.Name, toAgentID);
sp.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
// m_log.DebugFormat("[HG INSTANT MESSAGE]: Delivering IM to {0} via XMLRPC", im.toAgentID);
// Is the user a local user?
string url = string.Empty;
bool foreigner = false;
if (UserManagementModule != null && !UserManagementModule.IsLocalGridUser(toAgentID)) // foreign user
{
url = UserManagementModule.GetUserServerURL(toAgentID, "IMServerURI");
foreigner = true;
}
Util.FireAndForget(delegate
{
bool success = false;
if (foreigner && url == string.Empty) // we don't know about this user
{
string recipientUUI = TryGetRecipientUUI(new UUID(im.fromAgentID), toAgentID);
m_log.DebugFormat("[HG MESSAGE TRANSFER]: Got UUI {0}", recipientUUI);
if (recipientUUI != string.Empty)
{
UUID id; string u = string.Empty, first = string.Empty, last = string.Empty, secret = string.Empty;
if (Util.ParseUniversalUserIdentifier(recipientUUI, out id, out u, out first, out last, out secret))
{
success = m_IMService.OutgoingInstantMessage(im, u, true);
if (success)
UserManagementModule.AddUser(toAgentID, u + ";" + first + " " + last);
}
}
}
else
success = m_IMService.OutgoingInstantMessage(im, url, foreigner);
if (!success && !foreigner)
HandleUndeliverableMessage(im, result);
else
result(success);
});
return;
}
protected bool SendIMToScene(GridInstantMessage gim, UUID toAgentID)
{
bool successful = false;
foreach (Scene scene in m_Scenes)
{
ScenePresence sp = scene.GetScenePresence(toAgentID);
if(sp != null && !sp.IsChildAgent)
{
scene.EventManager.TriggerIncomingInstantMessage(gim);
successful = true;
}
}
if (!successful)
{
// If the message can't be delivered to an agent, it
// is likely to be a group IM. On a group IM, the
// imSessionID = toAgentID = group id. Raise the
// unhandled IM event to give the groups module
// a chance to pick it up. We raise that in a random
// scene, since the groups module is shared.
//
m_Scenes[0].EventManager.TriggerUnhandledInstantMessage(gim);
}
return successful;
}
public void HandleUndeliverableMessage(GridInstantMessage im, MessageResultNotification result)
{
UndeliveredMessage handlerUndeliveredMessage = OnUndeliveredMessage;
// If this event has handlers, then an IM from an agent will be
// considered delivered. This will suppress the error message.
//
if (handlerUndeliveredMessage != null)
{
handlerUndeliveredMessage(im);
if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent)
result(true);
else
result(false);
return;
}
//m_log.DebugFormat("[INSTANT MESSAGE]: Undeliverable");
result(false);
}
private string TryGetRecipientUUI(UUID fromAgent, UUID toAgent)
{
// Let's call back the fromAgent's user agent service
// Maybe that service knows about the toAgent
IClientAPI client = LocateClientObject(fromAgent);
if (client != null)
{
AgentCircuitData circuit = m_Scenes[0].AuthenticateHandler.GetAgentCircuitData(client.AgentId);
if (circuit != null)
{
if (circuit.ServiceURLs.ContainsKey("HomeURI"))
{
string uasURL = circuit.ServiceURLs["HomeURI"].ToString();
m_log.DebugFormat("[HG MESSAGE TRANSFER]: getting UUI of user {0} from {1}", toAgent, uasURL);
UserAgentServiceConnector uasConn = new UserAgentServiceConnector(uasURL);
string agentUUI = string.Empty;
try
{
agentUUI = uasConn.GetUUI(fromAgent, toAgent);
}
catch (Exception e) {
m_log.Debug("[HG MESSAGE TRANSFER]: GetUUI call failed ", e);
}
return agentUUI;
}
}
}
return string.Empty;
}
/// <summary>
/// Find the root client for a ID
/// </summary>
public IClientAPI LocateClientObject(UUID agentID)
{
lock (m_Scenes)
{
foreach (Scene scene in m_Scenes)
{
ScenePresence presence = scene.GetScenePresence(agentID);
if (presence != null && !presence.IsChildAgent)
return presence.ControllingClient;
}
}
return null;
}
#region IInstantMessageSimConnector
public bool SendInstantMessage(GridInstantMessage im)
{
//m_log.DebugFormat("[XXX] Hook SendInstantMessage {0}", im.message);
UUID agentID = new UUID(im.toAgentID);
return SendIMToScene(im, agentID);
}
#endregion
}
}
| |
//
// OracleDataReader.cs
//
// Part of the Mono class libraries at
// mcs/class/System.Data.OracleClient/System.Data.OracleClient
//
// Assembly: System.Data.OracleClient.dll
// Namespace: System.Data.OracleClient
//
// Authors: Tim Coleman <[email protected]>
// Daniel Morgan <[email protected]>
//
// Copyright (C) Tim Coleman, 2003
// Copyright (C) Daniel Morgan, 2003, 2005
//
// Licensed under the MIT/X11 License.
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.OracleClient.Oci;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Data.OracleClient {
public sealed class OracleDataReader : MarshalByRefObject, IDataReader, IDisposable, IDataRecord, IEnumerable
{
#region Fields
OracleCommand command;
ArrayList dataTypeNames;
bool disposed = false;
bool isClosed;
bool hasRows;
DataTable schemaTable;
int recordsAffected = -1;
OciStatementType statementType;
OciStatementHandle statement;
#endregion // Fields
#region Constructors
internal OracleDataReader (OracleCommand command, OciStatementHandle statement)
{
this.command = command;
this.hasRows = false;
this.isClosed = false;
this.schemaTable = ConstructSchemaTable ();
this.statement = statement;
this.statementType = statement.GetStatementType ();
}
internal OracleDataReader (OracleCommand command, OciStatementHandle statement, bool extHasRows )
{
this.command = command;
this.hasRows = extHasRows;
this.isClosed = false;
this.schemaTable = ConstructSchemaTable ();
this.statement = statement;
this.statementType = statement.GetStatementType ();
}
~OracleDataReader ()
{
Dispose (false);
}
#endregion // Constructors
#region Properties
public int Depth {
get { return 0; }
}
public int FieldCount {
get { return statement.ColumnCount; }
}
public bool HasRows {
get { return hasRows; }
}
public bool IsClosed {
get { return isClosed; }
}
public object this [string name] {
get { return GetValue (GetOrdinal (name)); }
}
public object this [int i] {
get { return GetValue (i); }
}
public int RecordsAffected {
get {
if (statementType == OciStatementType.Select)
return -1;
else
return GetRecordsAffected ();
}
}
#endregion // Properties
#region Methods
public void Close ()
{
statement.Dispose();
if (!isClosed)
command.CloseDataReader ();
isClosed = true;
}
private static DataTable ConstructSchemaTable ()
{
Type booleanType = Type.GetType ("System.Boolean");
Type stringType = Type.GetType ("System.String");
Type intType = Type.GetType ("System.Int32");
Type typeType = Type.GetType ("System.Type");
Type shortType = Type.GetType ("System.Int16");
DataTable schemaTable = new DataTable ("SchemaTable");
schemaTable.Columns.Add ("ColumnName", stringType);
schemaTable.Columns.Add ("ColumnOrdinal", intType);
schemaTable.Columns.Add ("ColumnSize", intType);
schemaTable.Columns.Add ("NumericPrecision", shortType);
schemaTable.Columns.Add ("NumericScale", shortType);
schemaTable.Columns.Add ("DataType", typeType);
schemaTable.Columns.Add ("IsLong", booleanType);
schemaTable.Columns.Add ("AllowDBNull", booleanType);
schemaTable.Columns.Add ("IsUnique", booleanType);
schemaTable.Columns.Add ("IsKey", booleanType);
schemaTable.Columns.Add ("IsReadOnly", booleanType);
schemaTable.Columns.Add ("BaseSchemaTable", stringType);
schemaTable.Columns.Add ("BaseCatalogName", stringType);
schemaTable.Columns.Add ("BaseTableName", stringType);
schemaTable.Columns.Add ("BaseColumnName", stringType);
schemaTable.Columns.Add ("BaseSchemaName", stringType);
return schemaTable;
}
private void Dispose (bool disposing)
{
if (!disposed) {
if (disposing) {
schemaTable.Dispose ();
Close ();
}
disposed = true;
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public bool GetBoolean (int i)
{
throw new NotSupportedException ();
}
public byte GetByte (int i)
{
throw new NotSupportedException ();
}
public long GetBytes (int i, long fieldOffset, byte[] buffer2, int bufferoffset, int length)
{
object value = GetValue (i);
if (!(value is byte[]))
throw new InvalidCastException ();
if ( buffer2 == null )
return ((byte []) value).Length; // Return length of data
// Copy data into buffer
long lobLength = ((byte []) value).Length;
if ( (lobLength - fieldOffset) < length)
length = (int) (lobLength - fieldOffset);
Array.Copy ( (byte[]) value, (int) fieldOffset, buffer2, bufferoffset, length);
return length; // return actual read count
}
public char GetChar (int i)
{
throw new NotSupportedException ();
}
public long GetChars (int i, long fieldOffset, char[] buffer2, int bufferoffset, int length)
{
object value = GetValue (i);
if (!(value is char[]))
throw new InvalidCastException ();
Array.Copy ((char[]) value, (int) fieldOffset, buffer2, bufferoffset, length);
return ((char[]) value).Length - fieldOffset;
}
[MonoTODO]
public IDataReader GetData (int i)
{
throw new NotImplementedException ();
}
public string GetDataTypeName (int i)
{
return dataTypeNames [i].ToString ().ToUpper ();
}
public DateTime GetDateTime (int i)
{
IConvertible c = (IConvertible) GetValue (i);
return c.ToDateTime (CultureInfo.CurrentCulture);
}
public decimal GetDecimal (int i)
{
IConvertible c = (IConvertible) GetValue (i);
return c.ToDecimal (CultureInfo.CurrentCulture);
}
public double GetDouble (int i)
{
IConvertible c = (IConvertible) GetValue (i);
return c.ToDouble (CultureInfo.CurrentCulture);
}
public Type GetFieldType (int i)
{
OciDefineHandle defineHandle = (OciDefineHandle) statement.Values [i];
return defineHandle.FieldType;
}
public float GetFloat (int i)
{
IConvertible c = (IConvertible) GetValue (i);
return c.ToSingle (CultureInfo.CurrentCulture);
}
public Guid GetGuid (int i)
{
throw new NotSupportedException ();
}
public short GetInt16 (int i)
{
throw new NotSupportedException ();
}
public int GetInt32 (int i)
{
IConvertible c = (IConvertible) GetValue (i);
return c.ToInt32 (CultureInfo.CurrentCulture);
}
public long GetInt64 (int i)
{
IConvertible c = (IConvertible) GetValue (i);
return c.ToInt64 (CultureInfo.CurrentCulture);
}
public string GetName (int i)
{
return statement.GetParameter (i).GetName ();
}
[MonoTODO]
public OracleBFile GetOracleBFile (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public OracleBinary GetOracleBinary (int i)
{
if (IsDBNull (i))
throw new InvalidOperationException("The value is null");
return new OracleBinary ((byte[]) GetValue (i));
}
public OracleLob GetOracleLob (int i)
{
if (IsDBNull (i))
throw new InvalidOperationException("The value is null");
OracleLob output = (OracleLob) ((OciDefineHandle) statement.Values [i]).GetValue();
output.connection = command.Connection;
return output;
}
public OracleNumber GetOracleNumber (int i)
{
if (IsDBNull (i))
throw new InvalidOperationException("The value is null");
return new OracleNumber (GetDecimal (i));
}
public OracleDateTime GetOracleDateTime (int i)
{
if (IsDBNull (i))
throw new InvalidOperationException("The value is null");
return new OracleDateTime (GetDateTime (i));
}
[MonoTODO]
public OracleMonthSpan GetOracleMonthSpan (int i)
{
throw new NotImplementedException ();
}
public OracleString GetOracleString (int i)
{
if (IsDBNull (i))
throw new InvalidOperationException("The value is null");
return new OracleString (GetString (i));
}
public object GetOracleValue (int i)
{
OciDefineHandle defineHandle = (OciDefineHandle) statement.Values [i];
switch (defineHandle.DataType) {
case OciDataType.Raw:
return GetOracleBinary (i);
case OciDataType.Date:
return GetOracleDateTime (i);
case OciDataType.Clob:
case OciDataType.Blob:
return GetOracleLob (i);
case OciDataType.Integer:
case OciDataType.Number:
case OciDataType.Float:
return GetOracleNumber (i);
case OciDataType.VarChar2:
case OciDataType.String:
case OciDataType.VarChar:
case OciDataType.Char:
case OciDataType.CharZ:
case OciDataType.OciString:
case OciDataType.LongVarChar:
case OciDataType.Long:
case OciDataType.RowIdDescriptor:
return GetOracleString (i);
default:
throw new NotImplementedException ();
}
}
public int GetOracleValues (object[] values)
{
int len = values.Length;
int count = statement.ColumnCount;
int retval = 0;
if (len > count)
retval = count;
else
retval = len;
for (int i = 0; i < retval; i += 1)
values [i] = GetOracleValue (i);
return retval;
}
[MonoTODO]
public OracleTimeSpan GetOracleTimeSpan (int i)
{
return new OracleTimeSpan (GetTimeSpan (i));
}
public int GetOrdinal (string name)
{
int i;
for (i = 0; i < statement.ColumnCount; i += 1) {
if (String.Compare (statement.GetParameter(i).GetName(), name, false) == 0)
return i;
}
for (i = 0; i < statement.ColumnCount; i += 1) {
if (String.Compare (statement.GetParameter(i).GetName(), name, true) == 0)
return i;
}
throw new IndexOutOfRangeException ();
}
private int GetRecordsAffected ()
{
if (recordsAffected == -1)
recordsAffected = statement.GetAttributeInt32 (OciAttributeType.RowCount, command.ErrorHandle);
return recordsAffected;
}
public DataTable GetSchemaTable ()
{
if (schemaTable.Rows != null && schemaTable.Rows.Count > 0)
return schemaTable;
dataTypeNames = new ArrayList ();
for (int i = 0; i < statement.ColumnCount; i += 1) {
DataRow row = schemaTable.NewRow ();
OciParameterDescriptor parameter = statement.GetParameter (i);
dataTypeNames.Add (parameter.GetDataTypeName ());
row ["ColumnName"] = parameter.GetName ();
row ["ColumnOrdinal"] = i + 1;
row ["ColumnSize"] = parameter.GetDataSize ();
row ["NumericPrecision"] = parameter.GetPrecision ();
row ["NumericScale"] = parameter.GetScale ();
string sDataTypeName = parameter.GetDataTypeName ();
row ["DataType"] = parameter.GetFieldType (sDataTypeName);
row ["AllowDBNull"] = parameter.GetIsNull ();
row ["BaseColumnName"] = parameter.GetName ();
row ["IsReadOnly"] = true;
schemaTable.Rows.Add (row);
}
return schemaTable;
}
public string GetString (int i)
{
object value = GetValue (i);
if (!(value is string))
throw new InvalidCastException ();
return (string) value;
}
public TimeSpan GetTimeSpan (int i)
{
object value = GetValue (i);
if (!(value is TimeSpan))
throw new InvalidCastException ();
return (TimeSpan) value;
}
public object GetValue (int i)
{
OciDefineHandle defineHandle = (OciDefineHandle) statement.Values [i];
if (defineHandle.IsNull)
return DBNull.Value;
switch (defineHandle.DataType) {
case OciDataType.Blob:
case OciDataType.Clob:
OracleLob lob = GetOracleLob (i);
object value = lob.Value;
lob.Close ();
return value;
default:
return defineHandle.GetValue ();
}
}
public int GetValues (object[] values)
{
int len = values.Length;
int count = statement.ColumnCount;
int retval = 0;
if (len > count)
retval = count;
else
retval = len;
for (int i = 0; i < retval; i += 1)
values [i] = GetValue (i);
return retval;
}
IEnumerator IEnumerable.GetEnumerator ()
{
return new DbEnumerator (this);
}
public bool IsDBNull (int i)
{
OciDefineHandle defineHandle = (OciDefineHandle) statement.Values [i];
return defineHandle.IsNull;
}
[MonoTODO]
public bool NextResult ()
{
// FIXME: get next result
return false;
}
public bool Read ()
{
bool retval = statement.Fetch ();
hasRows = retval;
return retval;
}
#endregion // Methods
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule
{
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
/// <summary>
/// Class of extension rule for Entry.Core.2008
/// </summary>
[Export(typeof(ExtensionRule))]
public class EntryCore2008 : ExtensionRule
{
/// <summary>
/// Gets Category property
/// </summary>
public override string Category
{
get
{
return "core";
}
}
/// <summary>
/// Gets rule name
/// </summary>
public override string Name
{
get
{
return "Entry.Core.2008";
}
}
/// <summary>
/// Gets rule description
/// </summary>
public override string Description
{
get
{
return "If the FC_KeepInContent attribute is not supplied in the mapping, the data service MUST function as if it were specified with a value of true.";
}
}
/// <summary>
/// Gets rule specification in OData document
/// </summary>
public override string SpecificationSection
{
get
{
return "2.2.3.7.2.1";
}
}
/// <summary>
/// Gets location of help information of the rule
/// </summary>
public override string HelpLink
{
get
{
return null;
}
}
/// <summary>
/// Gets the error message for validation failure
/// </summary>
public override string ErrorMessage
{
get
{
return this.Description;
}
}
/// <summary>
/// Gets the requirement level.
/// </summary>
public override RequirementLevel RequirementLevel
{
get
{
return RequirementLevel.Must;
}
}
/// <summary>
/// Gets the version
/// </summary>
public override ODataVersion? Version
{
get
{
return ODataVersion.V1_V2;
}
}
/// <summary>
/// Gets the payload type to which the rule applies.
/// </summary>
public override PayloadType? PayloadType
{
get
{
return RuleEngine.PayloadType.Entry;
}
}
/// <summary>
/// Gets the flag whether the rule requires metadata document
/// </summary>
public override bool? RequireMetadata
{
get
{
return true;
}
}
/// <summary>
/// Gets the offline context to which the rule applies
/// </summary>
public override bool? IsOfflineContext
{
get
{
return false;
}
}
/// <summary>
/// Gets the flag whether this rule applies to proected response or not
/// </summary>
public override bool? Projection
{
get
{
return false; ;
}
}
/// <summary>
/// Gets the payload format to which the rule applies.
/// </summary>
public override PayloadFormat? PayloadFormat
{
get
{
return RuleEngine.PayloadFormat.Atom;
}
}
/// <summary>
/// Verify Entry.Core.2008
/// </summary>
/// <param name="context">Service context</param>
/// <param name="info">out parameter to return violation information when rule fail</param>
/// <returns>true if rule passes; false otherwise</returns>
public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
bool? passed = null;
info = null;
// Load MetadataDocument into XMLDOM
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(context.MetadataDocument);
// Check to see if the type has base type
XmlNode entityTypeNode = xmlDoc.SelectSingleNode("//*[local-name()='EntityType' and @Name = '" + context.EntityTypeShortName + "']");
bool hasBaseType = false;
string baseTypeName = string.Empty;
if (entityTypeNode.Attributes["BaseType"] != null)
{
baseTypeName = entityTypeNode.Attributes["BaseType"].Value.Split('.').Last();
hasBaseType = true;
}
XmlNodeList baseTypePropertyNodeList = null;
int expectedCount = 0;
if (hasBaseType)
{
baseTypePropertyNodeList = xmlDoc.SelectNodes("//*[local-name()='EntityType' and @Name = '" + baseTypeName + "']/*[local-name()='Property']");
foreach (XmlNode node in baseTypePropertyNodeList)
{
if (node.Attributes["m:FC_KeepInContent"] != null)
{
if (node.Attributes["m:FC_KeepInContent"].Value.Equals("true", StringComparison.OrdinalIgnoreCase))
{
expectedCount++;
}
}
else
{
expectedCount++;
}
}
}
XmlNodeList propertyNodeList = xmlDoc.SelectNodes("//*[local-name()='EntityType' and @Name = '" + context.EntityTypeShortName + "']/*[local-name()='Property']");
foreach (XmlNode node in propertyNodeList)
{
if (node.Attributes["m:FC_KeepInContent"] != null)
{
if (node.Attributes["m:FC_KeepInContent"].Value.Equals("true", StringComparison.OrdinalIgnoreCase))
{
expectedCount++;
}
}
else
{
expectedCount++;
}
}
// Get the actual count
XElement entry;
context.ResponsePayload.TryToXElement(out entry);
var properties = entry.XPathSelectElements("//m:properties/*", ODataNamespaceManager.Instance);
// to exclude those expended from linked properties
var propertiesEcpanded = entry.XPathSelectElements("//atom:link//m:properties/*", ODataNamespaceManager.Instance);
int actualCount = properties.Count() - propertiesEcpanded.Count();
if (actualCount == expectedCount)
{
passed = true;
}
else
{
passed = false;
}
info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
return passed;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Monitoring.Metrics;
using Microsoft.WindowsAzure.Management.Monitoring.Metrics.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.WindowsAzure.Management.Monitoring.Metrics
{
internal partial class MetricSettingOperations : IServiceOperations<MetricsClient>, IMetricSettingOperations
{
/// <summary>
/// Initializes a new instance of the MetricSettingOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal MetricSettingOperations(MetricsClient client)
{
this._client = client;
}
private MetricsClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Monitoring.Metrics.MetricsClient.
/// </summary>
public MetricsClient Client
{
get { return this._client; }
}
/// <summary>
/// The Put Metric Settings operation creates or updates the metric
/// settings for the resource.
/// </summary>
/// <param name='parameters'>
/// Required. Metric settings to be created or updated.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> CreateOrUpdateAsync(MetricSettingsPutParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.MetricSetting == null)
{
throw new ArgumentNullException("parameters.MetricSetting");
}
if (parameters.MetricSetting.ResourceId == null)
{
throw new ArgumentNullException("parameters.MetricSetting.ResourceId");
}
if (parameters.MetricSetting.Value == null)
{
throw new ArgumentNullException("parameters.MetricSetting.Value");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/monitoring/metricsettings";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2013-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
requestDoc = new JObject();
requestDoc["ResourceId"] = parameters.MetricSetting.ResourceId;
if (parameters.MetricSetting.Namespace != null)
{
requestDoc["Namespace"] = parameters.MetricSetting.Namespace;
}
JObject valueValue = new JObject();
requestDoc["Value"] = valueValue;
if (parameters.MetricSetting.Value is AvailabilityMetricSettingValue)
{
valueValue["odata.type"] = parameters.MetricSetting.Value.GetType().FullName;
AvailabilityMetricSettingValue derived = ((AvailabilityMetricSettingValue)parameters.MetricSetting.Value);
if (derived.AvailableLocations != null)
{
if (derived.AvailableLocations is ILazyCollection == false || ((ILazyCollection)derived.AvailableLocations).IsInitialized)
{
JArray availableLocationsArray = new JArray();
foreach (NameConfig availableLocationsItem in derived.AvailableLocations)
{
JObject nameConfigValue = new JObject();
availableLocationsArray.Add(nameConfigValue);
if (availableLocationsItem.Name != null)
{
nameConfigValue["Name"] = availableLocationsItem.Name;
}
if (availableLocationsItem.DisplayName != null)
{
nameConfigValue["DisplayName"] = availableLocationsItem.DisplayName;
}
}
valueValue["AvailableLocations"] = availableLocationsArray;
}
}
if (derived.Endpoints != null)
{
if (derived.Endpoints is ILazyCollection == false || ((ILazyCollection)derived.Endpoints).IsInitialized)
{
JArray endpointsArray = new JArray();
foreach (EndpointConfig endpointsItem in derived.Endpoints)
{
JObject endpointConfigValue = new JObject();
endpointsArray.Add(endpointConfigValue);
if (endpointsItem.ConfigId != null)
{
endpointConfigValue["ConfigId"] = endpointsItem.ConfigId;
}
if (endpointsItem.Name != null)
{
endpointConfigValue["Name"] = endpointsItem.Name;
}
if (endpointsItem.Location != null)
{
endpointConfigValue["Location"] = endpointsItem.Location;
}
if (endpointsItem.Url != null)
{
endpointConfigValue["Url"] = endpointsItem.Url.AbsoluteUri;
}
}
valueValue["Endpoints"] = endpointsArray;
}
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AzureOperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
}
}
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>
/// The List Metric Settings operation lists the metric settings for
/// the resource.
/// </summary>
/// <param name='resourceId'>
/// Required. The id of the resource.
/// </param>
/// <param name='metricNamespace'>
/// Required. The namespace of the metrics.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The list metric settings operation response.
/// </returns>
public async Task<MetricSettingListResponse> ListAsync(string resourceId, string metricNamespace, CancellationToken cancellationToken)
{
// Validate
if (resourceId == null)
{
throw new ArgumentNullException("resourceId");
}
if (metricNamespace == null)
{
throw new ArgumentNullException("metricNamespace");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceId", resourceId);
tracingParameters.Add("metricNamespace", metricNamespace);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/monitoring/metricsettings";
List<string> queryParameters = new List<string>();
queryParameters.Add("resourceId=" + Uri.EscapeDataString(resourceId));
queryParameters.Add("namespace=" + Uri.EscapeDataString(metricNamespace));
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("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2013-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
MetricSettingListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new MetricSettingListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
MetricSettingCollection metricSettingCollectionInstance = new MetricSettingCollection();
result.MetricSettingCollection = metricSettingCollectionInstance;
JToken valueArray = responseDoc["Value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
MetricSetting metricSettingInstance = new MetricSetting();
metricSettingCollectionInstance.Value.Add(metricSettingInstance);
JToken resourceIdValue = valueValue["ResourceId"];
if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null)
{
string resourceIdInstance = ((string)resourceIdValue);
metricSettingInstance.ResourceId = resourceIdInstance;
}
JToken namespaceValue = valueValue["Namespace"];
if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
{
string namespaceInstance = ((string)namespaceValue);
metricSettingInstance.Namespace = namespaceInstance;
}
JToken valueValue2 = valueValue["Value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string typeName = ((string)valueValue2["odata.type"]);
if (typeName == "Microsoft.WindowsAzure.Management.Monitoring.Metrics.Models.AvailabilityMetricSettingValue")
{
AvailabilityMetricSettingValue availabilityMetricSettingValueInstance = new AvailabilityMetricSettingValue();
JToken availableLocationsArray = valueValue2["AvailableLocations"];
if (availableLocationsArray != null && availableLocationsArray.Type != JTokenType.Null)
{
foreach (JToken availableLocationsValue in ((JArray)availableLocationsArray))
{
NameConfig nameConfigInstance = new NameConfig();
availabilityMetricSettingValueInstance.AvailableLocations.Add(nameConfigInstance);
JToken nameValue = availableLocationsValue["Name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
nameConfigInstance.Name = nameInstance;
}
JToken displayNameValue = availableLocationsValue["DisplayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
nameConfigInstance.DisplayName = displayNameInstance;
}
}
}
JToken endpointsArray = valueValue2["Endpoints"];
if (endpointsArray != null && endpointsArray.Type != JTokenType.Null)
{
foreach (JToken endpointsValue in ((JArray)endpointsArray))
{
EndpointConfig endpointConfigInstance = new EndpointConfig();
availabilityMetricSettingValueInstance.Endpoints.Add(endpointConfigInstance);
JToken configIdValue = endpointsValue["ConfigId"];
if (configIdValue != null && configIdValue.Type != JTokenType.Null)
{
string configIdInstance = ((string)configIdValue);
endpointConfigInstance.ConfigId = configIdInstance;
}
JToken nameValue2 = endpointsValue["Name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
endpointConfigInstance.Name = nameInstance2;
}
JToken locationValue = endpointsValue["Location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
endpointConfigInstance.Location = locationInstance;
}
JToken urlValue = endpointsValue["Url"];
if (urlValue != null && urlValue.Type != JTokenType.Null)
{
Uri urlInstance = TypeConversion.TryParseUri(((string)urlValue));
endpointConfigInstance.Url = urlInstance;
}
}
}
metricSettingInstance.Value = availabilityMetricSettingValueInstance;
}
}
}
}
}
}
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();
}
}
}
}
}
| |
// 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 System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Thrift.Protocol.Entities;
using Thrift.Protocol.Utilities;
using Thrift.Transport;
namespace Thrift.Protocol
{
/// <summary>
/// JSON protocol implementation for thrift.
/// This is a full-featured protocol supporting Write and Read.
/// Please see the C++ class header for a detailed description of the
/// protocol's wire format.
/// Adapted from the Java version.
/// </summary>
// ReSharper disable once InconsistentNaming
public class TJsonProtocol : TProtocol
{
private const long Version = 1;
// Temporary buffer used by several methods
private readonly byte[] _tempBuffer = new byte[4];
// Current context that we are in
protected JSONBaseContext Context;
// Stack of nested contexts that we may be in
protected Stack<JSONBaseContext> ContextStack = new Stack<JSONBaseContext>();
// Reader that manages a 1-byte buffer
protected LookaheadReader Reader;
// Default encoding
protected Encoding Utf8Encoding = Encoding.UTF8;
/// <summary>
/// TJsonProtocol Constructor
/// </summary>
public TJsonProtocol(TTransport trans)
: base(trans)
{
Context = new JSONBaseContext(this);
Reader = new LookaheadReader(this);
}
/// <summary>
/// Push a new JSON context onto the stack.
/// </summary>
protected void PushContext(JSONBaseContext c)
{
ContextStack.Push(Context);
Context = c;
}
/// <summary>
/// Pop the last JSON context off the stack
/// </summary>
protected void PopContext()
{
Context = ContextStack.Pop();
}
/// <summary>
/// Read a byte that must match b[0]; otherwise an exception is thrown.
/// Marked protected to avoid synthetic accessor in JSONListContext.Read
/// and JSONPairContext.Read
/// </summary>
protected async Task ReadJsonSyntaxCharAsync(byte[] bytes, CancellationToken cancellationToken)
{
var ch = await Reader.ReadAsync(cancellationToken);
if (ch != bytes[0])
{
throw new TProtocolException(TProtocolException.INVALID_DATA, $"Unexpected character: {(char) ch}");
}
}
/// <summary>
/// Write the bytes in array buf as a JSON characters, escaping as needed
/// </summary>
private async Task WriteJsonStringAsync(byte[] bytes, CancellationToken cancellationToken)
{
await Context.WriteAsync(cancellationToken);
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
var len = bytes.Length;
for (var i = 0; i < len; i++)
{
if ((bytes[i] & 0x00FF) >= 0x30)
{
if (bytes[i] == TJSONProtocolConstants.Backslash[0])
{
await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken);
await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken);
}
else
{
await Trans.WriteAsync(bytes.ToArray(), i, 1, cancellationToken);
}
}
else
{
_tempBuffer[0] = TJSONProtocolConstants.JsonCharTable[bytes[i]];
if (_tempBuffer[0] == 1)
{
await Trans.WriteAsync(bytes, i, 1, cancellationToken);
}
else if (_tempBuffer[0] > 1)
{
await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken);
await Trans.WriteAsync(_tempBuffer, 0, 1, cancellationToken);
}
else
{
await Trans.WriteAsync(TJSONProtocolConstants.EscSequences, cancellationToken);
_tempBuffer[0] = TJSONProtocolHelper.ToHexChar((byte) (bytes[i] >> 4));
_tempBuffer[1] = TJSONProtocolHelper.ToHexChar(bytes[i]);
await Trans.WriteAsync(_tempBuffer, 0, 2, cancellationToken);
}
}
}
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
/// <summary>
/// Write out number as a JSON value. If the context dictates so, it will be
/// wrapped in quotes to output as a JSON string.
/// </summary>
private async Task WriteJsonIntegerAsync(long num, CancellationToken cancellationToken)
{
await Context.WriteAsync(cancellationToken);
var str = num.ToString();
var escapeNum = Context.EscapeNumbers();
if (escapeNum)
{
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
var bytes = Utf8Encoding.GetBytes(str);
await Trans.WriteAsync(bytes, cancellationToken);
if (escapeNum)
{
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
}
/// <summary>
/// Write out a double as a JSON value. If it is NaN or infinity or if the
/// context dictates escaping, Write out as JSON string.
/// </summary>
private async Task WriteJsonDoubleAsync(double num, CancellationToken cancellationToken)
{
await Context.WriteAsync(cancellationToken);
var str = num.ToString("G17", CultureInfo.InvariantCulture);
var special = false;
switch (str[0])
{
case 'N': // NaN
case 'I': // Infinity
special = true;
break;
case '-':
if (str[1] == 'I')
{
// -Infinity
special = true;
}
break;
}
var escapeNum = special || Context.EscapeNumbers();
if (escapeNum)
{
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
await Trans.WriteAsync(Utf8Encoding.GetBytes(str), cancellationToken);
if (escapeNum)
{
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
}
/// <summary>
/// Write out contents of byte array b as a JSON string with base-64 encoded
/// data
/// </summary>
private async Task WriteJsonBase64Async(byte[] bytes, CancellationToken cancellationToken)
{
await Context.WriteAsync(cancellationToken);
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
var len = bytes.Length;
var off = 0;
while (len >= 3)
{
// Encode 3 bytes at a time
TBase64Utils.Encode(bytes, off, 3, _tempBuffer, 0);
await Trans.WriteAsync(_tempBuffer, 0, 4, cancellationToken);
off += 3;
len -= 3;
}
if (len > 0)
{
// Encode remainder
TBase64Utils.Encode(bytes, off, len, _tempBuffer, 0);
await Trans.WriteAsync(_tempBuffer, 0, len + 1, cancellationToken);
}
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
private async Task WriteJsonObjectStartAsync(CancellationToken cancellationToken)
{
await Context.WriteAsync(cancellationToken);
await Trans.WriteAsync(TJSONProtocolConstants.LeftBrace, cancellationToken);
PushContext(new JSONPairContext(this));
}
private async Task WriteJsonObjectEndAsync(CancellationToken cancellationToken)
{
PopContext();
await Trans.WriteAsync(TJSONProtocolConstants.RightBrace, cancellationToken);
}
private async Task WriteJsonArrayStartAsync(CancellationToken cancellationToken)
{
await Context.WriteAsync(cancellationToken);
await Trans.WriteAsync(TJSONProtocolConstants.LeftBracket, cancellationToken);
PushContext(new JSONListContext(this));
}
private async Task WriteJsonArrayEndAsync(CancellationToken cancellationToken)
{
PopContext();
await Trans.WriteAsync(TJSONProtocolConstants.RightBracket, cancellationToken);
}
public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken)
{
await WriteJsonArrayStartAsync(cancellationToken);
await WriteJsonIntegerAsync(Version, cancellationToken);
var b = Utf8Encoding.GetBytes(message.Name);
await WriteJsonStringAsync(b, cancellationToken);
await WriteJsonIntegerAsync((long) message.Type, cancellationToken);
await WriteJsonIntegerAsync(message.SeqID, cancellationToken);
}
public override async Task WriteMessageEndAsync(CancellationToken cancellationToken)
{
await WriteJsonArrayEndAsync(cancellationToken);
}
public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken)
{
await WriteJsonObjectStartAsync(cancellationToken);
}
public override async Task WriteStructEndAsync(CancellationToken cancellationToken)
{
await WriteJsonObjectEndAsync(cancellationToken);
}
public override async Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken)
{
await WriteJsonIntegerAsync(field.ID, cancellationToken);
await WriteJsonObjectStartAsync(cancellationToken);
await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(field.Type), cancellationToken);
}
public override async Task WriteFieldEndAsync(CancellationToken cancellationToken)
{
await WriteJsonObjectEndAsync(cancellationToken);
}
public override async Task WriteFieldStopAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken)
{
await WriteJsonArrayStartAsync(cancellationToken);
await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(map.KeyType), cancellationToken);
await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(map.ValueType), cancellationToken);
await WriteJsonIntegerAsync(map.Count, cancellationToken);
await WriteJsonObjectStartAsync(cancellationToken);
}
public override async Task WriteMapEndAsync(CancellationToken cancellationToken)
{
await WriteJsonObjectEndAsync(cancellationToken);
await WriteJsonArrayEndAsync(cancellationToken);
}
public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken)
{
await WriteJsonArrayStartAsync(cancellationToken);
await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(list.ElementType), cancellationToken);
await WriteJsonIntegerAsync(list.Count, cancellationToken);
}
public override async Task WriteListEndAsync(CancellationToken cancellationToken)
{
await WriteJsonArrayEndAsync(cancellationToken);
}
public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken)
{
await WriteJsonArrayStartAsync(cancellationToken);
await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(set.ElementType), cancellationToken);
await WriteJsonIntegerAsync(set.Count, cancellationToken);
}
public override async Task WriteSetEndAsync(CancellationToken cancellationToken)
{
await WriteJsonArrayEndAsync(cancellationToken);
}
public override async Task WriteBoolAsync(bool b, CancellationToken cancellationToken)
{
await WriteJsonIntegerAsync(b ? 1 : 0, cancellationToken);
}
public override async Task WriteByteAsync(sbyte b, CancellationToken cancellationToken)
{
await WriteJsonIntegerAsync(b, cancellationToken);
}
public override async Task WriteI16Async(short i16, CancellationToken cancellationToken)
{
await WriteJsonIntegerAsync(i16, cancellationToken);
}
public override async Task WriteI32Async(int i32, CancellationToken cancellationToken)
{
await WriteJsonIntegerAsync(i32, cancellationToken);
}
public override async Task WriteI64Async(long i64, CancellationToken cancellationToken)
{
await WriteJsonIntegerAsync(i64, cancellationToken);
}
public override async Task WriteDoubleAsync(double d, CancellationToken cancellationToken)
{
await WriteJsonDoubleAsync(d, cancellationToken);
}
public override async Task WriteStringAsync(string s, CancellationToken cancellationToken)
{
var b = Utf8Encoding.GetBytes(s);
await WriteJsonStringAsync(b, cancellationToken);
}
public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken)
{
await WriteJsonBase64Async(bytes, cancellationToken);
}
/// <summary>
/// Read in a JSON string, unescaping as appropriate.. Skip Reading from the
/// context if skipContext is true.
/// </summary>
private async Task<byte[]> ReadJsonStringAsync(bool skipContext, CancellationToken cancellationToken)
{
using (var buffer = new MemoryStream())
{
var codeunits = new List<char>();
if (!skipContext)
{
await Context.ReadAsync(cancellationToken);
}
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken);
while (true)
{
var ch = await Reader.ReadAsync(cancellationToken);
if (ch == TJSONProtocolConstants.Quote[0])
{
break;
}
// escaped?
if (ch != TJSONProtocolConstants.EscSequences[0])
{
await buffer.WriteAsync(new[] {ch}, 0, 1, cancellationToken);
continue;
}
// distinguish between \uXXXX and \?
ch = await Reader.ReadAsync(cancellationToken);
if (ch != TJSONProtocolConstants.EscSequences[1]) // control chars like \n
{
var off = Array.IndexOf(TJSONProtocolConstants.EscapeChars, (char) ch);
if (off == -1)
{
throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected control char");
}
ch = TJSONProtocolConstants.EscapeCharValues[off];
await buffer.WriteAsync(new[] {ch}, 0, 1, cancellationToken);
continue;
}
// it's \uXXXX
await Trans.ReadAllAsync(_tempBuffer, 0, 4, cancellationToken);
var wch = (short) ((TJSONProtocolHelper.ToHexVal(_tempBuffer[0]) << 12) +
(TJSONProtocolHelper.ToHexVal(_tempBuffer[1]) << 8) +
(TJSONProtocolHelper.ToHexVal(_tempBuffer[2]) << 4) +
TJSONProtocolHelper.ToHexVal(_tempBuffer[3]));
if (char.IsHighSurrogate((char) wch))
{
if (codeunits.Count > 0)
{
throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected low surrogate char");
}
codeunits.Add((char) wch);
}
else if (char.IsLowSurrogate((char) wch))
{
if (codeunits.Count == 0)
{
throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected high surrogate char");
}
codeunits.Add((char) wch);
var tmp = Utf8Encoding.GetBytes(codeunits.ToArray());
await buffer.WriteAsync(tmp, 0, tmp.Length, cancellationToken);
codeunits.Clear();
}
else
{
var tmp = Utf8Encoding.GetBytes(new[] {(char) wch});
await buffer.WriteAsync(tmp, 0, tmp.Length, cancellationToken);
}
}
if (codeunits.Count > 0)
{
throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected low surrogate char");
}
return buffer.ToArray();
}
}
/// <summary>
/// Read in a sequence of characters that are all valid in JSON numbers. Does
/// not do a complete regex check to validate that this is actually a number.
/// </summary>
private async Task<string> ReadJsonNumericCharsAsync(CancellationToken cancellationToken)
{
var strbld = new StringBuilder();
while (true)
{
//TODO: workaround for primitive types with TJsonProtocol, think - how to rewrite into more easy form without exceptions
try
{
var ch = await Reader.PeekAsync(cancellationToken);
if (!TJSONProtocolHelper.IsJsonNumeric(ch))
{
break;
}
var c = (char)await Reader.ReadAsync(cancellationToken);
strbld.Append(c);
}
catch (TTransportException)
{
break;
}
}
return strbld.ToString();
}
/// <summary>
/// Read in a JSON number. If the context dictates, Read in enclosing quotes.
/// </summary>
private async Task<long> ReadJsonIntegerAsync(CancellationToken cancellationToken)
{
await Context.ReadAsync(cancellationToken);
if (Context.EscapeNumbers())
{
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
var str = await ReadJsonNumericCharsAsync(cancellationToken);
if (Context.EscapeNumbers())
{
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
try
{
return long.Parse(str);
}
catch (FormatException)
{
throw new TProtocolException(TProtocolException.INVALID_DATA, "Bad data encounted in numeric data");
}
}
/// <summary>
/// Read in a JSON double value. Throw if the value is not wrapped in quotes
/// when expected or if wrapped in quotes when not expected.
/// </summary>
private async Task<double> ReadJsonDoubleAsync(CancellationToken cancellationToken)
{
await Context.ReadAsync(cancellationToken);
if (await Reader.PeekAsync(cancellationToken) == TJSONProtocolConstants.Quote[0])
{
var arr = await ReadJsonStringAsync(true, cancellationToken);
var dub = double.Parse(Utf8Encoding.GetString(arr, 0, arr.Length), CultureInfo.InvariantCulture);
if (!Context.EscapeNumbers() && !double.IsNaN(dub) && !double.IsInfinity(dub))
{
// Throw exception -- we should not be in a string in this case
throw new TProtocolException(TProtocolException.INVALID_DATA, "Numeric data unexpectedly quoted");
}
return dub;
}
if (Context.EscapeNumbers())
{
// This will throw - we should have had a quote if escapeNum == true
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
try
{
return double.Parse(await ReadJsonNumericCharsAsync(cancellationToken), CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new TProtocolException(TProtocolException.INVALID_DATA, "Bad data encounted in numeric data");
}
}
/// <summary>
/// Read in a JSON string containing base-64 encoded data and decode it.
/// </summary>
private async Task<byte[]> ReadJsonBase64Async(CancellationToken cancellationToken)
{
var b = await ReadJsonStringAsync(false, cancellationToken);
var len = b.Length;
var off = 0;
var size = 0;
// reduce len to ignore fill bytes
while ((len > 0) && (b[len - 1] == '='))
{
--len;
}
// read & decode full byte triplets = 4 source bytes
while (len > 4)
{
// Decode 4 bytes at a time
TBase64Utils.Decode(b, off, 4, b, size); // NB: decoded in place
off += 4;
len -= 4;
size += 3;
}
// Don't decode if we hit the end or got a single leftover byte (invalid
// base64 but legal for skip of regular string exType)
if (len > 1)
{
// Decode remainder
TBase64Utils.Decode(b, off, len, b, size); // NB: decoded in place
size += len - 1;
}
// Sadly we must copy the byte[] (any way around this?)
var result = new byte[size];
Array.Copy(b, 0, result, 0, size);
return result;
}
private async Task ReadJsonObjectStartAsync(CancellationToken cancellationToken)
{
await Context.ReadAsync(cancellationToken);
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.LeftBrace, cancellationToken);
PushContext(new JSONPairContext(this));
}
private async Task ReadJsonObjectEndAsync(CancellationToken cancellationToken)
{
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.RightBrace, cancellationToken);
PopContext();
}
private async Task ReadJsonArrayStartAsync(CancellationToken cancellationToken)
{
await Context.ReadAsync(cancellationToken);
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.LeftBracket, cancellationToken);
PushContext(new JSONListContext(this));
}
private async Task ReadJsonArrayEndAsync(CancellationToken cancellationToken)
{
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.RightBracket, cancellationToken);
PopContext();
}
public override async Task<TMessage> ReadMessageBeginAsync(CancellationToken cancellationToken)
{
var message = new TMessage();
await ReadJsonArrayStartAsync(cancellationToken);
if (await ReadJsonIntegerAsync(cancellationToken) != Version)
{
throw new TProtocolException(TProtocolException.BAD_VERSION, "Message contained bad version.");
}
var buf = await ReadJsonStringAsync(false, cancellationToken);
message.Name = Utf8Encoding.GetString(buf, 0, buf.Length);
message.Type = (TMessageType) await ReadJsonIntegerAsync(cancellationToken);
message.SeqID = (int) await ReadJsonIntegerAsync(cancellationToken);
return message;
}
public override async Task ReadMessageEndAsync(CancellationToken cancellationToken)
{
await ReadJsonArrayEndAsync(cancellationToken);
}
public override async Task<TStruct> ReadStructBeginAsync(CancellationToken cancellationToken)
{
await ReadJsonObjectStartAsync(cancellationToken);
return new TStruct();
}
public override async Task ReadStructEndAsync(CancellationToken cancellationToken)
{
await ReadJsonObjectEndAsync(cancellationToken);
}
public override async Task<TField> ReadFieldBeginAsync(CancellationToken cancellationToken)
{
var field = new TField();
var ch = await Reader.PeekAsync(cancellationToken);
if (ch == TJSONProtocolConstants.RightBrace[0])
{
field.Type = TType.Stop;
}
else
{
field.ID = (short) await ReadJsonIntegerAsync(cancellationToken);
await ReadJsonObjectStartAsync(cancellationToken);
field.Type = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
}
return field;
}
public override async Task ReadFieldEndAsync(CancellationToken cancellationToken)
{
await ReadJsonObjectEndAsync(cancellationToken);
}
public override async Task<TMap> ReadMapBeginAsync(CancellationToken cancellationToken)
{
var map = new TMap();
await ReadJsonArrayStartAsync(cancellationToken);
map.KeyType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
map.ValueType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
map.Count = (int) await ReadJsonIntegerAsync(cancellationToken);
await ReadJsonObjectStartAsync(cancellationToken);
return map;
}
public override async Task ReadMapEndAsync(CancellationToken cancellationToken)
{
await ReadJsonObjectEndAsync(cancellationToken);
await ReadJsonArrayEndAsync(cancellationToken);
}
public override async Task<TList> ReadListBeginAsync(CancellationToken cancellationToken)
{
var list = new TList();
await ReadJsonArrayStartAsync(cancellationToken);
list.ElementType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
list.Count = (int) await ReadJsonIntegerAsync(cancellationToken);
return list;
}
public override async Task ReadListEndAsync(CancellationToken cancellationToken)
{
await ReadJsonArrayEndAsync(cancellationToken);
}
public override async Task<TSet> ReadSetBeginAsync(CancellationToken cancellationToken)
{
var set = new TSet();
await ReadJsonArrayStartAsync(cancellationToken);
set.ElementType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
set.Count = (int) await ReadJsonIntegerAsync(cancellationToken);
return set;
}
public override async Task ReadSetEndAsync(CancellationToken cancellationToken)
{
await ReadJsonArrayEndAsync(cancellationToken);
}
public override async Task<bool> ReadBoolAsync(CancellationToken cancellationToken)
{
return await ReadJsonIntegerAsync(cancellationToken) != 0;
}
public override async Task<sbyte> ReadByteAsync(CancellationToken cancellationToken)
{
return (sbyte) await ReadJsonIntegerAsync(cancellationToken);
}
public override async Task<short> ReadI16Async(CancellationToken cancellationToken)
{
return (short) await ReadJsonIntegerAsync(cancellationToken);
}
public override async Task<int> ReadI32Async(CancellationToken cancellationToken)
{
return (int) await ReadJsonIntegerAsync(cancellationToken);
}
public override async Task<long> ReadI64Async(CancellationToken cancellationToken)
{
return await ReadJsonIntegerAsync(cancellationToken);
}
public override async Task<double> ReadDoubleAsync(CancellationToken cancellationToken)
{
return await ReadJsonDoubleAsync(cancellationToken);
}
public override async Task<string> ReadStringAsync(CancellationToken cancellationToken)
{
var buf = await ReadJsonStringAsync(false, cancellationToken);
return Utf8Encoding.GetString(buf, 0, buf.Length);
}
public override async Task<byte[]> ReadBinaryAsync(CancellationToken cancellationToken)
{
return await ReadJsonBase64Async(cancellationToken);
}
/// <summary>
/// Factory for JSON protocol objects
/// </summary>
public class Factory : TProtocolFactory
{
public override TProtocol GetProtocol(TTransport trans)
{
return new TJsonProtocol(trans);
}
}
/// <summary>
/// Base class for tracking JSON contexts that may require
/// inserting/Reading additional JSON syntax characters
/// This base context does nothing.
/// </summary>
protected class JSONBaseContext
{
protected TJsonProtocol Proto;
public JSONBaseContext(TJsonProtocol proto)
{
Proto = proto;
}
public virtual async Task WriteAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public virtual async Task ReadAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public virtual bool EscapeNumbers()
{
return false;
}
}
/// <summary>
/// Context for JSON lists. Will insert/Read commas before each item except
/// for the first one
/// </summary>
protected class JSONListContext : JSONBaseContext
{
private bool _first = true;
public JSONListContext(TJsonProtocol protocol)
: base(protocol)
{
}
public override async Task WriteAsync(CancellationToken cancellationToken)
{
if (_first)
{
_first = false;
}
else
{
await Proto.Trans.WriteAsync(TJSONProtocolConstants.Comma, cancellationToken);
}
}
public override async Task ReadAsync(CancellationToken cancellationToken)
{
if (_first)
{
_first = false;
}
else
{
await Proto.ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Comma, cancellationToken);
}
}
}
/// <summary>
/// Context for JSON records. Will insert/Read colons before the value portion
/// of each record pair, and commas before each key except the first. In
/// addition, will indicate that numbers in the key position need to be
/// escaped in quotes (since JSON keys must be strings).
/// </summary>
// ReSharper disable once InconsistentNaming
protected class JSONPairContext : JSONBaseContext
{
private bool _colon = true;
private bool _first = true;
public JSONPairContext(TJsonProtocol proto)
: base(proto)
{
}
public override async Task WriteAsync(CancellationToken cancellationToken)
{
if (_first)
{
_first = false;
_colon = true;
}
else
{
await Proto.Trans.WriteAsync(_colon ? TJSONProtocolConstants.Colon : TJSONProtocolConstants.Comma, cancellationToken);
_colon = !_colon;
}
}
public override async Task ReadAsync(CancellationToken cancellationToken)
{
if (_first)
{
_first = false;
_colon = true;
}
else
{
await Proto.ReadJsonSyntaxCharAsync(_colon ? TJSONProtocolConstants.Colon : TJSONProtocolConstants.Comma, cancellationToken);
_colon = !_colon;
}
}
public override bool EscapeNumbers()
{
return _colon;
}
}
/// <summary>
/// Holds up to one byte from the transport
/// </summary>
protected class LookaheadReader
{
private readonly byte[] _data = new byte[1];
private bool _hasData;
protected TJsonProtocol Proto;
public LookaheadReader(TJsonProtocol proto)
{
Proto = proto;
}
/// <summary>
/// Return and consume the next byte to be Read, either taking it from the
/// data buffer if present or getting it from the transport otherwise.
/// </summary>
public async Task<byte> ReadAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<byte>(cancellationToken);
}
if (_hasData)
{
_hasData = false;
}
else
{
// find more easy way to avoid exception on reading primitive types
await Proto.Trans.ReadAllAsync(_data, 0, 1, cancellationToken);
}
return _data[0];
}
/// <summary>
/// Return the next byte to be Read without consuming, filling the data
/// buffer if it has not been filled alReady.
/// </summary>
public async Task<byte> PeekAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<byte>(cancellationToken);
}
if (!_hasData)
{
// find more easy way to avoid exception on reading primitive types
await Proto.Trans.ReadAllAsync(_data, 0, 1, cancellationToken);
}
_hasData = true;
return _data[0];
}
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Account Feed
///<para>SObject Name: AccountFeed</para>
///<para>Custom Object: False</para>
///</summary>
public class SfAccountFeed : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "AccountFeed"; }
}
///<summary>
/// Feed Item ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Parent ID
/// <para>Name: ParentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "parentId")]
[Updateable(false), Createable(false)]
public string ParentId { get; set; }
///<summary>
/// ReferenceTo: Account
/// <para>RelationshipName: Parent</para>
///</summary>
[JsonProperty(PropertyName = "parent")]
[Updateable(false), Createable(false)]
public SfAccount Parent { get; set; }
///<summary>
/// Feed Item Type
/// <para>Name: Type</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "type")]
[Updateable(false), Createable(false)]
public string Type { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Comment Count
/// <para>Name: CommentCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "commentCount")]
[Updateable(false), Createable(false)]
public int? CommentCount { get; set; }
///<summary>
/// Like Count
/// <para>Name: LikeCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "likeCount")]
[Updateable(false), Createable(false)]
public int? LikeCount { get; set; }
///<summary>
/// Title
/// <para>Name: Title</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "title")]
[Updateable(false), Createable(false)]
public string Title { get; set; }
///<summary>
/// Body
/// <para>Name: Body</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "body")]
[Updateable(false), Createable(false)]
public string Body { get; set; }
///<summary>
/// Link Url
/// <para>Name: LinkUrl</para>
/// <para>SF Type: url</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "linkUrl")]
[Updateable(false), Createable(false)]
public string LinkUrl { get; set; }
///<summary>
/// Is Rich Text
/// <para>Name: IsRichText</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isRichText")]
[Updateable(false), Createable(false)]
public bool? IsRichText { get; set; }
///<summary>
/// Related Record ID
/// <para>Name: RelatedRecordId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "relatedRecordId")]
[Updateable(false), Createable(false)]
public string RelatedRecordId { get; set; }
///<summary>
/// InsertedBy ID
/// <para>Name: InsertedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "insertedById")]
[Updateable(false), Createable(false)]
public string InsertedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: InsertedBy</para>
///</summary>
[JsonProperty(PropertyName = "insertedBy")]
[Updateable(false), Createable(false)]
public SfUser InsertedBy { get; set; }
///<summary>
/// Best Comment ID
/// <para>Name: BestCommentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestCommentId")]
[Updateable(false), Createable(false)]
public string BestCommentId { get; set; }
///<summary>
/// ReferenceTo: FeedComment
/// <para>RelationshipName: BestComment</para>
///</summary>
[JsonProperty(PropertyName = "bestComment")]
[Updateable(false), Createable(false)]
public SfFeedComment BestComment { get; set; }
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace CodeSight.Server.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System.Linq;
using Microsoft.CodeAnalysis;
using Stratis.SmartContracts.CLR;
using Stratis.SmartContracts.CLR.Compilation;
using Stratis.SmartContracts.CLR.Validation;
using Stratis.SmartContracts.CLR.Validation.Validators;
using Stratis.SmartContracts.CLR.Validation.Validators.Instruction;
using Stratis.SmartContracts.CLR.Validation.Validators.Method;
using Stratis.SmartContracts.CLR.Validation.Validators.Type;
using Xunit;
namespace Stratis.Bitcoin.Features.SmartContracts.Tests
{
/// <summary>
/// In the long run, it would be great if there is a way for us to run through all possible types and methods
/// in the system namespace and see how they are evaluated. Depending on what we find out we may have to change our algo.
/// </summary>
public class DeterminismValidationTest
{
private const string TestString = @"using System;
using Stratis.SmartContracts;
[References]
public class Test : SmartContract
{
public Test(ISmartContractState state)
: base(state) {}
public void TestMethod()
{
[CodeToExecute]
}
}";
private const string ReplaceReferencesString = "[References]";
private const string ReplaceCodeString = "[CodeToExecute]";
private readonly ISmartContractValidator validator = new SmartContractValidator();
#region Action
[Fact]
public void Validate_Determinism_ActionAllowed()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, @"var test = new Action(() =>
{
int insideAction = 5 + 6;
});
test();").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
[Fact]
public void Validate_Determinism_ValidateActionDisallowed()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, @"var test = new Action(() =>
{
var insideAction = DateTime.Now;
});
test();").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion
#region Activator
[Fact]
public void Validate_Determinism_ActivatorNotAllowed()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, @"Address ts = System.Activator.CreateInstance<Address>();").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
Assert.Single(result.Errors);
Assert.IsAssignableFrom<WhitelistValidator.WhitelistValidationResult>(result.Errors.Single());
}
#endregion
#region Anonymous Classes
[Fact]
public void Validate_Determinism_AnonymousClassFloats()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, @"var test = new
{
Prop1 = 6.8
};").Replace(ReplaceReferencesString, "");
byte[] assemblyBytes = ContractCompiler.Compile(adjustedSource).Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
[Fact]
public void ValidateAnonymousClassesDisallowed()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, @"var test = new
{
Test = ""Stratis""
};").Replace(ReplaceReferencesString, "");
byte[] assemblyBytes = ContractCompiler.Compile(adjustedSource).Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion
#region AppDomain
[Fact]
public void Validate_Determinism_AppDomain()
{
// AppDomain should not be available
// We do not compile contracts with a reference to System.Runtime.Extensions
string adjustedSource = TestString.Replace(ReplaceCodeString, @"var test = AppDomain.CurrentDomain; var test2 = test.Id;").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.False(compilationResult.Success);
}
#endregion
#region Async
[Fact]
public void Validate_Determinism_Async()
{
string adjustedSource = @"using System;
using Stratis.SmartContracts;
using System.Threading.Tasks;
public class Test : SmartContract
{
public Test(ISmartContractState state)
: base(state) {}
public async void Bid()
{
await Task.Run(job);
}
public async Task job()
{
int w = 9;
}
}";
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion
#region Arrays
/*
* The compiler handles arrays differently when they're initialised with less
* than 2 or more than 2 elements.
*
* In the case where it's more than 2 items it adds a <PrivateImplementationDetails> type to the module.
*
* We test for both cases below.
*/
[Fact]
public void Validate_Determinism_Passes_ArrayConstruction_MoreThan2()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, @"var test = new int[]{2,2,3};").Replace(ReplaceReferencesString, "");
byte[] assemblyBytes = ContractCompiler.Compile(adjustedSource).Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.True(result.IsValid);
}
[Fact]
public void Validate_Determinism_Passes_ArrayConstruction_LessThan2()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, @"var test = new int[]{10167};").Replace(ReplaceReferencesString, "");
byte[] assemblyBytes = ContractCompiler.Compile(adjustedSource).Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.True(result.IsValid);
}
[Fact]
public void Validate_Determinism_Passes_Array_AllowedMembers()
{
string code = @"
var test = new int[25];
var test2 = new int[25];
test[0] = 123;
int ret = test[0];
int len = test.Length;
Array.Resize(ref test, 50);
Array.Copy(test, test2, len);";
string adjustedSource = TestString.Replace(ReplaceCodeString,code).Replace(ReplaceReferencesString, "");
byte[] assemblyBytes = ContractCompiler.Compile(adjustedSource).Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.True(result.IsValid);
}
[Fact]
public void Validate_Determinism_Fails_Array_Clone()
{
string code = @"
var test = new int[25];
var ret = test.Clone();";
string adjustedSource = TestString.Replace(ReplaceCodeString, code).Replace(ReplaceReferencesString, "");
byte[] assemblyBytes = ContractCompiler.Compile(adjustedSource).Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
[Fact]
public void Validate_Determinism_Fails_MultiDimensional_Arrays()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, @"var test = new int[50,50];").Replace(ReplaceReferencesString, "");
byte[] assemblyBytes = ContractCompiler.Compile(adjustedSource).Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion
#region BitConverter
[Fact]
public void Validate_Determinism_BitConverter()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, @"var test = BitConverter.IsLittleEndian;").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
Assert.Single(result.Errors);
Assert.IsAssignableFrom<WhitelistValidator.WhitelistValidationResult>(result.Errors.Single());
}
#endregion
#region DateTime
[Fact]
public void Validate_Determinism_DateTimeNow()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, "var test = DateTime.Now;").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
[Fact]
public void Validate_Determinism_DateTimeToday()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, "var test = DateTime.Today;").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion
#region Decimal and Floats
[Fact]
public void Validate_Determinism_Floats()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, "float test = (float) 3.5; test = test + 1;").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
Assert.Contains(result.Errors, e => e is FloatValidator.FloatValidationResult);
}
[Fact]
public void Validate_Determinism_Double()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, "double test = 3.5;").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource, OptimizationLevel.Debug);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
Assert.Contains(result.Errors, e => e is FloatValidator.FloatValidationResult);
}
[Fact]
public void Validate_Determinism_Decimal()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, "decimal test = (decimal) 3.5; test = test / 2;").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
Assert.True(result.Errors.All(e => e is WhitelistValidator.WhitelistValidationResult));
Assert.True(result.Errors.All(e => e.Message.Contains("Decimal")));
}
[Fact]
public void Validate_Determinism_DecimalParse()
{
string adjustedSource = TestString.Replace(ReplaceCodeString,
"decimal largerAmount = decimal.Parse(\"1\");")
.Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
Assert.True(result.Errors.All(e => e is WhitelistValidator.WhitelistValidationResult));
Assert.True(result.Errors.All(e => e.Message.Contains("Decimal")));
}
#endregion
#region Dynamic
[Fact]
public void Validate_Determinism_DynamicTypeAllowed()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, "dynamic test = 56; test = \"aString\"; ").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.True(result.IsValid);
}
#endregion
#region Environment
[Fact]
public void Validate_Determinism_Environment()
{
// Environment should not be available
// We do not compile contracts with a reference to System.Runtime.Extensions
string adjustedSource = TestString.Replace(ReplaceCodeString, "int test = Environment.TickCount;").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.False(compilationResult.Success);
}
#endregion
#region Exceptions
[Fact]
public void Validate_Determinism_Exceptions()
{
// Note that NotFiniteNumberException is commented out - it causes an issue as it deals with floats
string adjustedSource = TestString.Replace(ReplaceCodeString, @"var test = new AccessViolationException();
var test2 = new AggregateException();
var test4 = new ApplicationException();
var test5 = new ArgumentException();
var test6 = new ArgumentNullException();
var test7 = new ArgumentOutOfRangeException();
var test8 = new ArithmeticException();
var test9 = new ArrayTypeMismatchException();
var test10 = new BadImageFormatException();
var test13 = new DataMisalignedException();
var test14 = new DivideByZeroException();
var test15 = new DllNotFoundException();
var test16 = new DuplicateWaitObjectException();
var test17 = new EntryPointNotFoundException();
var test19 = new FieldAccessException();
var test20 = new FormatException();
var test21 = new IndexOutOfRangeException();
var test22 = new InsufficientExecutionStackException();
var test23 = new InsufficientMemoryException();
var test24 = new InvalidCastException();
var test25 = new InvalidOperationException();
var test26 = new InvalidProgramException();
var test27 = new InvalidTimeZoneException();
var test28 = new MemberAccessException();
var test29 = new MethodAccessException();
var test30 = new MissingFieldException();
var test31 = new MissingMemberException();
var test32 = new MissingMethodException();
var test33 = new MulticastNotSupportedException();
var test35 = new NotImplementedException();
var test36 = new NotSupportedException();
var test37 = new NullReferenceException();
var test38 = new ObjectDisposedException(""test"");
var test39 = new OperationCanceledException();
var test40 = new OutOfMemoryException();
var test41 = new OverflowException();
var test42 = new PlatformNotSupportedException();
var test43 = new RankException();
var test44 = new StackOverflowException();
var test45 = new SystemException();
var test46 = new TimeoutException();
var test47 = new TimeZoneNotFoundException();
var test48 = new TypeAccessException();
var test49 = new TypeInitializationException(""test"", new Exception());
var test50 = new TypeLoadException();
var test51 = new TypeUnloadedException();
var test52 = new UnauthorizedAccessException();"
).Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion Exceptions
#region GetType
[Fact]
public void Validate_Determinism_GetType()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, "var type = GetType();").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion
#region Generics
[Fact]
public void Validate_Determinism_GenericMethod()
{
string adjustedSource = @"using System;
using Stratis.SmartContracts;
public class Test : SmartContract
{
public Test(ISmartContractState state)
: base(state) {}
public T TestMethod<T>(int param)
{
return default(T);
}
}";
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
Assert.Single(result.Errors);
Assert.True(result.Errors.First() is GenericMethodValidator.GenericMethodValidationResult);
}
[Fact]
public void Validate_Determinism_GenericClass()
{
string adjustedSource = @"using System;
using Stratis.SmartContracts;
public class Test<T> : SmartContract
{
public Test(ISmartContractState state)
: base(state) {}
public T TestMethod(int param)
{
return default(T);
}
}";
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
Assert.Single(result.Errors);
Assert.True(result.Errors.First() is GenericTypeValidator.GenericTypeValidationResult);
}
#endregion
#region GetHashCode
[Fact]
public void Validate_Determinism_GetHashCode()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, "int hashCode = GetHashCode();").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
[Fact]
public void Validate_Determinism_GetHashCode_Overridden()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, @"
}
public override int GetHashCode()
{
return base.GetHashCode();
").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion
#region Globalisation
[Fact]
public void Validate_Determinism_Globalisation()
{
string adjustedSource = TestString.Replace(ReplaceCodeString,
"var r = System.Globalization.CultureInfo.CurrentCulture;")
.Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion
#region IntPtr
[Fact]
public void Validate_Determinism_IntPtr_Fails()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, "var test = new IntPtr(0);").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion
#region Inheritance
// It's not necessarily a requirement that contract inheritance isn't allowed in the long run,
// but this test allows us to see the currently expected functionality and track changes.
[Fact]
public void Validate_Determinism_Inheritance_Fails()
{
ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/Inheritance.cs");
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion
#region KnownBadMethodCall
[Fact]
public void Validate_Determinism_KnownBadMethodCall()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, @"var floor = System.Math.Floor(12D);").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion
#region Method Paramaters
[Fact]
public void Validate_Determinism_AllowedMethodParams()
{
string adjustedSource = @"using System;
using Stratis.SmartContracts;
public class Test : SmartContract
{
public Test(ISmartContractState state)
: base(state) {}
public void Bool(bool param)
{
}
public void Byte(byte param)
{
}
public void ByteArray(byte[] param)
{
}
public void Char(char param)
{
}
public void String(string param)
{
}
public void Int32(int param)
{
}
public void UInt32(uint param)
{
}
public void UInt64(ulong param)
{
}
public void Int64(long param)
{
}
public void Address1(Address param)
{
}
}";
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.True(result.IsValid);
}
[Fact]
public void Validate_Determinism_DisallowedMethodParams()
{
string adjustedSource = @"using System;
using Stratis.SmartContracts;
public class Test : SmartContract
{
public Test(ISmartContractState state)
: base(state) {}
public void DateTime1(DateTime param)
{
}
public void F(float param)
{
}
}";
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
Assert.Equal(2, result.Errors.Count());
Assert.True(result.Errors.All(e => e is MethodParamValidator.MethodParamValidationResult));
Assert.Contains(result.Errors, e => e.Message.Contains("System.DateTime"));
Assert.Contains(result.Errors, e => e.Message.Contains("System.Single"));
}
[Fact]
public void Validate_Determinism_MethodParams_Private()
{
string adjustedSource = @"using System;
using Stratis.SmartContracts;
public class Test : SmartContract
{
public Test(ISmartContractState state)
: base(state) {}
private void PrivateStruct(TestStruct test)
{
}
private void PrivateIntArray(int[] test)
{
}
public void PublicIntArray(int[] test)
{
}
public void PublicStruct(TestStruct test)
{
}
internal void InternalStruct(TestStruct test)
{
}
public struct TestStruct
{
public int TestInt;
}
}";
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource, OptimizationLevel.Debug);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
Assert.Equal(2, result.Errors.Count());
Assert.Contains("PublicIntArray", result.Errors.ElementAt(0).Message);
Assert.Contains("PublicStruct", result.Errors.ElementAt(1).Message);
}
#endregion
#region Nullable
[Fact]
public void Validate_Determinism_Nullable_Fails()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, "int? test = null;").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource, OptimizationLevel.Debug);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion
#region Recursion
[Fact]
public void Validate_Determinism_Recursion()
{
string source = @"
using Stratis.SmartContracts;
public class RecursionTest : SmartContract
{
public RecursionTest(ISmartContractState smartContractState)
: base(smartContractState)
{
}
public void Bid()
{
Job(5);
}
public void Job(int index)
{
if (index > 0)
Job(index - 1);
}
}";
ContractCompilationResult compilationResult = ContractCompiler.Compile(source);
Assert.True(compilationResult.Success);
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(compilationResult.Compilation).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.True(result.IsValid);
}
#endregion
#region SimpleContract
[Fact]
public void Validate_Determinism_SimpleContract()
{
ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/Token.cs");
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.True(result.IsValid);
}
#endregion
#region TaskAwaiter
[Fact]
public void Validate_Determinism_TaskAwaiter()
{
string adjustedSource = TestString.Replace(ReplaceCodeString,
"var r = new System.Runtime.CompilerServices.TaskAwaiter();")
.Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource, OptimizationLevel.Debug);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion
#region TryCatch
[Fact]
public void Validate_Determinism_TryCatch()
{
ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/TryCatch.cs");
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
#endregion
[Fact(Skip = "This test fails as it involves compilation of multiple classes, which is a format validation issue, not a determinism one")]
public void Validate_Determinism_ExtensionMethods()
{
string adjustedSource = TestString.Replace(ReplaceCodeString, "\"testString\".Test();").Replace(ReplaceReferencesString, "");
adjustedSource += @"public static class Extension
{
public static void Test(this string str)
{
var test = DateTime.Now;
}
}";
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.False(result.IsValid);
}
[Fact]
public void Validate_Determinism_StringIteration()
{
string adjustedSource = TestString.Replace(ReplaceCodeString,
@"int randomNumber = 0;
foreach (byte c in ""Abcdefgh"")
{
randomNumber += c;
}").Replace(ReplaceReferencesString, "");
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.True(result.IsValid);
}
[Fact]
public void Validate_ByteArray_Conversion()
{
ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/ByteArrayConversion.cs");
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition moduleDefinition = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
SmartContractValidationResult result = this.validator.Validate(moduleDefinition.ModuleDefinition);
Assert.True(result.IsValid);
}
[Fact]
public void Validate_Determinism_TwoTypes_Valid()
{
var adjustedSource = @"
using System;
using Stratis.SmartContracts;
public class Test : SmartContract
{
public Test(ISmartContractState state) : base(state) {}
}
public class Test2 {
}
";
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition decomp = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
var result = this.validator.Validate(decomp.ModuleDefinition);
Assert.True(result.IsValid);
}
[Fact]
public void Validate_Determinism_TwoTypes_Invalid()
{
var adjustedSource = @"
using System;
using Stratis.SmartContracts;
public class Test : SmartContract
{
public Test(ISmartContractState state) : base(state) {}
}
public class Test2 {
public Test2() {
var dt = DateTime.Now;
}
}
";
ContractCompilationResult compilationResult = ContractCompiler.Compile(adjustedSource);
Assert.True(compilationResult.Success);
byte[] assemblyBytes = compilationResult.Compilation;
IContractModuleDefinition decomp = ContractDecompiler.GetModuleDefinition(assemblyBytes).Value;
var result = this.validator.Validate(decomp.ModuleDefinition);
Assert.False(result.IsValid);
Assert.NotEmpty(result.Errors);
}
}
}
| |
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 SL.WebApi.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.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
/*
* Clas for various methods and utility constants.
*/
class M {
internal const int SSLv20 = 0x0200;
internal const int SSLv30 = 0x0300;
internal const int TLSv10 = 0x0301;
internal const int TLSv11 = 0x0302;
internal const int TLSv12 = 0x0303;
internal const int CHANGE_CIPHER_SPEC = 20;
internal const int ALERT = 21;
internal const int HANDSHAKE = 22;
internal const int APPLICATION = 23;
internal const int HELLO_REQUEST = 0;
internal const int CLIENT_HELLO = 1;
internal const int SERVER_HELLO = 2;
internal const int CERTIFICATE = 11;
internal const int SERVER_KEY_EXCHANGE = 12;
internal const int CERTIFICATE_REQUEST = 13;
internal const int SERVER_HELLO_DONE = 14;
internal const int CERTIFICATE_VERIFY = 15;
internal const int CLIENT_KEY_EXCHANGE = 16;
internal const int FINISHED = 20;
internal const int TLS_EMPTY_RENEGOTIATION_INFO_SCSV = 0x00FF;
internal const int TLS_FALLBACK_SCSV = 0x5600;
/* From RFC 5246 */
internal const int EXT_SIGNATURE_ALGORITHMS = 0x000D;
/* From RFC 6066 */
internal const int EXT_SERVER_NAME = 0x0000;
internal const int EXT_MAX_FRAGMENT_LENGTH = 0x0001;
internal const int EXT_CLIENT_CERTIFICATE_URL = 0x0002;
internal const int EXT_TRUSTED_CA_KEYS = 0x0003;
internal const int EXT_TRUNCATED_HMAC = 0x0004;
internal const int EXT_STATUS_REQUEST = 0x0005;
/* From RFC 4492 */
internal const int EXT_SUPPORTED_CURVES = 0x000A;
internal const int EXT_SUPPORTED_EC_POINTS = 0x000B;
/* From RFC 5746 */
internal const int EXT_RENEGOTIATION_INFO = 0xFF01;
internal static void Enc16be(int val, byte[] buf, int off)
{
buf[off] = (byte)(val >> 8);
buf[off + 1] = (byte)val;
}
internal static void Enc24be(int val, byte[] buf, int off)
{
buf[off] = (byte)(val >> 16);
buf[off + 1] = (byte)(val >> 8);
buf[off + 2] = (byte)val;
}
internal static void Enc32be(int val, byte[] buf, int off)
{
buf[off] = (byte)(val >> 24);
buf[off + 1] = (byte)(val >> 16);
buf[off + 2] = (byte)(val >> 8);
buf[off + 3] = (byte)val;
}
internal static int Dec16be(byte[] buf, int off)
{
return ((int)buf[off] << 8)
| (int)buf[off + 1];
}
internal static int Dec24be(byte[] buf, int off)
{
return ((int)buf[off] << 16)
| ((int)buf[off + 1] << 8)
| (int)buf[off + 2];
}
internal static uint Dec32be(byte[] buf, int off)
{
return ((uint)buf[off] << 24)
| ((uint)buf[off + 1] << 16)
| ((uint)buf[off + 2] << 8)
| (uint)buf[off + 3];
}
internal static void ReadFully(Stream s, byte[] buf)
{
ReadFully(s, buf, 0, buf.Length);
}
internal static void ReadFully(Stream s, byte[] buf, int off, int len)
{
while (len > 0) {
int rlen = s.Read(buf, off, len);
if (rlen <= 0) {
throw new EndOfStreamException();
}
off += rlen;
len -= rlen;
}
}
static byte[] SKIPBUF = new byte[8192];
internal static void Skip(Stream s, int len)
{
while (len > 0) {
int rlen = Math.Min(len, SKIPBUF.Length);
ReadFully(s, SKIPBUF, 0, rlen);
len -= rlen;
}
}
static readonly DateTime Jan1st1970 =
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
internal static long CurrentTimeMillis()
{
return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
}
/*
* Compute the SHA-1 hash of some bytes, returning the hash
* value in hexadecimal (lowercase).
*/
internal static string DoSHA1(byte[] buf)
{
return DoSHA1(buf, 0, buf.Length);
}
internal static string DoSHA1(byte[] buf, int off, int len)
{
byte[] hv = new SHA1Managed().ComputeHash(buf, off, len);
StringBuilder sb = new StringBuilder();
foreach (byte b in hv) {
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
}
/*
* Hash a whole chain of certificates. This is the SHA-1 hash
* of the concatenation of the provided buffers. The hash value
* is returned in lowercase hexadecimal.
*/
internal static string DoSHA1(byte[][] chain)
{
SHA1Managed sh = new SHA1Managed();
foreach (byte[] ec in chain) {
sh.TransformBlock(ec, 0, ec.Length, null, 0);
}
sh.TransformFinalBlock(new byte[0], 0, 0);
StringBuilder sb = new StringBuilder();
foreach (byte b in sh.Hash) {
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
}
internal static int Read1(Stream s)
{
int x = s.ReadByte();
if (x < 0) {
throw new IOException();
}
return x;
}
internal static int Read2(Stream s)
{
int x = Read1(s);
return (x << 8) | Read1(s);
}
internal static int Read3(Stream s)
{
int x = Read1(s);
x = (x << 8) | Read1(s);
return (x << 8) | Read1(s);
}
internal static void Write1(Stream s, int x)
{
s.WriteByte((byte)x);
}
internal static void Write2(Stream s, int x)
{
s.WriteByte((byte)(x >> 8));
s.WriteByte((byte)x);
}
internal static void Write3(Stream s, int x)
{
s.WriteByte((byte)(x >> 16));
s.WriteByte((byte)(x >> 8));
s.WriteByte((byte)x);
}
internal static void Write4(Stream s, int x)
{
s.WriteByte((byte)(x >> 24));
s.WriteByte((byte)(x >> 16));
s.WriteByte((byte)(x >> 8));
s.WriteByte((byte)x);
}
internal static void Write4(Stream s, uint x)
{
Write4(s, (int)x);
}
internal static void WriteExtension(Stream s, int extType, byte[] val)
{
if (val.Length > 0xFFFF) {
throw new ArgumentException("Oversized extension");
}
Write2(s, extType);
Write2(s, val.Length);
s.Write(val, 0, val.Length);
}
static RNGCryptoServiceProvider RNG = new RNGCryptoServiceProvider();
static byte[] rngBuf = new byte[256];
internal static void Rand(byte[] buf)
{
RNG.GetBytes(buf);
}
internal static void Rand(byte[] buf, int off, int len)
{
if (len == 0) {
return;
}
if (off == 0 && len == buf.Length) {
RNG.GetBytes(buf);
return;
}
while (len > 0) {
RNG.GetBytes(rngBuf);
int clen = Math.Min(len, rngBuf.Length);
Array.Copy(rngBuf, 0, buf, off, clen);
off += clen;
len -= clen;
}
}
internal static string VersionString(int v)
{
if (v == 0x0200) {
return "SSLv2";
} else if (v == 0x0300) {
return "SSLv3";
} else if ((v >> 8) == 0x03) {
return "TLSv1." + ((v & 0xFF) - 1);
} else {
return string.Format(
"UNKNOWN_VERSION:0x{0:X4}", v);
}
}
internal static bool Equals(int[] t1, int[] t2)
{
if (t1 == t2) {
return true;
}
if (t1 == null || t2 == null) {
return false;
}
int n = t1.Length;
if (t2.Length != n) {
return false;
}
for (int i = 0; i < n; i ++) {
if (t1[i] != t2[i]) {
return false;
}
}
return true;
}
internal static void Reverse<T>(T[] tab)
{
if (tab == null || tab.Length <= 1) {
return;
}
int n = tab.Length;
for (int i = 0; i < (n >> 1); i ++) {
T x = tab[i];
tab[i] = tab[n - 1 - i];
tab[n - 1 - i] = x;
}
}
const string B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz0123456789+/";
static string ToBase64(byte[] buf, int off, int len)
{
char[] tc = new char[((len + 2) / 3) << 2];
for (int i = 0, j = 0; i < len; i += 3) {
if ((i + 3) <= len) {
int x = Dec24be(buf, off + i);
tc[j ++] = B64[x >> 18];
tc[j ++] = B64[(x >> 12) & 0x3F];
tc[j ++] = B64[(x >> 6) & 0x3F];
tc[j ++] = B64[x & 0x3F];
} else if ((i + 2) == len) {
int x = Dec16be(buf, off + i);
tc[j ++] = B64[x >> 10];
tc[j ++] = B64[(x >> 4) & 0x3F];
tc[j ++] = B64[(x << 2) & 0x3F];
tc[j ++] = '=';
} else if ((i + 1) == len) {
int x = buf[off + i];
tc[j ++] = B64[(x >> 2) & 0x3F];
tc[j ++] = B64[(x << 4) & 0x3F];
tc[j ++] = '=';
tc[j ++] = '=';
}
}
return new string(tc);
}
internal static void WritePEM(TextWriter w, string objType, byte[] buf)
{
w.WriteLine("-----BEGIN {0}-----", objType.ToUpperInvariant());
int n = buf.Length;
for (int i = 0; i < n; i += 57) {
int len = Math.Min(57, n - i);
w.WriteLine(ToBase64(buf, i, len));
}
w.WriteLine("-----END {0}-----", objType.ToUpperInvariant());
}
internal static string ToPEM(string objType, byte[] buf)
{
return ToPEM(objType, buf, "\n");
}
internal static string ToPEM(string objType, byte[] buf, string nl)
{
StringWriter w = new StringWriter();
w.NewLine = nl;
WritePEM(w, objType, buf);
return w.ToString();
}
/*
* Compute bit length for an integer (unsigned big-endian).
* Bit length is the smallest integer k such that the integer
* value is less than 2^k.
*/
internal static int BitLength(byte[] v)
{
for (int k = 0; k < v.Length; k ++) {
int b = v[k];
if (b != 0) {
int bitLen = (v.Length - k) << 3;
while (b < 0x80) {
b <<= 1;
bitLen --;
}
return bitLen;
}
}
return 0;
}
/*
* Compute "adjusted" bit length for an integer (unsigned
* big-endian). The adjusted bit length is the integer k
* such that 2^k is closest to the integer value (if the
* integer is x = 3*2^m, then the adjusted bit length is
* m+2, not m+1).
*/
internal static int AdjustedBitLength(byte[] v)
{
for (int k = 0; k < v.Length; k ++) {
int b = v[k];
if (b == 0) {
continue;
}
int bitLen = (v.Length - k) << 3;
if (b == 1) {
if ((k + 1) == v.Length) {
return 0;
}
bitLen -= 7;
if (v[k + 1] < 0x80) {
bitLen --;
}
} else {
while (b < 0x80) {
b <<= 1;
bitLen --;
}
if (b < 0xC0) {
bitLen --;
}
}
return bitLen;
}
return 0;
}
internal static V[] ToValueArray<K, V>(IDictionary<K, V> s)
{
V[] vv = new V[s.Count];
int k = 0;
foreach (V v in s.Values) {
vv[k ++] = v;
}
return vv;
}
}
| |
//---------------------------------------------------------------------
// <copyright file="KeyInstance.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Provides a class used to represent a key value for a resource.
// </summary>
//
// @owner [....]
//---------------------------------------------------------------------
namespace System.Data.Services
{
using System.Collections.Generic;
using System.Data.Services.Parsing;
using System.Data.Services.Providers;
using System.Diagnostics;
/// <summary>Provides a class used to represent a key for a resource.</summary>
/// <remarks>
/// Internally, every key instance has a collection of values. These values
/// can be named or positional, depending on how they were specified
/// if parsed from a URI.
/// </remarks>
internal class KeyInstance
{
/// <summary>Empty key singleton.</summary>
private static readonly KeyInstance Empty = new KeyInstance();
/// <summary>Named values.</summary>
private readonly Dictionary<string, object> namedValues;
/// <summary>Positional values.</summary>
private readonly List<object> positionalValues;
/// <summary>Initializes a new empty <see cref="KeyInstance"/> instance.</summary>
private KeyInstance()
{
}
/// <summary>Initializes a new <see cref="KeyInstance"/> instance.</summary>
/// <param name='namedValues'>Named values.</param>
/// <param name='positionalValues'>Positional values for this instance.</param>
/// <remarks>
/// One of namedValues or positionalValues should be non-null, but not both.
/// </remarks>
private KeyInstance(Dictionary<string, object> namedValues, List<object> positionalValues)
{
Debug.Assert(
(namedValues == null) != (positionalValues == null),
"namedValues == null != positionalValues == null -- one or the other should be assigned, but not both");
this.namedValues = namedValues;
this.positionalValues = positionalValues;
}
/// <summary>Whether the values have a name.</summary>
internal bool AreValuesNamed
{
get { return this.namedValues != null; }
}
/// <summary>Checks whether this key has any values.</summary>
internal bool IsEmpty
{
get { return this == Empty; }
}
/// <summary>Returns a dictionary of named values when they AreValuesNamed is true.</summary>
internal IDictionary<string, object> NamedValues
{
get { return this.namedValues; }
}
/// <summary>Returns a list of values when they AreValuesNamed is false.</summary>
internal IList<object> PositionalValues
{
get { return this.positionalValues; }
}
/// <summary>Number of values in the key.</summary>
internal int ValueCount
{
get
{
if (this == Empty)
{
return 0;
}
else if (this.namedValues != null)
{
return this.namedValues.Count;
}
else
{
Debug.Assert(this.positionalValues != null, "this.positionalValues != null");
return this.positionalValues.Count;
}
}
}
/// <summary>Attempts to parse key values from the specified text.</summary>
/// <param name='text'>Text to parse (not null).</param>
/// <param name='instance'>After invocation, the parsed key instance.</param>
/// <returns>
/// true if the key instance was parsed; false if there was a
/// syntactic error.
/// </returns>
/// <remarks>
/// The returned instance contains only string values. To get typed values, a call to
/// <see cref="TryConvertValues"/> is necessary.
/// </remarks>
internal static bool TryParseKeysFromUri(string text, out KeyInstance instance)
{
return TryParseFromUri(text, true /*allowNamedValues*/, false /*allowNull*/, out instance);
}
/// <summary>Attempts to parse nullable values (only positional values, no name-value pairs) from the specified text.</summary>
/// <param name='text'>Text to parse (not null).</param>
/// <param name='instance'>After invocation, the parsed key instance.</param>
/// <returns>
/// true if the given values were parsed; false if there was a
/// syntactic error.
/// </returns>
/// <remarks>
/// The returned instance contains only string values. To get typed values, a call to
/// <see cref="TryConvertValues"/> is necessary.
/// </remarks>
internal static bool TryParseNullableTokens(string text, out KeyInstance instance)
{
return TryParseFromUri(text, false /*allowNamedValues*/, true /*allowNull*/, out instance);
}
/// <summary>Tries to convert values to the keys of the specified type.</summary>
/// <param name="type">Type with key information for conversion.</param>
/// <returns>true if all values were converted; false otherwise.</returns>
internal bool TryConvertValues(ResourceType type)
{
Debug.Assert(type != null, "type != null");
Debug.Assert(!this.IsEmpty, "!this.IsEmpty -- caller should check");
Debug.Assert(type.KeyProperties.Count == this.ValueCount, "type.KeyProperties.Count == this.ValueCount -- will change with containment");
if (this.namedValues != null)
{
for (int i = 0; i < type.KeyProperties.Count; i++)
{
ResourceProperty property = type.KeyProperties[i];
object unconvertedValue;
if (!this.namedValues.TryGetValue(property.Name, out unconvertedValue))
{
return false;
}
string valueText = (string)unconvertedValue;
object convertedValue;
if (!WebConvert.TryKeyStringToPrimitive(valueText, property.Type, out convertedValue))
{
return false;
}
this.namedValues[property.Name] = convertedValue;
}
}
else
{
Debug.Assert(this.positionalValues != null, "positionalValues != null -- otherwise this is Empty");
for (int i = 0; i < type.KeyProperties.Count; i++)
{
string valueText = (string)this.positionalValues[i];
object convertedValue;
if (!WebConvert.TryKeyStringToPrimitive(valueText, type.KeyProperties[i].Type, out convertedValue))
{
return false;
}
this.positionalValues[i] = convertedValue;
}
}
return true;
}
/// <summary>Attempts to parse key values from the specified text.</summary>
/// <param name='text'>Text to parse (not null).</param>
/// <param name="allowNamedValues">Set to true if the parser should accept named values
/// so syntax like Name='value'. If this is false, the parsing will fail on such constructs.</param>
/// <param name="allowNull">Set to true if the parser should accept null values.
/// If set to false, the parser will fail on null values.</param>
/// <param name='instance'>After invocation, the parsed key instance.</param>
/// <returns>
/// true if the key instance was parsed; false if there was a
/// syntactic error.
/// </returns>
/// <remarks>
/// The returned instance contains only string values. To get typed values, a call to
/// <see cref="TryConvertValues"/> is necessary.
/// </remarks>
private static bool TryParseFromUri(string text, bool allowNamedValues, bool allowNull, out KeyInstance instance)
{
Debug.Assert(text != null, "text != null");
Dictionary<string, object> namedValues = null;
List<object> positionalValues = null;
ExpressionLexer lexer = new ExpressionLexer(text);
Token currentToken = lexer.CurrentToken;
if (currentToken.Id == TokenId.End)
{
instance = Empty;
return true;
}
instance = null;
do
{
if (currentToken.Id == TokenId.Identifier && allowNamedValues)
{
// Name-value pair.
if (positionalValues != null)
{
// We cannot mix named and non-named values.
return false;
}
string identifier = lexer.CurrentToken.GetIdentifier();
lexer.NextToken();
if (lexer.CurrentToken.Id != TokenId.Equal)
{
return false;
}
lexer.NextToken();
if (!lexer.CurrentToken.IsKeyValueToken)
{
return false;
}
string namedValue = lexer.CurrentToken.Text;
WebUtil.CreateIfNull(ref namedValues);
if (namedValues.ContainsKey(identifier))
{
// Duplicate name.
return false;
}
namedValues.Add(identifier, namedValue);
}
else if (currentToken.IsKeyValueToken || (allowNull && currentToken.Id == TokenId.NullLiteral))
{
// Positional value.
if (namedValues != null)
{
// We cannot mix named and non-named values.
return false;
}
WebUtil.CreateIfNull(ref positionalValues);
positionalValues.Add(lexer.CurrentToken.Text);
}
else
{
return false;
}
// Read the next token. We should be at the end, or find
// we have a comma followed by something.
lexer.NextToken();
currentToken = lexer.CurrentToken;
if (currentToken.Id == TokenId.Comma)
{
lexer.NextToken();
currentToken = lexer.CurrentToken;
if (currentToken.Id == TokenId.End)
{
// Trailing comma.
return false;
}
}
}
while (currentToken.Id != TokenId.End);
instance = new KeyInstance(namedValues, positionalValues);
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace ME.Kevingleason.Pnwebrtc {
// Metadata.xml XPath class reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnRTCListener']"
[global::Android.Runtime.Register ("me/kevingleason/pnwebrtc/PnRTCListener", DoNotGenerateAcw=true)]
public abstract partial class PnRTCListener : global::Java.Lang.Object {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("me/kevingleason/pnwebrtc/PnRTCListener", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (PnRTCListener); }
}
protected PnRTCListener (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor;
// Metadata.xml XPath constructor reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnRTCListener']/constructor[@name='PnRTCListener' and count(parameter)=0]"
[Register (".ctor", "()V", "")]
public unsafe PnRTCListener ()
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
try {
if (GetType () != typeof (PnRTCListener)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V");
return;
}
if (id_ctor == IntPtr.Zero)
id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor);
} finally {
}
}
static Delegate cb_onAddRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_;
#pragma warning disable 0169
static Delegate GetOnAddRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_Handler ()
{
if (cb_onAddRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_ == null)
cb_onAddRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr>) n_OnAddRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_);
return cb_onAddRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_;
}
static void n_OnAddRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1)
{
global::ME.Kevingleason.Pnwebrtc.PnRTCListener __this = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnRTCListener> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Webrtc.MediaStream p0 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStream> (native_p0, JniHandleOwnership.DoNotTransfer);
global::ME.Kevingleason.Pnwebrtc.PnPeer p1 = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnPeer> (native_p1, JniHandleOwnership.DoNotTransfer);
__this.OnAddRemoteStream (p0, p1);
}
#pragma warning restore 0169
static IntPtr id_onAddRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_;
// Metadata.xml XPath method reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnRTCListener']/method[@name='onAddRemoteStream' and count(parameter)=2 and parameter[1][@type='org.webrtc.MediaStream'] and parameter[2][@type='me.kevingleason.pnwebrtc.PnPeer']]"
[Register ("onAddRemoteStream", "(Lorg/webrtc/MediaStream;Lme/kevingleason/pnwebrtc/PnPeer;)V", "GetOnAddRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_Handler")]
public virtual unsafe void OnAddRemoteStream (global::Org.Webrtc.MediaStream p0, global::ME.Kevingleason.Pnwebrtc.PnPeer p1)
{
if (id_onAddRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_ == IntPtr.Zero)
id_onAddRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_ = JNIEnv.GetMethodID (class_ref, "onAddRemoteStream", "(Lorg/webrtc/MediaStream;Lme/kevingleason/pnwebrtc/PnPeer;)V");
try {
JValue* __args = stackalloc JValue [2];
__args [0] = new JValue (p0);
__args [1] = new JValue (p1);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onAddRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onAddRemoteStream", "(Lorg/webrtc/MediaStream;Lme/kevingleason/pnwebrtc/PnPeer;)V"), __args);
} finally {
}
}
static Delegate cb_onCallReady_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetOnCallReady_Ljava_lang_String_Handler ()
{
if (cb_onCallReady_Ljava_lang_String_ == null)
cb_onCallReady_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_OnCallReady_Ljava_lang_String_);
return cb_onCallReady_Ljava_lang_String_;
}
static void n_OnCallReady_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::ME.Kevingleason.Pnwebrtc.PnRTCListener __this = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnRTCListener> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
__this.OnCallReady (p0);
}
#pragma warning restore 0169
static IntPtr id_onCallReady_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnRTCListener']/method[@name='onCallReady' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("onCallReady", "(Ljava/lang/String;)V", "GetOnCallReady_Ljava_lang_String_Handler")]
public virtual unsafe void OnCallReady (string p0)
{
if (id_onCallReady_Ljava_lang_String_ == IntPtr.Zero)
id_onCallReady_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "onCallReady", "(Ljava/lang/String;)V");
IntPtr native_p0 = JNIEnv.NewString (p0);
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (native_p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onCallReady_Ljava_lang_String_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onCallReady", "(Ljava/lang/String;)V"), __args);
} finally {
JNIEnv.DeleteLocalRef (native_p0);
}
}
static Delegate cb_onConnected_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetOnConnected_Ljava_lang_String_Handler ()
{
if (cb_onConnected_Ljava_lang_String_ == null)
cb_onConnected_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_OnConnected_Ljava_lang_String_);
return cb_onConnected_Ljava_lang_String_;
}
static void n_OnConnected_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::ME.Kevingleason.Pnwebrtc.PnRTCListener __this = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnRTCListener> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
__this.OnConnected (p0);
}
#pragma warning restore 0169
static IntPtr id_onConnected_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnRTCListener']/method[@name='onConnected' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("onConnected", "(Ljava/lang/String;)V", "GetOnConnected_Ljava_lang_String_Handler")]
public virtual unsafe void OnConnected (string p0)
{
if (id_onConnected_Ljava_lang_String_ == IntPtr.Zero)
id_onConnected_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "onConnected", "(Ljava/lang/String;)V");
IntPtr native_p0 = JNIEnv.NewString (p0);
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (native_p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onConnected_Ljava_lang_String_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onConnected", "(Ljava/lang/String;)V"), __args);
} finally {
JNIEnv.DeleteLocalRef (native_p0);
}
}
static Delegate cb_onDebug_Lme_kevingleason_pnwebrtc_PnRTCMessage_;
#pragma warning disable 0169
static Delegate GetOnDebug_Lme_kevingleason_pnwebrtc_PnRTCMessage_Handler ()
{
if (cb_onDebug_Lme_kevingleason_pnwebrtc_PnRTCMessage_ == null)
cb_onDebug_Lme_kevingleason_pnwebrtc_PnRTCMessage_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_OnDebug_Lme_kevingleason_pnwebrtc_PnRTCMessage_);
return cb_onDebug_Lme_kevingleason_pnwebrtc_PnRTCMessage_;
}
static void n_OnDebug_Lme_kevingleason_pnwebrtc_PnRTCMessage_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::ME.Kevingleason.Pnwebrtc.PnRTCListener __this = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnRTCListener> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::ME.Kevingleason.Pnwebrtc.PnRTCMessage p0 = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnRTCMessage> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.OnDebug (p0);
}
#pragma warning restore 0169
static IntPtr id_onDebug_Lme_kevingleason_pnwebrtc_PnRTCMessage_;
// Metadata.xml XPath method reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnRTCListener']/method[@name='onDebug' and count(parameter)=1 and parameter[1][@type='me.kevingleason.pnwebrtc.PnRTCMessage']]"
[Register ("onDebug", "(Lme/kevingleason/pnwebrtc/PnRTCMessage;)V", "GetOnDebug_Lme_kevingleason_pnwebrtc_PnRTCMessage_Handler")]
public virtual unsafe void OnDebug (global::ME.Kevingleason.Pnwebrtc.PnRTCMessage p0)
{
if (id_onDebug_Lme_kevingleason_pnwebrtc_PnRTCMessage_ == IntPtr.Zero)
id_onDebug_Lme_kevingleason_pnwebrtc_PnRTCMessage_ = JNIEnv.GetMethodID (class_ref, "onDebug", "(Lme/kevingleason/pnwebrtc/PnRTCMessage;)V");
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onDebug_Lme_kevingleason_pnwebrtc_PnRTCMessage_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onDebug", "(Lme/kevingleason/pnwebrtc/PnRTCMessage;)V"), __args);
} finally {
}
}
static Delegate cb_onLocalStream_Lorg_webrtc_MediaStream_;
#pragma warning disable 0169
static Delegate GetOnLocalStream_Lorg_webrtc_MediaStream_Handler ()
{
if (cb_onLocalStream_Lorg_webrtc_MediaStream_ == null)
cb_onLocalStream_Lorg_webrtc_MediaStream_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_OnLocalStream_Lorg_webrtc_MediaStream_);
return cb_onLocalStream_Lorg_webrtc_MediaStream_;
}
static void n_OnLocalStream_Lorg_webrtc_MediaStream_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::ME.Kevingleason.Pnwebrtc.PnRTCListener __this = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnRTCListener> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Webrtc.MediaStream p0 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStream> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.OnLocalStream (p0);
}
#pragma warning restore 0169
static IntPtr id_onLocalStream_Lorg_webrtc_MediaStream_;
// Metadata.xml XPath method reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnRTCListener']/method[@name='onLocalStream' and count(parameter)=1 and parameter[1][@type='org.webrtc.MediaStream']]"
[Register ("onLocalStream", "(Lorg/webrtc/MediaStream;)V", "GetOnLocalStream_Lorg_webrtc_MediaStream_Handler")]
public virtual unsafe void OnLocalStream (global::Org.Webrtc.MediaStream p0)
{
if (id_onLocalStream_Lorg_webrtc_MediaStream_ == IntPtr.Zero)
id_onLocalStream_Lorg_webrtc_MediaStream_ = JNIEnv.GetMethodID (class_ref, "onLocalStream", "(Lorg/webrtc/MediaStream;)V");
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onLocalStream_Lorg_webrtc_MediaStream_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onLocalStream", "(Lorg/webrtc/MediaStream;)V"), __args);
} finally {
}
}
static Delegate cb_onMessage_Lme_kevingleason_pnwebrtc_PnPeer_Ljava_lang_Object_;
#pragma warning disable 0169
static Delegate GetOnMessage_Lme_kevingleason_pnwebrtc_PnPeer_Ljava_lang_Object_Handler ()
{
if (cb_onMessage_Lme_kevingleason_pnwebrtc_PnPeer_Ljava_lang_Object_ == null)
cb_onMessage_Lme_kevingleason_pnwebrtc_PnPeer_Ljava_lang_Object_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr>) n_OnMessage_Lme_kevingleason_pnwebrtc_PnPeer_Ljava_lang_Object_);
return cb_onMessage_Lme_kevingleason_pnwebrtc_PnPeer_Ljava_lang_Object_;
}
static void n_OnMessage_Lme_kevingleason_pnwebrtc_PnPeer_Ljava_lang_Object_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1)
{
global::ME.Kevingleason.Pnwebrtc.PnRTCListener __this = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnRTCListener> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::ME.Kevingleason.Pnwebrtc.PnPeer p0 = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnPeer> (native_p0, JniHandleOwnership.DoNotTransfer);
global::Java.Lang.Object p1 = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (native_p1, JniHandleOwnership.DoNotTransfer);
__this.OnMessage (p0, p1);
}
#pragma warning restore 0169
static IntPtr id_onMessage_Lme_kevingleason_pnwebrtc_PnPeer_Ljava_lang_Object_;
// Metadata.xml XPath method reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnRTCListener']/method[@name='onMessage' and count(parameter)=2 and parameter[1][@type='me.kevingleason.pnwebrtc.PnPeer'] and parameter[2][@type='java.lang.Object']]"
[Register ("onMessage", "(Lme/kevingleason/pnwebrtc/PnPeer;Ljava/lang/Object;)V", "GetOnMessage_Lme_kevingleason_pnwebrtc_PnPeer_Ljava_lang_Object_Handler")]
public virtual unsafe void OnMessage (global::ME.Kevingleason.Pnwebrtc.PnPeer p0, global::Java.Lang.Object p1)
{
if (id_onMessage_Lme_kevingleason_pnwebrtc_PnPeer_Ljava_lang_Object_ == IntPtr.Zero)
id_onMessage_Lme_kevingleason_pnwebrtc_PnPeer_Ljava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "onMessage", "(Lme/kevingleason/pnwebrtc/PnPeer;Ljava/lang/Object;)V");
try {
JValue* __args = stackalloc JValue [2];
__args [0] = new JValue (p0);
__args [1] = new JValue (p1);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onMessage_Lme_kevingleason_pnwebrtc_PnPeer_Ljava_lang_Object_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onMessage", "(Lme/kevingleason/pnwebrtc/PnPeer;Ljava/lang/Object;)V"), __args);
} finally {
}
}
static Delegate cb_onPeerConnectionClosed_Lme_kevingleason_pnwebrtc_PnPeer_;
#pragma warning disable 0169
static Delegate GetOnPeerConnectionClosed_Lme_kevingleason_pnwebrtc_PnPeer_Handler ()
{
if (cb_onPeerConnectionClosed_Lme_kevingleason_pnwebrtc_PnPeer_ == null)
cb_onPeerConnectionClosed_Lme_kevingleason_pnwebrtc_PnPeer_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_OnPeerConnectionClosed_Lme_kevingleason_pnwebrtc_PnPeer_);
return cb_onPeerConnectionClosed_Lme_kevingleason_pnwebrtc_PnPeer_;
}
static void n_OnPeerConnectionClosed_Lme_kevingleason_pnwebrtc_PnPeer_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::ME.Kevingleason.Pnwebrtc.PnRTCListener __this = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnRTCListener> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::ME.Kevingleason.Pnwebrtc.PnPeer p0 = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnPeer> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.OnPeerConnectionClosed (p0);
}
#pragma warning restore 0169
static IntPtr id_onPeerConnectionClosed_Lme_kevingleason_pnwebrtc_PnPeer_;
// Metadata.xml XPath method reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnRTCListener']/method[@name='onPeerConnectionClosed' and count(parameter)=1 and parameter[1][@type='me.kevingleason.pnwebrtc.PnPeer']]"
[Register ("onPeerConnectionClosed", "(Lme/kevingleason/pnwebrtc/PnPeer;)V", "GetOnPeerConnectionClosed_Lme_kevingleason_pnwebrtc_PnPeer_Handler")]
public virtual unsafe void OnPeerConnectionClosed (global::ME.Kevingleason.Pnwebrtc.PnPeer p0)
{
if (id_onPeerConnectionClosed_Lme_kevingleason_pnwebrtc_PnPeer_ == IntPtr.Zero)
id_onPeerConnectionClosed_Lme_kevingleason_pnwebrtc_PnPeer_ = JNIEnv.GetMethodID (class_ref, "onPeerConnectionClosed", "(Lme/kevingleason/pnwebrtc/PnPeer;)V");
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onPeerConnectionClosed_Lme_kevingleason_pnwebrtc_PnPeer_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onPeerConnectionClosed", "(Lme/kevingleason/pnwebrtc/PnPeer;)V"), __args);
} finally {
}
}
static Delegate cb_onPeerStatusChanged_Lme_kevingleason_pnwebrtc_PnPeer_;
#pragma warning disable 0169
static Delegate GetOnPeerStatusChanged_Lme_kevingleason_pnwebrtc_PnPeer_Handler ()
{
if (cb_onPeerStatusChanged_Lme_kevingleason_pnwebrtc_PnPeer_ == null)
cb_onPeerStatusChanged_Lme_kevingleason_pnwebrtc_PnPeer_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_OnPeerStatusChanged_Lme_kevingleason_pnwebrtc_PnPeer_);
return cb_onPeerStatusChanged_Lme_kevingleason_pnwebrtc_PnPeer_;
}
static void n_OnPeerStatusChanged_Lme_kevingleason_pnwebrtc_PnPeer_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::ME.Kevingleason.Pnwebrtc.PnRTCListener __this = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnRTCListener> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::ME.Kevingleason.Pnwebrtc.PnPeer p0 = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnPeer> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.OnPeerStatusChanged (p0);
}
#pragma warning restore 0169
static IntPtr id_onPeerStatusChanged_Lme_kevingleason_pnwebrtc_PnPeer_;
// Metadata.xml XPath method reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnRTCListener']/method[@name='onPeerStatusChanged' and count(parameter)=1 and parameter[1][@type='me.kevingleason.pnwebrtc.PnPeer']]"
[Register ("onPeerStatusChanged", "(Lme/kevingleason/pnwebrtc/PnPeer;)V", "GetOnPeerStatusChanged_Lme_kevingleason_pnwebrtc_PnPeer_Handler")]
public virtual unsafe void OnPeerStatusChanged (global::ME.Kevingleason.Pnwebrtc.PnPeer p0)
{
if (id_onPeerStatusChanged_Lme_kevingleason_pnwebrtc_PnPeer_ == IntPtr.Zero)
id_onPeerStatusChanged_Lme_kevingleason_pnwebrtc_PnPeer_ = JNIEnv.GetMethodID (class_ref, "onPeerStatusChanged", "(Lme/kevingleason/pnwebrtc/PnPeer;)V");
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onPeerStatusChanged_Lme_kevingleason_pnwebrtc_PnPeer_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onPeerStatusChanged", "(Lme/kevingleason/pnwebrtc/PnPeer;)V"), __args);
} finally {
}
}
static Delegate cb_onRemoveRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_;
#pragma warning disable 0169
static Delegate GetOnRemoveRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_Handler ()
{
if (cb_onRemoveRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_ == null)
cb_onRemoveRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr>) n_OnRemoveRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_);
return cb_onRemoveRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_;
}
static void n_OnRemoveRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1)
{
global::ME.Kevingleason.Pnwebrtc.PnRTCListener __this = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnRTCListener> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Webrtc.MediaStream p0 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStream> (native_p0, JniHandleOwnership.DoNotTransfer);
global::ME.Kevingleason.Pnwebrtc.PnPeer p1 = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnPeer> (native_p1, JniHandleOwnership.DoNotTransfer);
__this.OnRemoveRemoteStream (p0, p1);
}
#pragma warning restore 0169
static IntPtr id_onRemoveRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_;
// Metadata.xml XPath method reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnRTCListener']/method[@name='onRemoveRemoteStream' and count(parameter)=2 and parameter[1][@type='org.webrtc.MediaStream'] and parameter[2][@type='me.kevingleason.pnwebrtc.PnPeer']]"
[Register ("onRemoveRemoteStream", "(Lorg/webrtc/MediaStream;Lme/kevingleason/pnwebrtc/PnPeer;)V", "GetOnRemoveRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_Handler")]
public virtual unsafe void OnRemoveRemoteStream (global::Org.Webrtc.MediaStream p0, global::ME.Kevingleason.Pnwebrtc.PnPeer p1)
{
if (id_onRemoveRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_ == IntPtr.Zero)
id_onRemoveRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_ = JNIEnv.GetMethodID (class_ref, "onRemoveRemoteStream", "(Lorg/webrtc/MediaStream;Lme/kevingleason/pnwebrtc/PnPeer;)V");
try {
JValue* __args = stackalloc JValue [2];
__args [0] = new JValue (p0);
__args [1] = new JValue (p1);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onRemoveRemoteStream_Lorg_webrtc_MediaStream_Lme_kevingleason_pnwebrtc_PnPeer_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onRemoveRemoteStream", "(Lorg/webrtc/MediaStream;Lme/kevingleason/pnwebrtc/PnPeer;)V"), __args);
} finally {
}
}
}
[global::Android.Runtime.Register ("me/kevingleason/pnwebrtc/PnRTCListener", DoNotGenerateAcw=true)]
internal partial class PnRTCListenerInvoker : PnRTCListener {
public PnRTCListenerInvoker (IntPtr handle, JniHandleOwnership transfer) : base (handle, transfer) {}
protected override global::System.Type ThresholdType {
get { return typeof (PnRTCListenerInvoker); }
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Tests
{
public class TypeTestsNetcore
{
private static readonly IList<Type> NonArrayBaseTypes;
static TypeTestsNetcore()
{
NonArrayBaseTypes = new List<Type>()
{
typeof(int),
typeof(void),
typeof(int*),
typeof(Outside),
typeof(Outside<int>),
typeof(Outside<>).GetTypeInfo().GenericTypeParameters[0],
new object().GetType().GetType()
};
if (PlatformDetection.IsWindows)
{
NonArrayBaseTypes.Add(Type.GetTypeFromCLSID(default(Guid)));
}
}
[Fact]
public void IsSZArray_FalseForNonArrayTypes()
{
foreach (Type type in NonArrayBaseTypes)
{
Assert.False(type.IsSZArray);
}
}
[Fact]
public void IsSZArray_TrueForSZArrayTypes()
{
foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType()))
{
Assert.True(type.IsSZArray);
}
}
[Fact]
public void IsSZArray_FalseForVariableBoundArrayTypes()
{
foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(1)))
{
Assert.False(type.IsSZArray);
}
foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(2)))
{
Assert.False(type.IsSZArray);
}
}
[Fact]
public void IsSZArray_FalseForNonArrayByRefType()
{
Assert.False(typeof(int).MakeByRefType().IsSZArray);
}
[Fact]
public void IsSZArray_FalseForByRefSZArrayType()
{
Assert.False(typeof(int[]).MakeByRefType().IsSZArray);
}
[Fact]
public void IsSZArray_FalseForByRefVariableArrayType()
{
Assert.False(typeof(int[,]).MakeByRefType().IsSZArray);
}
[Fact]
public void IsVariableBoundArray_FalseForNonArrayTypes()
{
foreach (Type type in NonArrayBaseTypes)
{
Assert.False(type.IsVariableBoundArray);
}
}
[Fact]
public void IsVariableBoundArray_FalseForSZArrayTypes()
{
foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType()))
{
Assert.False(type.IsVariableBoundArray);
}
}
[Fact]
public void IsVariableBoundArray_TrueForVariableBoundArrayTypes()
{
foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(1)))
{
Assert.True(type.IsVariableBoundArray);
}
foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(2)))
{
Assert.True(type.IsVariableBoundArray);
}
}
[Fact]
public void IsVariableBoundArray_FalseForNonArrayByRefType()
{
Assert.False(typeof(int).MakeByRefType().IsVariableBoundArray);
}
[Fact]
public void IsVariableBoundArray_FalseForByRefSZArrayType()
{
Assert.False(typeof(int[]).MakeByRefType().IsVariableBoundArray);
}
[Fact]
public void IsVariableBoundArray_FalseForByRefVariableArrayType()
{
Assert.False(typeof(int[,]).MakeByRefType().IsVariableBoundArray);
}
[Theory]
[MemberData(nameof(DefinedTypes))]
public void IsTypeDefinition_True(Type type)
{
Assert.True(type.IsTypeDefinition);
}
[Theory]
[MemberData(nameof(NotDefinedTypes))]
public void IsTypeDefinition_False(Type type)
{
Assert.False(type.IsTypeDefinition);
}
// In the unlikely event we ever add new values to the CorElementType enumeration, CoreCLR will probably miss it because of the way IsTypeDefinition
// works. It's likely that such a type will live in the core assembly so to improve our chances of catching this situation, test IsTypeDefinition
// on every type exposed out of that assembly.
//
// Skipping this on .Net Native because:
// - We really don't want to opt in all the metadata in System.Private.CoreLib
// - The .Net Native implementation of IsTypeDefinition is not the one that works by enumerating selected values off CorElementType.
// It has much less need of a test like this.
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot)]
public void IsTypeDefinition_AllDefinedTypesInCoreAssembly()
{
foreach (Type type in typeof(object).Assembly.DefinedTypes)
{
Assert.True(type.IsTypeDefinition, "IsTypeDefinition expected to be true for type " + type);
}
}
public static IEnumerable<object[]> DefinedTypes
{
get
{
yield return new object[] { typeof(void) };
yield return new object[] { typeof(int) };
yield return new object[] { typeof(Outside) };
yield return new object[] { typeof(Outside.Inside) };
yield return new object[] { typeof(Outside<>) };
yield return new object[] { typeof(IEnumerable<>) };
yield return new object[] { 3.GetType().GetType() }; // This yields a reflection-blocked type on .Net Native - which is implemented separately
if (PlatformDetection.IsWindows)
yield return new object[] { Type.GetTypeFromCLSID(default(Guid)) };
}
}
public static IEnumerable<object[]> NotDefinedTypes
{
get
{
Type theT = typeof(Outside<>).GetTypeInfo().GenericTypeParameters[0];
yield return new object[] { typeof(int[]) };
yield return new object[] { theT.MakeArrayType(1) }; // Using an open type as element type gets around .Net Native nonsupport of rank-1 multidim arrays
yield return new object[] { typeof(int[,]) };
yield return new object[] { typeof(int).MakeByRefType() };
yield return new object[] { typeof(int).MakePointerType() };
yield return new object[] { typeof(Outside<int>) };
yield return new object[] { typeof(Outside<int>.Inside<int>) };
yield return new object[] { theT };
}
}
[Theory]
[MemberData(nameof(IsByRefLikeTestData))]
public static void TestIsByRefLike(Type type, bool expected)
{
Assert.Equal(expected, type.IsByRefLike);
}
public static IEnumerable<object[]> IsByRefLikeTestData
{
get
{
Type theT = typeof(Outside<>).GetTypeInfo().GenericTypeParameters[0];
yield return new object[] { typeof(TypedReference), true };
yield return new object[] { typeof(Span<>), true };
yield return new object[] { typeof(Span<int>), true };
yield return new object[] { typeof(Span<>).MakeGenericType(theT), true };
yield return new object[] { typeof(ByRefLikeStruct), true };
yield return new object[] { typeof(RegularStruct), false };
yield return new object[] { typeof(object), false };
yield return new object[] { typeof(Span<int>).MakeByRefType(), false };
yield return new object[] { typeof(Span<int>).MakePointerType(), false };
yield return new object[] { theT, false };
yield return new object[] { typeof(int[]), false };
yield return new object[] { typeof(int[,]), false };
if (PlatformDetection.IsWindows) // GetTypeFromCLSID is Windows only
{
yield return new object[] { Type.GetTypeFromCLSID(default(Guid)), false };
}
}
}
private ref struct ByRefLikeStruct
{
public ByRefLikeStruct(int dummy)
{
S = default(Span<int>);
}
public Span<int> S;
}
private struct RegularStruct
{
}
[Theory]
[MemberData(nameof(IsGenericParameterTestData))]
public static void TestIsGenericParameter(Type type, bool isGenericParameter, bool isGenericTypeParameter, bool isGenericMethodParameter)
{
Assert.Equal(isGenericParameter, type.IsGenericParameter);
Assert.Equal(isGenericTypeParameter, type.IsGenericTypeParameter);
Assert.Equal(isGenericMethodParameter, type.IsGenericMethodParameter);
}
public static IEnumerable<object[]> IsGenericParameterTestData
{
get
{
yield return new object[] { typeof(void), false, false, false };
yield return new object[] { typeof(int), false, false, false };
yield return new object[] { typeof(int[]), false, false, false };
yield return new object[] { typeof(int).MakeArrayType(1), false, false, false };
yield return new object[] { typeof(int[,]), false, false, false };
yield return new object[] { typeof(int).MakeByRefType(), false, false, false };
yield return new object[] { typeof(int).MakePointerType(), false, false, false };
yield return new object[] { typeof(G<>), false, false, false };
yield return new object[] { typeof(G<int>), false, false, false };
if (PlatformDetection.IsWindows) // GetTypeFromCLSID is Windows only
{
yield return new object[] { Type.GetTypeFromCLSID(default(Guid)), false, false, false };
}
Type theT = typeof(Outside<>).GetTypeInfo().GenericTypeParameters[0];
yield return new object[] { theT, true, true, false };
Type theM = typeof(TypeTestsNetcore).GetMethod(nameof(GenericMethod), BindingFlags.NonPublic | BindingFlags.Static).GetGenericArguments()[0];
yield return new object[] { theM, true, false, true };
}
}
private static void GenericMethod<M>() { }
}
}
| |
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Schema;
using System.Xml;
namespace System.Xml.Serialization
{
internal class ReflectionXmlSerializationWriter : XmlSerializationWriter
{
private XmlMapping _mapping;
internal static TypeDesc StringTypeDesc { get; private set; } = (new TypeScope()).GetTypeDesc(typeof(string));
internal static TypeDesc QnameTypeDesc { get; private set; } = (new TypeScope()).GetTypeDesc(typeof(XmlQualifiedName));
public ReflectionXmlSerializationWriter(XmlMapping xmlMapping, XmlWriter xmlWriter, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
{
Init(xmlWriter, namespaces, encodingStyle, id, null);
if (!xmlMapping.IsWriteable || !xmlMapping.GenerateSerializer)
{
throw new ArgumentException(SR.Format(SR.XmlInternalError, nameof(xmlMapping)));
}
if (xmlMapping is XmlTypeMapping || xmlMapping is XmlMembersMapping)
{
_mapping = xmlMapping;
}
else
{
throw new ArgumentException(SR.Format(SR.XmlInternalError, nameof(xmlMapping)));
}
}
protected override void InitCallbacks()
{
TypeScope scope = _mapping.Scope;
foreach (TypeMapping mapping in scope.TypeMappings)
{
if (mapping.IsSoap &&
(mapping is StructMapping || mapping is EnumMapping) &&
!mapping.TypeDesc.IsRoot)
{
AddWriteCallback(
mapping.TypeDesc.Type,
mapping.TypeName,
mapping.Namespace,
CreateXmlSerializationWriteCallback(mapping, mapping.TypeName, mapping.Namespace, mapping.TypeDesc.IsNullable)
);
}
}
}
public void WriteObject(object o)
{
XmlMapping xmlMapping = _mapping;
if (xmlMapping is XmlTypeMapping xmlTypeMapping)
{
WriteObjectOfTypeElement(o, xmlTypeMapping);
}
else if (xmlMapping is XmlMembersMapping xmlMembersMapping)
{
GenerateMembersElement(o, xmlMembersMapping);
}
}
private void WriteObjectOfTypeElement(object o, XmlTypeMapping mapping)
{
GenerateTypeElement(o, mapping);
}
private void GenerateTypeElement(object o, XmlTypeMapping xmlMapping)
{
ElementAccessor element = xmlMapping.Accessor;
TypeMapping mapping = element.Mapping;
WriteStartDocument();
if (o == null)
{
string ns = (element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty);
if (element.IsNullable)
{
if (mapping.IsSoap)
{
WriteNullTagEncoded(element.Name, ns);
}
else
{
WriteNullTagLiteral(element.Name, ns);
}
}
else
{
WriteEmptyTag(element.Name, ns);
}
return;
}
if (!mapping.TypeDesc.IsValueType && !mapping.TypeDesc.Type.IsPrimitive)
{
TopLevelElement();
}
WriteMember(o, null, new ElementAccessor[] { element }, null, null, mapping.TypeDesc, !element.IsSoap);
if (mapping.IsSoap)
{
WriteReferencedElements();
}
}
private void WriteMember(object o, object choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc memberTypeDesc, bool writeAccessors)
{
if (memberTypeDesc.IsArrayLike &&
!(elements.Length == 1 && elements[0].Mapping is ArrayMapping))
{
WriteArray(o, choiceSource, elements, text, choice, memberTypeDesc);
}
else
{
WriteElements(o, choiceSource, elements, text, choice, writeAccessors, memberTypeDesc.IsNullable);
}
}
private void WriteArray(object o, object choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc)
{
if (elements.Length == 0 && text == null)
{
return;
}
if (arrayTypeDesc.IsNullable && o == null)
{
return;
}
if (choice != null)
{
if (choiceSource == null || ((Array)choiceSource).Length < ((Array)o).Length)
{
throw CreateInvalidChoiceIdentifierValueException(choice.Mapping.TypeDesc.FullName, choice.MemberName);
}
}
WriteArrayItems(elements, text, choice, arrayTypeDesc, o);
}
private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc, object o)
{
TypeDesc arrayElementTypeDesc = arrayTypeDesc.ArrayElementTypeDesc;
var arr = o as IList;
if (arr != null)
{
for (int i = 0; i < arr.Count; i++)
{
object ai = arr[i];
WriteElements(ai, null/*choiceName + "i"*/, elements, text, choice, true, true);
}
}
else
{
var a = o as IEnumerable;
// #10593: This assert may not be true. We need more tests for this method.
Debug.Assert(a != null);
IEnumerator e = a.GetEnumerator();
if (e != null)
{
while (e.MoveNext())
{
object ai = e.Current;
WriteElements(ai, null/*choiceName + "i"*/, elements, text, choice, true, true);
}
}
}
}
private void WriteElements(object o, object enumSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, bool writeAccessors, bool isNullable)
{
if (elements.Length == 0 && text == null)
return;
if (elements.Length == 1 && text == null)
{
WriteElement(o, elements[0], writeAccessors);
}
else
{
if (isNullable && choice == null && o == null)
{
return;
}
int anyCount = 0;
var namedAnys = new List<ElementAccessor>();
ElementAccessor unnamedAny = null; // can only have one
string enumTypeName = choice?.Mapping.TypeDesc.FullName;
for (int i = 0; i < elements.Length; i++)
{
ElementAccessor element = elements[i];
if (element.Any)
{
anyCount++;
if (element.Name != null && element.Name.Length > 0)
namedAnys.Add(element);
else if (unnamedAny == null)
unnamedAny = element;
}
else if (choice != null)
{
if (o != null && o.GetType() == element.Mapping.TypeDesc.Type)
{
WriteElement(o, element, writeAccessors);
return;
}
}
else
{
TypeDesc td = element.IsUnbounded ? element.Mapping.TypeDesc.CreateArrayTypeDesc() : element.Mapping.TypeDesc;
if (o.GetType() == td.Type)
{
WriteElement(o, element, writeAccessors);
return;
}
}
}
if (anyCount > 0)
{
if (o is XmlElement elem)
{
foreach (ElementAccessor element in namedAnys)
{
if (element.Name == elem.Name && element.Namespace == elem.NamespaceURI)
{
WriteElement(elem, element, writeAccessors);
return;
}
}
if (choice != null)
{
throw CreateChoiceIdentifierValueException(choice.Mapping.TypeDesc.FullName, choice.MemberName, elem.Name, elem.NamespaceURI);
}
if (unnamedAny != null)
{
WriteElement(elem, unnamedAny, writeAccessors);
return;
}
throw CreateUnknownAnyElementException(elem.Name, elem.NamespaceURI);
}
}
if (text != null)
{
bool useReflection = text.Mapping.TypeDesc.UseReflection;
string fullTypeName = text.Mapping.TypeDesc.CSharpName;
WriteText(o, text);
return;
}
if (elements.Length > 0 && o != null)
{
throw CreateUnknownTypeException(o);
}
}
}
private void WriteText(object o, TextAccessor text)
{
if (text.Mapping is PrimitiveMapping primitiveMapping)
{
string stringValue;
if (text.Mapping is EnumMapping enumMapping)
{
stringValue = WriteEnumMethod(enumMapping, o);
}
else
{
if (!WritePrimitiveValue(primitiveMapping.TypeDesc, o, false, out stringValue))
{
// #10593: Add More Tests for Serialization Code
Debug.Assert(o is byte[]);
}
}
if (o is byte[] byteArray)
{
WriteValue(byteArray);
}
else
{
WriteValue(stringValue);
}
}
else if (text.Mapping is SpecialMapping specialMapping)
{
switch (specialMapping.TypeDesc.Kind)
{
case TypeKind.Node:
((XmlNode)o).WriteTo(Writer);
break;
default:
throw new InvalidOperationException(SR.XmlInternalError);
}
}
}
private void WriteElement(object o, ElementAccessor element, bool writeAccessor)
{
string name = writeAccessor ? element.Name : element.Mapping.TypeName;
string ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping.Namespace) : string.Empty);
if (element.Mapping is NullableMapping nullableMapping)
{
if (o != null)
{
ElementAccessor e = element.Clone();
e.Mapping = nullableMapping.BaseMapping;
WriteElement(o, e, writeAccessor);
}
else if (element.IsNullable)
{
WriteNullTagLiteral(element.Name, ns);
}
}
else if (element.Mapping is ArrayMapping)
{
var mapping = element.Mapping as ArrayMapping;
if (element.IsNullable && o == null)
{
WriteNullTagLiteral(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty);
}
else if (mapping.IsSoap)
{
if (mapping.Elements == null || mapping.Elements.Length != 1)
{
throw new InvalidOperationException(SR.XmlInternalError);
}
if (!writeAccessor)
{
WritePotentiallyReferencingElement(name, ns, o, mapping.TypeDesc.Type, true, element.IsNullable);
}
else
{
WritePotentiallyReferencingElement(name, ns, o, null, false, element.IsNullable);
}
}
else if (element.IsUnbounded)
{
TypeDesc arrayTypeDesc = mapping.TypeDesc.CreateArrayTypeDesc();
var enumerable = (IEnumerable)o;
foreach (var e in enumerable)
{
element.IsUnbounded = false;
WriteElement(e, element, writeAccessor);
element.IsUnbounded = true;
}
}
else
{
if (o != null)
{
WriteStartElement(name, ns, false);
WriteArrayItems(mapping.ElementsSortedByDerivation, null, null, mapping.TypeDesc, o);
WriteEndElement();
}
}
}
else if (element.Mapping is EnumMapping)
{
if (element.Mapping.IsSoap)
{
Writer.WriteStartElement(name, ns);
WriteEnumMethod((EnumMapping)element.Mapping, o);
WriteEndElement();
}
else
{
WritePrimitive(WritePrimitiveMethodRequirement.WriteElementString, name, ns, element.Default, o, element.Mapping, false, true, element.IsNullable);
}
}
else if (element.Mapping is PrimitiveMapping)
{
var mapping = element.Mapping as PrimitiveMapping;
if (mapping.TypeDesc == QnameTypeDesc)
{
WriteQualifiedNameElement(name, ns, element.Default, (XmlQualifiedName)o, element.IsNullable, mapping.IsSoap, mapping);
}
else
{
WritePrimitiveMethodRequirement suffixNullable = mapping.IsSoap ? WritePrimitiveMethodRequirement.Encoded : WritePrimitiveMethodRequirement.None;
WritePrimitiveMethodRequirement suffixRaw = mapping.TypeDesc.XmlEncodingNotRequired ? WritePrimitiveMethodRequirement.Raw : WritePrimitiveMethodRequirement.None;
WritePrimitive(element.IsNullable
? WritePrimitiveMethodRequirement.WriteNullableStringLiteral | suffixNullable | suffixRaw
: WritePrimitiveMethodRequirement.WriteElementString | suffixRaw,
name, ns, element.Default, o, mapping, mapping.IsSoap, true, element.IsNullable);
}
}
else if (element.Mapping is StructMapping)
{
var mapping = element.Mapping as StructMapping;
if (mapping.IsSoap)
{
WritePotentiallyReferencingElement(name, ns, o, !writeAccessor ? mapping.TypeDesc.Type : null, !writeAccessor, element.IsNullable);
}
else
{
WriteStructMethod(mapping, name, ns, o, element.IsNullable, needType: false);
}
}
else if (element.Mapping is SpecialMapping)
{
if (element.Mapping is SerializableMapping)
{
WriteSerializable((IXmlSerializable)o, name, ns, element.IsNullable, !element.Any);
}
else
{
// XmlNode, XmlElement
if (o is XmlNode node)
{
WriteElementLiteral(node, name, ns, element.IsNullable, element.Any);
}
else
{
throw CreateInvalidAnyTypeException(o);
}
}
}
else
{
throw new InvalidOperationException(SR.XmlInternalError);
}
}
private XmlSerializationWriteCallback CreateXmlSerializationWriteCallback(TypeMapping mapping, string name, string ns, bool isNullable)
{
if (mapping is StructMapping structMapping)
{
return (o) =>
{
WriteStructMethod(structMapping, name, ns, o, isNullable, needType: false);
};
}
else if (mapping is EnumMapping enumMapping)
{
return (o) =>
{
WriteEnumMethod(enumMapping, o);
};
}
else
{
throw new InvalidOperationException(SR.XmlInternalError);
}
}
private void WriteQualifiedNameElement(string name, string ns, object defaultValue, XmlQualifiedName o, bool nullable, bool isSoap, PrimitiveMapping mapping)
{
bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport;
if (hasDefault && IsDefaultValue(mapping, o, defaultValue, nullable))
return;
if (isSoap)
{
if (nullable)
{
WriteNullableQualifiedNameEncoded(name, ns, o, new XmlQualifiedName(mapping.TypeName, mapping.Namespace));
}
else
{
WriteElementQualifiedName(name, ns, o, new XmlQualifiedName(mapping.TypeName, mapping.Namespace));
}
}
else
{
if (nullable)
{
WriteNullableQualifiedNameLiteral(name, ns, o);
}
else
{
WriteElementQualifiedName(name, ns, o);
}
}
}
private void WriteStructMethod(StructMapping mapping, string n, string ns, object o, bool isNullable, bool needType)
{
if (mapping.IsSoap && mapping.TypeDesc.IsRoot) return;
if (!mapping.IsSoap)
{
if (o == null)
{
if (isNullable) WriteNullTagLiteral(n, ns);
return;
}
if (!needType
&& o.GetType() != mapping.TypeDesc.Type)
{
if (WriteDerivedTypes(mapping, n, ns, o, isNullable))
{
return;
}
if (mapping.TypeDesc.IsRoot)
{
if (WriteEnumAndArrayTypes(mapping, o, n, ns))
{
return;
}
WriteTypedPrimitive(n, ns, o, true);
return;
}
throw CreateUnknownTypeException(o);
}
}
if (!mapping.TypeDesc.IsAbstract)
{
if (mapping.TypeDesc.Type != null && typeof(XmlSchemaObject).IsAssignableFrom(mapping.TypeDesc.Type))
{
EscapeName = false;
}
XmlSerializerNamespaces xmlnsSource = null;
MemberMapping[] members = TypeScope.GetAllMembers(mapping);
int xmlnsMember = FindXmlnsIndex(members);
if (xmlnsMember >= 0)
{
MemberMapping member = members[xmlnsMember];
xmlnsSource = (XmlSerializerNamespaces)GetMemberValue(o, member.Name);
}
if (!mapping.IsSoap)
{
WriteStartElement(n, ns, o, false, xmlnsSource);
if (!mapping.TypeDesc.IsRoot)
{
if (needType)
{
WriteXsiType(mapping.TypeName, mapping.Namespace);
}
}
}
else if (xmlnsSource != null)
{
WriteNamespaceDeclarations(xmlnsSource);
}
for (int i = 0; i < members.Length; i++)
{
MemberMapping m = members[i];
bool isSpecified = true;
bool shouldPersist = true;
if (m.CheckSpecified != SpecifiedAccessor.None)
{
string specifiedMemberName = m.Name + "Specified";
isSpecified = (bool)GetMemberValue(o, specifiedMemberName);
}
if (m.CheckShouldPersist)
{
string methodInvoke = "ShouldSerialize" + m.Name;
MethodInfo method = o.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke);
shouldPersist = (bool)method.Invoke(o, Array.Empty<object>());
}
if (m.Attribute != null)
{
if (isSpecified && shouldPersist)
{
object memberValue = GetMemberValue(o, m.Name);
WriteMember(memberValue, m.Attribute, m.TypeDesc, o);
}
}
}
for (int i = 0; i < members.Length; i++)
{
MemberMapping m = members[i];
if (m.Xmlns != null)
continue;
bool isSpecified = true;
bool shouldPersist = true;
if (m.CheckSpecified != SpecifiedAccessor.None)
{
string specifiedMemberName = m.Name + "Specified";
isSpecified = (bool)GetMemberValue(o, specifiedMemberName);
}
if (m.CheckShouldPersist)
{
string methodInvoke = "ShouldSerialize" + m.Name;
MethodInfo method = o.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke);
shouldPersist = (bool)method.Invoke(o, Array.Empty<object>());
}
bool checkShouldPersist = m.CheckShouldPersist && (m.Elements.Length > 0 || m.Text != null);
if (!checkShouldPersist)
{
shouldPersist = true;
}
if (isSpecified && shouldPersist)
{
object choiceSource = null;
if (m.ChoiceIdentifier != null)
{
choiceSource = GetMemberValue(o, m.ChoiceIdentifier.MemberName);
}
object memberValue = GetMemberValue(o, m.Name);
WriteMember(memberValue, choiceSource, m.ElementsSortedByDerivation, m.Text, m.ChoiceIdentifier, m.TypeDesc, true);
}
}
if (!mapping.IsSoap)
{
WriteEndElement(o);
}
}
}
private object GetMemberValue(object o, string memberName)
{
MemberInfo memberInfo = ReflectionXmlSerializationHelper.GetMember(o.GetType(), memberName);
object memberValue = GetMemberValue(o, memberInfo);
return memberValue;
}
private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, string n, string ns)
{
if (o is Enum)
{
Writer.WriteStartElement(n, ns);
EnumMapping enumMapping = null;
Type enumType = o.GetType();
foreach (var m in _mapping.Scope.TypeMappings)
{
if (m is EnumMapping em && em.TypeDesc.Type == enumType)
{
enumMapping = em;
break;
}
}
if (enumMapping == null)
throw new InvalidOperationException(SR.XmlInternalError);
WriteXsiType(enumMapping.TypeName, ns);
Writer.WriteString(WriteEnumMethod(enumMapping, o));
Writer.WriteEndElement();
return true;
}
if (o is Array)
{
Writer.WriteStartElement(n, ns);
ArrayMapping arrayMapping = null;
Type arrayType = o.GetType();
foreach (var m in _mapping.Scope.TypeMappings)
{
if (m is ArrayMapping am && am.TypeDesc.Type == arrayType)
{
arrayMapping = am;
break;
}
}
if (arrayMapping == null)
throw new InvalidOperationException(SR.XmlInternalError);
WriteXsiType(arrayMapping.TypeName, ns);
WriteMember(o, null, arrayMapping.ElementsSortedByDerivation, null, null, arrayMapping.TypeDesc, true);
Writer.WriteEndElement();
return true;
}
return false;
}
private string WriteEnumMethod(EnumMapping mapping, object v)
{
string returnString = null;
if (mapping != null)
{
ConstantMapping[] constants = mapping.Constants;
if (constants.Length > 0)
{
bool foundValue = false;
var enumValue = Convert.ToInt64(v);
for (int i = 0; i < constants.Length; i++)
{
ConstantMapping c = constants[i];
if (enumValue == c.Value)
{
returnString = c.XmlName;
foundValue = true;
break;
}
}
if (!foundValue)
{
if (mapping.IsFlags)
{
string[] xmlNames = new string[constants.Length];
long[] valueIds = new long[constants.Length];
for (int i = 0; i < constants.Length; i++)
{
xmlNames[i] = constants[i].XmlName;
valueIds[i] = constants[i].Value;
}
returnString = FromEnum(enumValue, xmlNames, valueIds);
}
else
{
throw CreateInvalidEnumValueException(v, mapping.TypeDesc.FullName);
}
}
}
}
else
{
returnString = v.ToString();
}
if (mapping.IsSoap)
{
WriteXsiType(mapping.TypeName, mapping.Namespace);
Writer.WriteString(returnString);
return null;
}
else
{
return returnString;
}
}
private object GetMemberValue(object o, MemberInfo memberInfo)
{
if (memberInfo is PropertyInfo memberProperty)
{
return memberProperty.GetValue(o);
}
else if (memberInfo is FieldInfo memberField)
{
return memberField.GetValue(o);
}
throw new InvalidOperationException(SR.XmlInternalError);
}
private void WriteMember(object memberValue, AttributeAccessor attribute, TypeDesc memberTypeDesc, object container)
{
if (memberTypeDesc.IsAbstract) return;
if (memberTypeDesc.IsArrayLike)
{
var sb = new StringBuilder();
TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc;
bool canOptimizeWriteListSequence = CanOptimizeWriteListSequence(arrayElementTypeDesc);
if (attribute.IsList)
{
if (canOptimizeWriteListSequence)
{
Writer.WriteStartAttribute(null, attribute.Name, attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty);
}
}
if (memberValue != null)
{
var a = (IEnumerable)memberValue;
IEnumerator e = a.GetEnumerator();
bool shouldAppendWhitespace = false;
if (e != null)
{
while (e.MoveNext())
{
object ai = e.Current;
if (attribute.IsList)
{
string stringValue;
if (attribute.Mapping is EnumMapping enumMapping)
{
stringValue = WriteEnumMethod(enumMapping, ai);
}
else
{
if (!WritePrimitiveValue(arrayElementTypeDesc, ai, true, out stringValue))
{
// #10593: Add More Tests for Serialization Code
Debug.Assert(ai is byte[]);
}
}
// check to see if we can write values of the attribute sequentially
if (canOptimizeWriteListSequence)
{
if (shouldAppendWhitespace)
{
Writer.WriteString(" ");
}
if (ai is byte[])
{
WriteValue((byte[])ai);
}
else
{
WriteValue(stringValue);
}
}
else
{
if (shouldAppendWhitespace)
{
sb.Append(" ");
}
sb.Append(stringValue);
}
}
else
{
WriteAttribute(ai, attribute, container);
}
shouldAppendWhitespace = true;
}
if (attribute.IsList)
{
// check to see if we can write values of the attribute sequentially
if (canOptimizeWriteListSequence)
{
Writer.WriteEndAttribute();
}
else
{
if (sb.Length != 0)
{
string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty;
WriteAttribute(attribute.Name, ns, sb.ToString());
}
}
}
}
}
}
else
{
WriteAttribute(memberValue, attribute, container);
}
}
private bool CanOptimizeWriteListSequence(TypeDesc listElementTypeDesc) {
// check to see if we can write values of the attribute sequentially
// currently we have only one data type (XmlQualifiedName) that we can not write "inline",
// because we need to output xmlns:qx="..." for each of the qnames
return (listElementTypeDesc != null && listElementTypeDesc != QnameTypeDesc);
}
private void WriteAttribute(object memberValue, AttributeAccessor attribute, object container)
{
// TODO: this block is never hit by our tests.
if (attribute.Mapping is SpecialMapping special)
{
if (special.TypeDesc.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue)
{
WriteXmlAttribute((XmlNode)memberValue, container);
}
else
{
throw new InvalidOperationException(SR.XmlInternalError);
}
}
else
{
string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty;
WritePrimitive(WritePrimitiveMethodRequirement.WriteAttribute, attribute.Name, ns, attribute.Default, memberValue, attribute.Mapping, false, false, false);
}
}
private int FindXmlnsIndex(MemberMapping[] members)
{
for (int i = 0; i < members.Length; i++)
{
if (members[i].Xmlns == null)
continue;
return i;
}
return -1;
}
private bool WriteDerivedTypes(StructMapping mapping, string n, string ns, object o, bool isNullable)
{
Type t = o.GetType();
for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping)
{
if (t == derived.TypeDesc.Type)
{
WriteStructMethod(derived, n, ns, o, isNullable, needType: true);
return true;
}
if (WriteDerivedTypes(derived, n, ns, o, isNullable))
{
return true;
}
}
return false;
}
private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, string ns, object defaultValue, object o, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable)
{
TypeDesc typeDesc = mapping.TypeDesc;
bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport;
if (hasDefault)
{
if (mapping is EnumMapping)
{
if (((EnumMapping)mapping).IsFlags)
{
IEnumerable<string> defaultEnumFlagValues = defaultValue.ToString().Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
string defaultEnumFlagString = string.Join(", ", defaultEnumFlagValues);
if (o.ToString() == defaultEnumFlagString)
return;
}
else
{
if (o.ToString() == defaultValue.ToString())
return;
}
}
else
{
if (IsDefaultValue(mapping, o, defaultValue, isNullable))
{
return;
}
}
}
XmlQualifiedName xmlQualifiedName = null;
if (writeXsiType)
{
xmlQualifiedName = new XmlQualifiedName(mapping.TypeName, mapping.Namespace);
}
string stringValue = null;
bool hasValidStringValue = false;
if (mapping is EnumMapping enumMapping)
{
stringValue = WriteEnumMethod(enumMapping, o);
hasValidStringValue = true;
}
else
{
hasValidStringValue = WritePrimitiveValue(typeDesc, o, isElement, out stringValue);
}
if (hasValidStringValue)
{
if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteElementString))
{
if (hasRequirement(method, WritePrimitiveMethodRequirement.Raw))
{
WriteElementString(name, ns, stringValue, xmlQualifiedName);
}
else
{
WriteElementStringRaw(name, ns, stringValue, xmlQualifiedName);
}
}
else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteNullableStringLiteral))
{
if (hasRequirement(method, WritePrimitiveMethodRequirement.Encoded))
{
if (hasRequirement(method, WritePrimitiveMethodRequirement.Raw))
{
WriteNullableStringEncoded(name, ns, stringValue, xmlQualifiedName);
}
else
{
WriteNullableStringEncodedRaw(name, ns, stringValue, xmlQualifiedName);
}
}
else
{
if (hasRequirement(method, WritePrimitiveMethodRequirement.Raw))
{
WriteNullableStringLiteral(name, ns, stringValue);
}
else
{
WriteNullableStringLiteralRaw(name, ns, stringValue);
}
}
}
else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteAttribute))
{
WriteAttribute(name, ns, stringValue);
}
else
{
Debug.Fail("#10593: Add More Tests for Serialization Code");
}
}
else if (o is byte[] a)
{
if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteElementString | WritePrimitiveMethodRequirement.Raw))
{
WriteElementStringRaw(name, ns, FromByteArrayBase64(a));
}
else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteNullableStringLiteral | WritePrimitiveMethodRequirement.Raw))
{
WriteNullableStringLiteralRaw(name, ns, FromByteArrayBase64(a));
}
else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteAttribute))
{
WriteAttribute(name, ns, a);
}
else
{
Debug.Fail("#10593: Add More Tests for Serialization Code");
}
}
else
{
Debug.Fail("#10593: Add More Tests for Serialization Code");
}
}
private bool hasRequirement(WritePrimitiveMethodRequirement value, WritePrimitiveMethodRequirement requirement)
{
return (value & requirement) == requirement;
}
private bool IsDefaultValue(TypeMapping mapping, object o, object value, bool isNullable)
{
if (value is string && ((string)value).Length == 0)
{
string str = (string)o;
return str == null || str.Length == 0;
}
else
{
return value.Equals(o);
}
}
private bool WritePrimitiveValue(TypeDesc typeDesc, object o, bool isElement, out string stringValue)
{
if (typeDesc == StringTypeDesc || typeDesc.FormatterName == "String")
{
stringValue = (string)o;
return true;
}
else
{
if (!typeDesc.HasCustomFormatter)
{
stringValue = ConvertPrimitiveToString(o, typeDesc);
return true;
}
else if (o is byte[] && typeDesc.FormatterName == "ByteArrayHex")
{
stringValue = FromByteArrayHex((byte[])o);
return true;
}
else if (o is DateTime)
{
if (typeDesc.FormatterName == "DateTime")
{
stringValue = FromDateTime((DateTime)o);
return true;
}
else if (typeDesc.FormatterName == "Date")
{
stringValue = FromDate((DateTime)o);
return true;
}
else if (typeDesc.FormatterName == "Time")
{
stringValue = FromTime((DateTime)o);
return true;
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Invalid DateTime"));
}
}
else if (typeDesc == QnameTypeDesc)
{
stringValue = FromXmlQualifiedName((XmlQualifiedName)o);
return true;
}
else if (o is string)
{
switch (typeDesc.FormatterName)
{
case "XmlName":
stringValue = FromXmlName((string)o);
break;
case "XmlNCName":
stringValue = FromXmlNCName((string)o);
break;
case "XmlNmToken":
stringValue = FromXmlNmToken((string)o);
break;
case "XmlNmTokens":
stringValue = FromXmlNmTokens((string)o);
break;
default:
stringValue = null;
return false;
}
return true;
}
else if (o is char && typeDesc.FormatterName == "Char")
{
stringValue = FromChar((char)o);
return true;
}
else if (o is byte[])
{
// we deal with byte[] specially in WritePrimitive()
}
else
{
throw new InvalidOperationException(SR.XmlInternalError);
}
}
stringValue = null;
return false;
}
private string ConvertPrimitiveToString(object o, TypeDesc typeDesc)
{
string stringValue;
switch (typeDesc.FormatterName)
{
case "Boolean":
stringValue = XmlConvert.ToString((bool)o);
break;
case "Int32":
stringValue = XmlConvert.ToString((int)o);
break;
case "Int16":
stringValue = XmlConvert.ToString((short)o);
break;
case "Int64":
stringValue = XmlConvert.ToString((long)o);
break;
case "Single":
stringValue = XmlConvert.ToString((float)o);
break;
case "Double":
stringValue = XmlConvert.ToString((double)o);
break;
case "Decimal":
stringValue = XmlConvert.ToString((decimal)o);
break;
case "Byte":
stringValue = XmlConvert.ToString((byte)o);
break;
case "SByte":
stringValue = XmlConvert.ToString((sbyte)o);
break;
case "UInt16":
stringValue = XmlConvert.ToString((ushort)o);
break;
case "UInt32":
stringValue = XmlConvert.ToString((uint)o);
break;
case "UInt64":
stringValue = XmlConvert.ToString((ulong)o);
break;
// Types without direct mapping (ambiguous)
case "Guid":
stringValue = XmlConvert.ToString((Guid)o);
break;
case "Char":
stringValue = XmlConvert.ToString((char)o);
break;
case "TimeSpan":
stringValue = XmlConvert.ToString((TimeSpan)o);
break;
default:
stringValue = o.ToString();
break;
}
return stringValue;
}
private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMapping)
{
ElementAccessor element = xmlMembersMapping.Accessor;
MembersMapping mapping = (MembersMapping)element.Mapping;
bool hasWrapperElement = mapping.HasWrapperElement;
bool writeAccessors = mapping.WriteAccessors;
bool isRpc = xmlMembersMapping.IsSoap && writeAccessors;
WriteStartDocument();
if (!mapping.IsSoap)
{
TopLevelElement();
}
object[] p = (object[])o;
int pLength = p.Length;
if (hasWrapperElement)
{
WriteStartElement(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty), mapping.IsSoap);
int xmlnsMember = FindXmlnsIndex(mapping.Members);
if (xmlnsMember >= 0)
{
MemberMapping member = mapping.Members[xmlnsMember];
var source = (XmlSerializerNamespaces)p[xmlnsMember];
if (pLength > xmlnsMember)
{
WriteNamespaceDeclarations(source);
}
}
for (int i = 0; i < mapping.Members.Length; i++)
{
MemberMapping member = mapping.Members[i];
if (member.Attribute != null && !member.Ignore)
{
object source = p[i];
bool? specifiedSource = null;
if (member.CheckSpecified != SpecifiedAccessor.None)
{
string memberNameSpecified = member.Name + "Specified";
for (int j = 0; j < Math.Min(pLength, mapping.Members.Length); j++)
{
if (mapping.Members[j].Name == memberNameSpecified)
{
specifiedSource = (bool) p[j];
break;
}
}
}
if (pLength > i && (specifiedSource == null || specifiedSource.Value))
{
WriteMember(source, member.Attribute, member.TypeDesc, null);
}
}
}
}
for (int i = 0; i < mapping.Members.Length; i++)
{
MemberMapping member = mapping.Members[i];
if (member.Xmlns != null)
continue;
if (member.Ignore)
continue;
bool? specifiedSource = null;
if (member.CheckSpecified != SpecifiedAccessor.None)
{
string memberNameSpecified = member.Name + "Specified";
for (int j = 0; j < Math.Min(pLength, mapping.Members.Length); j++)
{
if (mapping.Members[j].Name == memberNameSpecified)
{
specifiedSource = (bool)p[j];
break;
}
}
}
if (pLength > i)
{
if (specifiedSource == null || specifiedSource.Value)
{
object source = p[i];
object enumSource = null;
if (member.ChoiceIdentifier != null)
{
for (int j = 0; j < mapping.Members.Length; j++)
{
if (mapping.Members[j].Name == member.ChoiceIdentifier.MemberName)
{
enumSource = p[j];
break;
}
}
}
if (isRpc && member.IsReturnValue && member.Elements.Length > 0)
{
WriteRpcResult(member.Elements[0].Name, string.Empty);
}
// override writeAccessors choice when we've written a wrapper element
WriteMember(source, enumSource, member.ElementsSortedByDerivation, member.Text, member.ChoiceIdentifier, member.TypeDesc, writeAccessors || hasWrapperElement);
}
}
}
if (hasWrapperElement)
{
WriteEndElement();
}
if (element.IsSoap)
{
if (!hasWrapperElement && !writeAccessors)
{
// doc/bare case -- allow extra members
if (pLength > mapping.Members.Length)
{
for (int i = mapping.Members.Length; i < pLength; i++)
{
if (p[i] != null)
{
WritePotentiallyReferencingElement(null, null, p[i], p[i].GetType(), true, false);
}
}
}
}
WriteReferencedElements();
}
}
[Flags]
private enum WritePrimitiveMethodRequirement
{
None = 0,
Raw = 1,
WriteAttribute = 2,
WriteElementString = 4,
WriteNullableStringLiteral = 8,
Encoded = 16
}
}
internal class ReflectionXmlSerializationHelper
{
public static MemberInfo GetMember(Type declaringType, string memberName)
{
MemberInfo[] memberInfos = declaringType.GetMember(memberName);
if (memberInfos == null || memberInfos.Length == 0)
{
bool foundMatchedMember = false;
Type currentType = declaringType.BaseType;
while (currentType != null)
{
memberInfos = currentType.GetMember(memberName);
if (memberInfos != null && memberInfos.Length != 0)
{
foundMatchedMember = true;
break;
}
currentType = currentType.BaseType;
}
if (!foundMatchedMember)
{
throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, $"Could not find member named {memberName} of type {declaringType}"));
}
declaringType = currentType;
}
MemberInfo memberInfo = memberInfos[0];
if (memberInfos.Length != 1)
{
foreach (MemberInfo mi in memberInfos)
{
if (declaringType == mi.DeclaringType)
{
memberInfo = mi;
break;
}
}
}
return memberInfo;
}
}
}
| |
// 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 1.2.2.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataLake;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for DataLakeStoreAccountsOperations.
/// </summary>
public static partial class DataLakeStoreAccountsOperationsExtensions
{
/// <summary>
/// Updates the specified Data Lake Analytics account to include the additional
/// Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to which to add the Data Lake
/// Store account.
/// </param>
/// <param name='dataLakeStoreAccountName'>
/// The name of the Data Lake Store account to add.
/// </param>
/// <param name='parameters'>
/// The details of the Data Lake Store account.
/// </param>
public static void Add(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, string dataLakeStoreAccountName, AddDataLakeStoreParameters parameters = default(AddDataLakeStoreParameters))
{
operations.AddAsync(resourceGroupName, accountName, dataLakeStoreAccountName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the specified Data Lake Analytics account to include the additional
/// Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to which to add the Data Lake
/// Store account.
/// </param>
/// <param name='dataLakeStoreAccountName'>
/// The name of the Data Lake Store account to add.
/// </param>
/// <param name='parameters'>
/// The details of the Data Lake Store account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task AddAsync(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, string dataLakeStoreAccountName, AddDataLakeStoreParameters parameters = default(AddDataLakeStoreParameters), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.AddWithHttpMessagesAsync(resourceGroupName, accountName, dataLakeStoreAccountName, parameters, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Updates the Data Lake Analytics account specified to remove the specified
/// Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to remove the Data
/// Lake Store account.
/// </param>
/// <param name='dataLakeStoreAccountName'>
/// The name of the Data Lake Store account to remove
/// </param>
public static void Delete(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, string dataLakeStoreAccountName)
{
operations.DeleteAsync(resourceGroupName, accountName, dataLakeStoreAccountName).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the Data Lake Analytics account specified to remove the specified
/// Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to remove the Data
/// Lake Store account.
/// </param>
/// <param name='dataLakeStoreAccountName'>
/// The name of the Data Lake Store account to remove
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, string dataLakeStoreAccountName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, dataLakeStoreAccountName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified Data Lake Store account details in the specified Data
/// Lake Analytics account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to retrieve the Data
/// Lake Store account details.
/// </param>
/// <param name='dataLakeStoreAccountName'>
/// The name of the Data Lake Store account to retrieve
/// </param>
public static DataLakeStoreAccountInfo Get(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, string dataLakeStoreAccountName)
{
return operations.GetAsync(resourceGroupName, accountName, dataLakeStoreAccountName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified Data Lake Store account details in the specified Data
/// Lake Analytics account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to retrieve the Data
/// Lake Store account details.
/// </param>
/// <param name='dataLakeStoreAccountName'>
/// The name of the Data Lake Store account to retrieve
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataLakeStoreAccountInfo> GetAsync(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, string dataLakeStoreAccountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, accountName, dataLakeStoreAccountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the first page of Data Lake Store accounts linked to the specified
/// Data Lake Analytics account. The response includes a link to the next page,
/// if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account for which to list Data Lake
/// Store accounts.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
public static IPage<DataLakeStoreAccountInfo> ListByAccount(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, ODataQuery<DataLakeStoreAccountInfo> odataQuery = default(ODataQuery<DataLakeStoreAccountInfo>), string select = default(string), bool? count = default(bool?))
{
return ((IDataLakeStoreAccountsOperations)operations).ListByAccountAsync(resourceGroupName, accountName, odataQuery, select, count).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the first page of Data Lake Store accounts linked to the specified
/// Data Lake Analytics account. The response includes a link to the next page,
/// if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account for which to list Data Lake
/// Store accounts.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DataLakeStoreAccountInfo>> ListByAccountAsync(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, ODataQuery<DataLakeStoreAccountInfo> odataQuery = default(ODataQuery<DataLakeStoreAccountInfo>), string select = default(string), bool? count = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByAccountWithHttpMessagesAsync(resourceGroupName, accountName, odataQuery, select, count, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the first page of Data Lake Store accounts linked to the specified
/// Data Lake Analytics account. The response includes a link to the next page,
/// if any.
/// </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<DataLakeStoreAccountInfo> ListByAccountNext(this IDataLakeStoreAccountsOperations operations, string nextPageLink)
{
return operations.ListByAccountNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the first page of Data Lake Store accounts linked to the specified
/// Data Lake Analytics account. The response includes a link to the next page,
/// if any.
/// </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<DataLakeStoreAccountInfo>> ListByAccountNextAsync(this IDataLakeStoreAccountsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByAccountNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
namespace System.Collections.Specialized.Tests
{
public class CtorIntNvcTests
{
[Fact]
public void Test01()
{
NameValueCollection nvc;
NameValueCollection nvc1; // argument NameValueCollection
// simple string values
string[] values =
{
"",
" ",
"a",
"aa",
"tExt",
" SPaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// names(keys) for simple string values
string[] names =
{
"zero",
"oNe",
" ",
"",
"aA",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
// [] NameValueCollection is constructed as expected
//-----------------------------------------------------------------
nvc1 = new NameValueCollection(10);
//
// [] Create w/o capacity from empty w capacity
//
nvc = new NameValueCollection(nvc1);
if (nvc == null)
{
Assert.False(true, "Error, collection is null");
}
if (nvc.Count != 0)
{
Assert.False(true, string.Format("Error, Count = {0} ", nvc.Count));
}
// [] Create w capacity from empty w same capacity
nvc = new NameValueCollection(10, nvc1);
if (nvc == null)
{
Assert.False(true, "Error, collection is null");
}
if (nvc.Count != 0)
{
Assert.False(true, string.Format("Error, Count = {0} ", nvc.Count));
}
//
//
// [] Create w capacity from empty w greater capacity
nvc = new NameValueCollection(5, nvc1);
if (nvc == null)
{
Assert.False(true, "Error, collection is null");
}
if (nvc.Count != 0)
{
Assert.False(true, string.Format("Error, Count = {0} ", nvc.Count));
}
// [] Create w capacity from empty w smaller capacity
nvc = new NameValueCollection(50, nvc1);
if (nvc == null)
{
Assert.False(true, "Error, collection is null");
}
if (nvc.Count != 0)
{
Assert.False(true, string.Format("Error, Count = {0} ", nvc.Count));
}
///////////////////////////////////////////////////////////////
//
// create from filled collection
// [] Create from filled collection - smaller capacity
//
int len = values.Length;
for (int i = 0; i < len; i++)
{
nvc1.Add(names[i], values[i]);
}
if (nvc1.Count != len)
{
Assert.False(true, string.Format("Error, Count = {0} after instead of {1}", nvc.Count, len));
}
nvc = new NameValueCollection(len / 2, nvc1);
if (nvc.Count != nvc1.Count)
{
Assert.False(true, string.Format("Error, Count = {0} instead of {1}", nvc.Count, nvc1.Count));
}
string[] keys1 = nvc1.AllKeys;
string[] keys = nvc.AllKeys;
if (keys1.Length != keys.Length)
{
Assert.False(true, string.Format("Error, new collection Keys.Length is {0} instead of {1}", keys.Length, keys1.Length));
}
else
{
for (int i = 0; i < keys1.Length; i++)
{
if (Array.IndexOf(keys, keys1[i]) < 0)
{
Assert.False(true, string.Format("Error, no key \"{1}\" in AllKeys", i, keys1[i]));
}
}
}
for (int i = 0; i < keys.Length; i++)
{
string[] val = nvc.GetValues(keys[i]);
if ((val.Length != 1) || String.Compare(val[0], (nvc1.GetValues(keys[i]))[0]) != 0)
{
Assert.False(true, string.Format("Error, unexpected value at key \"{1}\"", i, keys1[i]));
}
}
//
// [] Create from filled collection - count capacity
//
len = values.Length;
nvc = new NameValueCollection(len, nvc1);
if (nvc.Count != nvc1.Count)
{
Assert.False(true, string.Format("Error, Count = {0} instead of {1}", nvc.Count, nvc1.Count));
}
keys1 = nvc1.AllKeys;
keys = nvc.AllKeys;
if (keys1.Length != keys.Length)
{
Assert.False(true, string.Format("Error, new collection Keys.Length is {0} instead of {1}", keys.Length, keys1.Length));
}
else
{
for (int i = 0; i < keys1.Length; i++)
{
if (Array.IndexOf(keys, keys1[i]) < 0)
{
Assert.False(true, string.Format("Error, no key \"{1}\" in AllKeys", i, keys1[i]));
}
}
}
for (int i = 0; i < keys.Length; i++)
{
string[] val = nvc.GetValues(keys[i]);
if ((val.Length != 1) || String.Compare(val[0], (nvc1.GetValues(keys[i]))[0]) != 0)
{
Assert.False(true, string.Format("Error, unexpected value at key \"{1}\"", i, keys1[i]));
}
}
//
// [] Create from filled collection - greater capacity capacity
//
len = values.Length;
nvc = new NameValueCollection(len * 2, nvc1);
if (nvc.Count != nvc1.Count)
{
Assert.False(true, string.Format("Error, Count = {0} instead of {1}", nvc.Count, nvc1.Count));
}
keys1 = nvc1.AllKeys;
keys = nvc.AllKeys;
if (keys1.Length != keys.Length)
{
Assert.False(true, string.Format("Error, new collection Keys.Length is {0} instead of {1}", keys.Length, keys1.Length));
}
else
{
for (int i = 0; i < keys1.Length; i++)
{
if (Array.IndexOf(keys, keys1[i]) < 0)
{
Assert.False(true, string.Format("Error, no key \"{1}\" in AllKeys", i, keys1[i]));
}
}
}
for (int i = 0; i < keys.Length; i++)
{
string[] val = nvc.GetValues(keys[i]);
if ((val.Length != 1) || String.Compare(val[0], (nvc1.GetValues(keys[i]))[0]) != 0)
{
Assert.False(true, string.Format("Error, unexpected value at key \"{1}\"", i, keys1[i]));
}
}
//
// [] change argument collection
//
string toChange = keys1[0];
string init = nvc1[toChange];
//
// Change element
//
nvc1[toChange] = "new Value";
if (String.Compare(nvc1[toChange], "new Value") != 0)
{
Assert.False(true, "Error, failed to change element");
}
if (String.Compare(nvc[toChange], init) != 0)
{
Assert.False(true, "Error, changed element in new collection");
}
//
// Remove element
//
nvc1.Remove(toChange);
if (nvc1.Count != len - 1)
{
Assert.False(true, "Error, failed to remove element");
}
if (nvc.Count != len)
{
Assert.False(true, "Error, collection changed after argument change - removed element");
}
keys = nvc.AllKeys;
if (Array.IndexOf(keys, toChange) < 0)
{
Assert.False(true, "Error, collection changed after argument change - no key");
}
//
// [] invalid parameter - negative capacity
//
Assert.Throws<ArgumentOutOfRangeException>(() => { nvc = new NameValueCollection(-1, nvc1); });
//
// [] invalid parameter - null collection
//
Assert.Throws<ArgumentNullException>(() => { nvc = new NameValueCollection(10, (NameValueCollection)null); });
}
}
}
| |
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace Pomelo.EntityFrameworkCore.MySql.FunctionalTests.Query
{
public partial class NorthwindDbFunctionsQueryMySqlTest
{
[ConditionalFact]
public virtual void DateDiff_Year()
{
using (var context = CreateContext())
{
var count = context.Orders
.Count(c => EF.Functions.DateDiffYear(c.OrderDate, DateTime.Now) == 0);
Assert.Equal(0, count);
AssertSql(
@"SELECT COUNT(*)
FROM `Orders` AS `o`
WHERE TIMESTAMPDIFF(YEAR, `o`.`OrderDate`, CURRENT_TIMESTAMP()) = 0");
}
}
[ConditionalFact]
public virtual void DateDiff_Month()
{
using (var context = CreateContext())
{
var count = context.Orders
.Count(c => EF.Functions.DateDiffMonth(c.OrderDate, DateTime.Now) == 0);
Assert.Equal(0, count);
AssertSql(
@"SELECT COUNT(*)
FROM `Orders` AS `o`
WHERE TIMESTAMPDIFF(MONTH, `o`.`OrderDate`, CURRENT_TIMESTAMP()) = 0");
}
}
[ConditionalFact]
public virtual void DateDiff_Day()
{
using (var context = CreateContext())
{
var count = context.Orders
.Count(c => EF.Functions.DateDiffDay(c.OrderDate, DateTime.Now) == 0);
Assert.Equal(0, count);
AssertSql(
@"SELECT COUNT(*)
FROM `Orders` AS `o`
WHERE TIMESTAMPDIFF(DAY, `o`.`OrderDate`, CURRENT_TIMESTAMP()) = 0");
}
}
[ConditionalFact]
public virtual void DateDiff_Hour()
{
using (var context = CreateContext())
{
var count = context.Orders
.Count(o => EF.Functions.DateDiffHour(o.OrderDate, DateTime.Now) == 0);
Assert.Equal(0, count);
AssertSql(
@"SELECT COUNT(*)
FROM `Orders` AS `o`
WHERE TIMESTAMPDIFF(HOUR, `o`.`OrderDate`, CURRENT_TIMESTAMP()) = 0");
}
}
[ConditionalFact]
public virtual void DateDiff_Minute()
{
using (var context = CreateContext())
{
var count = context.Orders
.Count(c => EF.Functions.DateDiffMinute(c.OrderDate, DateTime.Now) == 0);
Assert.Equal(0, count);
AssertSql(
@"SELECT COUNT(*)
FROM `Orders` AS `o`
WHERE TIMESTAMPDIFF(MINUTE, `o`.`OrderDate`, CURRENT_TIMESTAMP()) = 0");
}
}
[ConditionalFact]
public virtual void DateDiff_Second()
{
using (var context = CreateContext())
{
var count = context.Orders
.Count(o => EF.Functions.DateDiffSecond(o.OrderDate, DateTime.Now) == 0);
Assert.Equal(0, count);
AssertSql(
@"SELECT COUNT(*)
FROM `Orders` AS `o`
WHERE TIMESTAMPDIFF(SECOND, `o`.`OrderDate`, CURRENT_TIMESTAMP()) = 0");
}
}
[ConditionalFact]
public virtual void DateDiff_Microsecond()
{
using (var context = CreateContext())
{
var count = context.Orders
.Count(o => EF.Functions.DateDiffMicrosecond(DateTime.Now, DateTime.Now.AddSeconds(1)) == 0);
Assert.Equal(0, count);
AssertSql(
@"SELECT COUNT(*)
FROM `Orders` AS `o`
WHERE TIMESTAMPDIFF(MICROSECOND, CURRENT_TIMESTAMP(), DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL CAST(1.0 AS signed) second)) = 0");
}
}
[ConditionalFact]
public virtual void Like_Int_literal()
{
using (var context = CreateContext())
{
var count = context.Orders.Count(o => EF.Functions.Like(o.OrderID, "%M%"));
Assert.Equal(0, count);
AssertSql(
@"SELECT COUNT(*)
FROM `Orders` AS `o`
WHERE `o`.`OrderID` LIKE '%M%'");
}
}
[ConditionalFact]
public virtual void Like_DateTime_literal()
{
using (var context = CreateContext())
{
var count = context.Orders.Count(o => EF.Functions.Like(o.OrderDate, "%M%"));
Assert.Equal(0, count);
AssertSql(
@"SELECT COUNT(*)
FROM `Orders` AS `o`
WHERE `o`.`OrderDate` LIKE '%M%'");
}
}
[ConditionalFact]
public virtual void Like_Uint_literal()
{
using (var context = CreateContext())
{
var count = context.Orders.Count(o => EF.Functions.Like(o.EmployeeID, "%M%"));
Assert.Equal(0, count);
AssertSql(
@"SELECT COUNT(*)
FROM `Orders` AS `o`
WHERE `o`.`EmployeeID` LIKE '%M%'");
}
}
[ConditionalFact]
public virtual void Like_Short_literal()
{
using (var context = CreateContext())
{
var count = context.OrderDetails.Count(o => EF.Functions.Like(o.Quantity, "%M%"));
Assert.Equal(0, count);
AssertSql(
@"SELECT COUNT(*)
FROM `Order Details` AS `o`
WHERE `o`.`Quantity` LIKE '%M%'");
}
}
[ConditionalFact]
public virtual void Like_Int_literal_with_escape()
{
using (var context = CreateContext())
{
var count = context.Orders.Count(o => EF.Functions.Like(o.OrderID, "!%", "!"));
Assert.Equal(0, count);
AssertSql(
@"SELECT COUNT(*)
FROM `Orders` AS `o`
WHERE `o`.`OrderID` LIKE '!%' ESCAPE '!'");
}
}
[ConditionalFact]
public virtual void Hex()
{
using (var context = CreateContext())
{
var count = context.Orders
.Count(o => EF.Functions.Hex(o.CustomerID) == "56494E4554");
Assert.Equal(5, count);
AssertSql(
@"SELECT COUNT(*)
FROM `Orders` AS `o`
WHERE HEX(`o`.`CustomerID`) = '56494E4554'");
}
}
[ConditionalFact]
public virtual void Unhex()
{
using (var context = CreateContext())
{
var count = context.Orders
.Count(o => EF.Functions.Unhex(EF.Functions.Hex(o.CustomerID)) == "VINET");
Assert.Equal(5, count);
AssertSql(
@"SELECT COUNT(*)
FROM `Orders` AS `o`
WHERE UNHEX(HEX(`o`.`CustomerID`)) = 'VINET'");
}
}
[ConditionalFact]
public virtual void Degrees()
{
var degrees = 90.0;
var radians = Math.PI / 180.0 * degrees;
using var context = CreateContext();
var office = context.Customers
.Select(c => new { c.CustomerID, OfficeRoofAngleDegrees = EF.Functions.Degrees(radians) })
.First(c => c.CustomerID == "VINET");
Assert.Equal(degrees, office.OfficeRoofAngleDegrees);
AssertSql(
@"@__radians_1='1.5707963267948966'
SELECT `c`.`CustomerID`, DEGREES(@__radians_1) AS `OfficeRoofAngleDegrees`
FROM `Customers` AS `c`
WHERE `c`.`CustomerID` = 'VINET'
LIMIT 1");
}
[ConditionalFact]
public virtual void Radians()
{
var degrees = 90.0;
var radians = Math.PI / 180.0 * degrees;
using var context = CreateContext();
var office = context.Customers
.Select(c => new { c.CustomerID, OfficeRoofAngleRadians = EF.Functions.Radians(degrees) })
.First(c => c.CustomerID == "VINET");
Assert.Equal(radians, office.OfficeRoofAngleRadians);
AssertSql(
@"@__degrees_1='90'
SELECT `c`.`CustomerID`, RADIANS(@__degrees_1) AS `OfficeRoofAngleRadians`
FROM `Customers` AS `c`
WHERE `c`.`CustomerID` = 'VINET'
LIMIT 1");
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Data.Entity.Migrations;
using Microsoft.Data.Entity.SqlServer.Metadata;
namespace Matozap.Entities.Migrations
{
public partial class initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Cinema",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
Name = table.Column<string>(isNullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Cinema", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Country",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
Name = table.Column<string>(isNullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Country", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Fixture",
columns: table => new
{
Id = table.Column<string>(isNullable: false),
AwayTeamId = table.Column<string>(isNullable: true),
AwayTeamName = table.Column<string>(isNullable: true),
Date = table.Column<DateTime>(isNullable: false),
GoalsAwayTeam = table.Column<int>(isNullable: false),
GoalsHomeTeam = table.Column<int>(isNullable: false),
HomeTeamId = table.Column<string>(isNullable: true),
HomeTeamName = table.Column<string>(isNullable: true),
Matchday = table.Column<int>(isNullable: false),
Status = table.Column<string>(isNullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Fixture", x => x.Id);
});
migrationBuilder.CreateTable(
name: "League",
columns: table => new
{
Id = table.Column<string>(isNullable: false),
Name = table.Column<string>(isNullable: false),
Region = table.Column<string>(isNullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_League", x => x.Id);
});
migrationBuilder.CreateTable(
name: "LeagueTable",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
Caption = table.Column<string>(isNullable: false),
Matchday = table.Column<int>(isNullable: false),
SeasonId = table.Column<int>(isNullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_LeagueTable", x => x.Id);
});
migrationBuilder.CreateTable(
name: "LeagueTableStanding",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
GoalDifference = table.Column<int>(isNullable: false),
Goals = table.Column<int>(isNullable: false),
GoalsAgainst = table.Column<int>(isNullable: false),
LeagueTableId = table.Column<int>(isNullable: false),
PlayedGames = table.Column<int>(isNullable: false),
Points = table.Column<int>(isNullable: false),
Position = table.Column<int>(isNullable: false),
TeamId = table.Column<string>(isNullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_LeagueTableStanding", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Movie",
columns: table => new
{
Id = table.Column<Guid>(isNullable: false),
Director = table.Column<string>(isNullable: false),
ReleaseDate = table.Column<DateTime>(isNullable: false),
TicketPrice = table.Column<decimal>(isNullable: false),
Title = table.Column<string>(isNullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Movie", x => x.Id);
});
migrationBuilder.CreateTable(
name: "News",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
Author = table.Column<string>(isNullable: true),
Body = table.Column<string>(isNullable: true),
ImageURL = table.Column<string>(isNullable: true),
ReferenceURL = table.Column<string>(isNullable: true),
Title = table.Column<string>(isNullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_News", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Player",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
ContractUntil = table.Column<DateTime>(isNullable: false),
DateOfBirth = table.Column<DateTime>(isNullable: false),
JerseryNumber = table.Column<string>(isNullable: true),
MarketValue = table.Column<string>(isNullable: true),
Name = table.Column<string>(isNullable: false),
Nationality = table.Column<string>(isNullable: true),
Position = table.Column<string>(isNullable: true),
TeamId = table.Column<string>(isNullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Player", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Season",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
Caption = table.Column<string>(isNullable: false),
LastUpdated = table.Column<DateTime>(isNullable: false),
LeagueId = table.Column<string>(isNullable: true),
NumberOfTeams = table.Column<int>(isNullable: false),
Year = table.Column<int>(isNullable: false),
numberOfGames = table.Column<int>(isNullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Season", x => x.Id);
});
migrationBuilder.CreateTable(
name: "SystemPreference",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
Category = table.Column<string>(isNullable: true),
Description = table.Column<string>(isNullable: true),
Key = table.Column<string>(isNullable: false),
Value = table.Column<string>(isNullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SystemPreference", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Team",
columns: table => new
{
Id = table.Column<string>(isNullable: false),
Code = table.Column<string>(isNullable: true),
CrestUrl = table.Column<string>(isNullable: true),
Name = table.Column<string>(isNullable: false),
ShortName = table.Column<string>(isNullable: true),
SquadMarketValue = table.Column<string>(isNullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Team", x => x.Id);
});
migrationBuilder.CreateTable(
name: "UserPreference",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
Category = table.Column<string>(isNullable: true),
Description = table.Column<string>(isNullable: true),
Key = table.Column<string>(isNullable: false),
UserId = table.Column<int>(isNullable: false),
Value = table.Column<string>(isNullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserPreference", x => x.Id);
});
migrationBuilder.CreateTable(
name: "UserProfile",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
BirthCountryCode = table.Column<string>(isNullable: true),
Birthday = table.Column<DateTime>(isNullable: false),
FistName = table.Column<string>(isNullable: true),
Nickname = table.Column<string>(isNullable: false),
Surname = table.Column<string>(isNullable: true),
UserId = table.Column<int>(isNullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserProfile", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Roles",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
ConcurrencyStamp = table.Column<string>(isNullable: true),
Disabled = table.Column<bool>(isNullable: false),
Name = table.Column<string>(isNullable: true),
NormalizedName = table.Column<string>(isNullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ApplicationRole", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
AccessFailedCount = table.Column<int>(isNullable: false),
ConcurrencyStamp = table.Column<string>(isNullable: true),
Disabled = table.Column<bool>(isNullable: false),
Email = table.Column<string>(isNullable: true),
EmailConfirmed = table.Column<bool>(isNullable: false),
LastKnownIP = table.Column<string>(isNullable: true),
LastLoginDate = table.Column<DateTime>(isNullable: true),
LockoutEnabled = table.Column<bool>(isNullable: false),
LockoutEnd = table.Column<DateTimeOffset>(isNullable: true),
NormalizedEmail = table.Column<string>(isNullable: true),
NormalizedUserName = table.Column<string>(isNullable: true),
PasswordHash = table.Column<string>(isNullable: true),
PhoneNumber = table.Column<string>(isNullable: true),
PhoneNumberConfirmed = table.Column<bool>(isNullable: false),
SecurityStamp = table.Column<string>(isNullable: true),
TwoFactorEnabled = table.Column<bool>(isNullable: false),
UserName = table.Column<string>(isNullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ApplicationUser", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Actor",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
MovieId = table.Column<Guid>(isNullable: false),
Name = table.Column<string>(isNullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Actor", x => x.Id);
table.ForeignKey(
name: "FK_Actor_Movie_MovieId",
column: x => x.MovieId,
principalTable: "Movie",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "RoleClaims",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
ClaimType = table.Column<string>(isNullable: true),
ClaimValue = table.Column<string>(isNullable: true),
RoleId = table.Column<int>(isNullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityRoleClaim<int>", x => x.Id);
table.ForeignKey(
name: "FK_IdentityRoleClaim<int>_ApplicationRole_RoleId",
column: x => x.RoleId,
principalTable: "Roles",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "UserClaims",
columns: table => new
{
Id = table.Column<int>(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
ClaimType = table.Column<string>(isNullable: true),
ClaimValue = table.Column<string>(isNullable: true),
UserId = table.Column<int>(isNullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityUserClaim<int>", x => x.Id);
table.ForeignKey(
name: "FK_IdentityUserClaim<int>_ApplicationUser_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "UserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(isNullable: false),
ProviderKey = table.Column<string>(isNullable: false),
ProviderDisplayName = table.Column<string>(isNullable: true),
UserId = table.Column<int>(isNullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityUserLogin<int>", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_IdentityUserLogin<int>_ApplicationUser_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "UserRoles",
columns: table => new
{
UserId = table.Column<int>(isNullable: false),
RoleId = table.Column<int>(isNullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityUserRole<int>", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_IdentityUserRole<int>_ApplicationRole_RoleId",
column: x => x.RoleId,
principalTable: "Roles",
principalColumn: "Id");
table.ForeignKey(
name: "FK_IdentityUserRole<int>_ApplicationUser_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id");
});
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "Roles",
column: "NormalizedName");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "Users",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "Users",
column: "NormalizedUserName");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable("Actor");
migrationBuilder.DropTable("Cinema");
migrationBuilder.DropTable("Country");
migrationBuilder.DropTable("Fixture");
migrationBuilder.DropTable("League");
migrationBuilder.DropTable("LeagueTable");
migrationBuilder.DropTable("LeagueTableStanding");
migrationBuilder.DropTable("News");
migrationBuilder.DropTable("Player");
migrationBuilder.DropTable("Season");
migrationBuilder.DropTable("SystemPreference");
migrationBuilder.DropTable("Team");
migrationBuilder.DropTable("UserPreference");
migrationBuilder.DropTable("UserProfile");
migrationBuilder.DropTable("RoleClaims");
migrationBuilder.DropTable("UserClaims");
migrationBuilder.DropTable("UserLogins");
migrationBuilder.DropTable("UserRoles");
migrationBuilder.DropTable("Movie");
migrationBuilder.DropTable("Roles");
migrationBuilder.DropTable("Users");
}
}
}
| |
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory.
using Parse.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Parse {
/// <summary>
/// Represents a user for a Parse application.
/// </summary>
[ParseClassName("_User")]
public class ParseUser : ParseObject {
private static readonly IDictionary<string, IParseAuthenticationProvider> authProviders =
new Dictionary<string, IParseAuthenticationProvider>();
private static readonly HashSet<string> readOnlyKeys = new HashSet<string> {
"sessionToken", "isNew"
};
internal static IParseUserController UserController {
get {
return ParseCorePlugins.Instance.UserController;
}
}
internal static IParseCurrentUserController CurrentUserController {
get {
return ParseCorePlugins.Instance.CurrentUserController;
}
}
/// <summary>
/// Whether the ParseUser has been authenticated on this device. Only an authenticated
/// ParseUser can be saved and deleted.
/// </summary>
public bool IsAuthenticated {
get {
lock (mutex) {
return SessionToken != null &&
CurrentUser != null &&
CurrentUser.ObjectId == ObjectId;
}
}
}
/// <summary>
/// Removes a key from the object's data if it exists.
/// </summary>
/// <param name="key">The key to remove.</param>
/// <exception cref="System.ArgumentException">Cannot remove the username key.</exception>
public override void Remove(string key) {
if (key == "username") {
throw new ArgumentException("Cannot remove the username key.");
}
base.Remove(key);
}
internal override bool IsKeyMutable(string key) {
return !readOnlyKeys.Contains(key);
}
internal override void HandleSave(IObjectState serverState) {
base.HandleSave(serverState);
SynchronizeAllAuthData();
CleanupAuthData();
MutateState(mutableClone => {
mutableClone.ServerData.Remove("password");
});
}
internal string SessionToken {
get {
if (State.ContainsKey("sessionToken")) {
return State["sessionToken"] as string;
}
return null;
}
}
internal static string CurrentSessionToken {
get {
Task<string> sessionTokenTask = GetCurrentSessionTokenAsync();
sessionTokenTask.Wait();
return sessionTokenTask.Result;
}
}
internal static Task<string> GetCurrentSessionTokenAsync(CancellationToken cancellationToken = default(CancellationToken)) {
return CurrentUserController.GetCurrentSessionTokenAsync(cancellationToken);
}
internal Task SetSessionTokenAsync(string newSessionToken) {
return SetSessionTokenAsync(newSessionToken, CancellationToken.None);
}
internal Task SetSessionTokenAsync(string newSessionToken, CancellationToken cancellationToken) {
MutateState(mutableClone => {
mutableClone.ServerData["sessionToken"] = newSessionToken;
});
return SaveCurrentUserAsync(this);
}
/// <summary>
/// Gets or sets the username.
/// </summary>
[ParseFieldName("username")]
public string Username {
get { return GetProperty<string>(null, "Username"); }
set { SetProperty(value, "Username"); }
}
/// <summary>
/// Sets the password.
/// </summary>
[ParseFieldName("password")]
public string Password {
private get { return GetProperty<string>(null, "Password"); }
set { SetProperty(value, "Password"); }
}
/// <summary>
/// Sets the email address.
/// </summary>
[ParseFieldName("email")]
public string Email {
get { return GetProperty<string>(null, "Email"); }
set { SetProperty(value, "Email"); }
}
internal Task SignUpAsync(Task toAwait, CancellationToken cancellationToken) {
if (AuthData == null) {
// TODO (hallucinogen): make an Extension of Task to create Task with exception/canceled.
if (string.IsNullOrEmpty(Username)) {
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
tcs.TrySetException(new InvalidOperationException("Cannot sign up user with an empty name."));
return tcs.Task;
}
if (string.IsNullOrEmpty(Password)) {
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
tcs.TrySetException(new InvalidOperationException("Cannot sign up user with an empty password."));
return tcs.Task;
}
}
if (!string.IsNullOrEmpty(ObjectId)) {
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
tcs.TrySetException(new InvalidOperationException("Cannot sign up a user that already exists."));
return tcs.Task;
}
IDictionary<string, IParseFieldOperation> currentOperations = StartSave();
return toAwait.OnSuccess(_ => {
return UserController.SignUpAsync(State, currentOperations, cancellationToken);
}).Unwrap().ContinueWith(t => {
if (t.IsFaulted || t.IsCanceled) {
HandleFailedSave(currentOperations);
} else {
var serverState = t.Result;
HandleSave(serverState);
}
return t;
}).Unwrap().OnSuccess(_ => SaveCurrentUserAsync(this)).Unwrap();
}
/// <summary>
/// Signs up a new user. This will create a new ParseUser on the server and will also persist the
/// session on disk so that you can access the user using <see cref="CurrentUser"/>. A username and
/// password must be set before calling SignUpAsync.
/// </summary>
public Task SignUpAsync() {
return SignUpAsync(CancellationToken.None);
}
/// <summary>
/// Signs up a new user. This will create a new ParseUser on the server and will also persist the
/// session on disk so that you can access the user using <see cref="CurrentUser"/>. A username and
/// password must be set before calling SignUpAsync.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
public Task SignUpAsync(CancellationToken cancellationToken) {
return taskQueue.Enqueue(toAwait => SignUpAsync(toAwait, cancellationToken),
cancellationToken);
}
/// <summary>
/// Logs in a user with a username and password. On success, this saves the session to disk so you
/// can retrieve the currently logged in user using <see cref="CurrentUser"/>.
/// </summary>
/// <param name="username">The username to log in with.</param>
/// <param name="password">The password to log in with.</param>
/// <returns>The newly logged-in user.</returns>
public static Task<ParseUser> LogInAsync(string username, string password) {
return LogInAsync(username, password, CancellationToken.None);
}
/// <summary>
/// Logs in a user with a username and password. On success, this saves the session to disk so you
/// can retrieve the currently logged in user using <see cref="CurrentUser"/>.
/// </summary>
/// <param name="username">The username to log in with.</param>
/// <param name="password">The password to log in with.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The newly logged-in user.</returns>
public static Task<ParseUser> LogInAsync(string username,
string password,
CancellationToken cancellationToken) {
return UserController.LogInAsync(username, password, cancellationToken).OnSuccess(t => {
ParseUser user = ParseObject.FromState<ParseUser>(t.Result, "_User");
return SaveCurrentUserAsync(user).OnSuccess(_ => user);
}).Unwrap();
}
/// <summary>
/// Logs in a user with a username and password. On success, this saves the session to disk so you
/// can retrieve the currently logged in user using <see cref="CurrentUser"/>.
/// </summary>
/// <param name="sessionToken">The session token to authorize with</param>
/// <returns>The user if authorization was successful</returns>
public static Task<ParseUser> BecomeAsync(string sessionToken) {
return BecomeAsync(sessionToken, CancellationToken.None);
}
/// <summary>
/// Logs in a user with a username and password. On success, this saves the session to disk so you
/// can retrieve the currently logged in user using <see cref="CurrentUser"/>.
/// </summary>
/// <param name="sessionToken">The session token to authorize with</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The user if authorization was successful</returns>
public static Task<ParseUser> BecomeAsync(string sessionToken, CancellationToken cancellationToken) {
return UserController.GetUserAsync(sessionToken, cancellationToken).OnSuccess(t => {
ParseUser user = ParseObject.FromState<ParseUser>(t.Result, "_User");
return SaveCurrentUserAsync(user).OnSuccess(_ => user);
}).Unwrap();
}
internal override Task SaveAsync(Task toAwait, CancellationToken cancellationToken) {
lock (mutex) {
if (ObjectId == null) {
throw new InvalidOperationException("You must call SignUpAsync before calling SaveAsync.");
}
return base.SaveAsync(toAwait, cancellationToken).OnSuccess(_ => {
if (!CurrentUserController.IsCurrent(this)) {
return Task.FromResult(0);
}
return SaveCurrentUserAsync(this);
}).Unwrap();
}
}
internal override Task<ParseObject> FetchAsyncInternal(Task toAwait, CancellationToken cancellationToken) {
return base.FetchAsyncInternal(toAwait, cancellationToken).OnSuccess(t => {
if (!CurrentUserController.IsCurrent(this)) {
return Task<ParseObject>.FromResult(t.Result);
}
// If this is already the current user, refresh its state on disk.
return SaveCurrentUserAsync(this).OnSuccess(_ => t.Result);
}).Unwrap();
}
/// <summary>
/// Logs out the currently logged in user session. This will remove the session from disk, log out of
/// linked services, and future calls to <see cref="CurrentUser"/> will return <c>null</c>.
/// </summary>
/// <remarks>
/// Typically, you should use <see cref="LogOutAsync()"/>, unless you are managing your own threading.
/// </remarks>
public static void LogOut() {
// TODO (hallucinogen): this will without a doubt fail in Unity. But what else can we do?
LogOutAsync().Wait();
}
/// <summary>
/// Logs out the currently logged in user session. This will remove the session from disk, log out of
/// linked services, and future calls to <see cref="CurrentUser"/> will return <c>null</c>.
/// </summary>
/// <remarks>
/// This is preferable to using <see cref="LogOut()"/>, unless your code is already running from a
/// background thread.
/// </remarks>
public static Task LogOutAsync() {
return LogOutAsync(CancellationToken.None);
}
/// <summary>
/// Logs out the currently logged in user session. This will remove the session from disk, log out of
/// linked services, and future calls to <see cref="CurrentUser"/> will return <c>null</c>.
///
/// This is preferable to using <see cref="LogOut()"/>, unless your code is already running from a
/// background thread.
/// </summary>
public static Task LogOutAsync(CancellationToken cancellationToken) {
return GetCurrentUserAsync().OnSuccess(t => {
LogOutWithProviders();
ParseUser user = t.Result;
if (user == null) {
return Task.FromResult(0);
}
return user.taskQueue.Enqueue(toAwait => user.LogOutAsync(toAwait, cancellationToken), cancellationToken);
}).Unwrap();
}
internal Task LogOutAsync(Task toAwait, CancellationToken cancellationToken) {
string oldSessionToken = SessionToken;
if (oldSessionToken == null) {
return Task.FromResult(0);
}
// Cleanup in-memory session.
MutateState(mutableClone => {
mutableClone.ServerData.Remove("sessionToken");
});
var revokeSessionTask = ParseSession.RevokeAsync(oldSessionToken, cancellationToken);
return Task.WhenAll(revokeSessionTask, CurrentUserController.LogOutAsync(cancellationToken));
}
private static void LogOutWithProviders() {
foreach (var provider in authProviders.Values) {
provider.Deauthenticate();
}
}
/// <summary>
/// Gets the currently logged in ParseUser with a valid session, either from memory or disk
/// if necessary.
/// </summary>
public static ParseUser CurrentUser {
get {
var userTask = GetCurrentUserAsync();
// TODO (hallucinogen): this will without a doubt fail in Unity. How should we fix it?
userTask.Wait();
return userTask.Result;
}
}
/// <summary>
/// Gets the currently logged in ParseUser with a valid session, either from memory or disk
/// if necessary, asynchronously.
/// </summary>
internal static Task<ParseUser> GetCurrentUserAsync() {
return GetCurrentUserAsync(CancellationToken.None);
}
/// <summary>
/// Gets the currently logged in ParseUser with a valid session, either from memory or disk
/// if necessary, asynchronously.
/// </summary>
internal static Task<ParseUser> GetCurrentUserAsync(CancellationToken cancellationToken) {
return CurrentUserController.GetAsync(cancellationToken);
}
private static Task SaveCurrentUserAsync(ParseUser user) {
return SaveCurrentUserAsync(user, CancellationToken.None);
}
private static Task SaveCurrentUserAsync(ParseUser user, CancellationToken cancellationToken) {
return CurrentUserController.SetAsync(user, cancellationToken);
}
internal static void ClearInMemoryUser() {
CurrentUserController.ClearFromMemory();
}
/// <summary>
/// Constructs a <see cref="ParseQuery{ParseUser}"/> for ParseUsers.
/// </summary>
public static ParseQuery<ParseUser> Query {
get {
return new ParseQuery<ParseUser>();
}
}
#region Legacy / Revocable Session Tokens
private static readonly object isRevocableSessionEnabledMutex = new object();
private static bool isRevocableSessionEnabled;
/// <summary>
/// Tells server to use revocable session on LogIn and SignUp, even when App's Settings
/// has "Require Revocable Session" turned off. Issues network request in background to
/// migrate the sessionToken on disk to revocable session.
/// </summary>
/// <returns>The Task that upgrades the session.</returns>
public static Task EnableRevocableSessionAsync() {
return EnableRevocableSessionAsync(CancellationToken.None);
}
/// <summary>
/// Tells server to use revocable session on LogIn and SignUp, even when App's Settings
/// has "Require Revocable Session" turned off. Issues network request in background to
/// migrate the sessionToken on disk to revocable session.
/// </summary>
/// <returns>The Task that upgrades the session.</returns>
public static Task EnableRevocableSessionAsync(CancellationToken cancellationToken) {
lock (isRevocableSessionEnabledMutex) {
isRevocableSessionEnabled = true;
}
return GetCurrentUserAsync(cancellationToken).OnSuccess(t => {
var user = t.Result;
return user.UpgradeToRevocableSessionAsync(cancellationToken);
});
}
internal static void DisableRevocableSession() {
lock (isRevocableSessionEnabledMutex) {
isRevocableSessionEnabled = false;
}
}
internal static bool IsRevocableSessionEnabled {
get {
lock (isRevocableSessionEnabledMutex) {
return isRevocableSessionEnabled;
}
}
}
internal Task UpgradeToRevocableSessionAsync() {
return UpgradeToRevocableSessionAsync(CancellationToken.None);
}
internal Task UpgradeToRevocableSessionAsync(CancellationToken cancellationToken) {
return taskQueue.Enqueue(toAwait => UpgradeToRevocableSessionAsync(toAwait, cancellationToken),
cancellationToken);
}
internal Task UpgradeToRevocableSessionAsync(Task toAwait, CancellationToken cancellationToken) {
string sessionToken = SessionToken;
return toAwait.OnSuccess(_ => {
return ParseSession.UpgradeToRevocableSessionAsync(sessionToken, cancellationToken);
}).Unwrap().OnSuccess(t => {
return SetSessionTokenAsync(t.Result);
}).Unwrap();
}
#endregion
/// <summary>
/// Requests a password reset email to be sent to the specified email address associated with the
/// user account. This email allows the user to securely reset their password on the Parse site.
/// </summary>
/// <param name="email">The email address associated with the user that forgot their password.</param>
public static Task RequestPasswordResetAsync(string email) {
return RequestPasswordResetAsync(email, CancellationToken.None);
}
/// <summary>
/// Requests a password reset email to be sent to the specified email address associated with the
/// user account. This email allows the user to securely reset their password on the Parse site.
/// </summary>
/// <param name="email">The email address associated with the user that forgot their password.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public static Task RequestPasswordResetAsync(string email,
CancellationToken cancellationToken) {
return UserController.RequestPasswordResetAsync(email, cancellationToken);
}
/// <summary>
/// Gets the authData for this user.
/// </summary>
internal IDictionary<string, IDictionary<string, object>> AuthData {
get {
IDictionary<string, IDictionary<string, object>> authData;
if (this.TryGetValue<IDictionary<string, IDictionary<string, object>>>(
"authData", out authData)) {
return authData;
}
return null;
}
private set {
this["authData"] = value;
}
}
private static IParseAuthenticationProvider GetProvider(string providerName) {
IParseAuthenticationProvider provider;
if (authProviders.TryGetValue(providerName, out provider)) {
return provider;
}
return null;
}
/// <summary>
/// Removes null values from authData (which exist temporarily for unlinking)
/// </summary>
private void CleanupAuthData() {
lock (mutex) {
if (!CurrentUserController.IsCurrent(this)) {
return;
}
var authData = AuthData;
if (authData == null) {
return;
}
foreach (var pair in new Dictionary<string, IDictionary<string, object>>(authData)) {
if (pair.Value == null) {
authData.Remove(pair.Key);
}
}
}
}
/// <summary>
/// Synchronizes authData for all providers.
/// </summary>
private void SynchronizeAllAuthData() {
lock (mutex) {
var authData = AuthData;
if (authData == null) {
return;
}
foreach (var pair in authData) {
SynchronizeAuthData(GetProvider(pair.Key));
}
}
}
private void SynchronizeAuthData(IParseAuthenticationProvider provider) {
bool restorationSuccess = false;
lock (mutex) {
var authData = AuthData;
if (authData == null || provider == null) {
return;
}
IDictionary<string, object> data;
if (authData.TryGetValue(provider.AuthType, out data)) {
restorationSuccess = provider.RestoreAuthentication(data);
}
}
if (!restorationSuccess) {
this.UnlinkFromAsync(provider.AuthType, CancellationToken.None);
}
}
internal Task LinkWithAsync(string authType, IDictionary<string, object> data, CancellationToken cancellationToken) {
return taskQueue.Enqueue(toAwait => {
var authData = AuthData;
if (authData == null) {
authData = AuthData = new Dictionary<string, IDictionary<string, object>>();
}
authData[authType] = data;
AuthData = authData;
return SaveAsync(cancellationToken);
}, cancellationToken);
}
internal Task LinkWithAsync(string authType, CancellationToken cancellationToken) {
var provider = GetProvider(authType);
return provider.AuthenticateAsync(cancellationToken)
.OnSuccess(t => LinkWithAsync(authType, t.Result, cancellationToken))
.Unwrap();
}
/// <summary>
/// Unlinks a user from a service.
/// </summary>
internal Task UnlinkFromAsync(string authType, CancellationToken cancellationToken) {
return LinkWithAsync(authType, null, cancellationToken);
}
/// <summary>
/// Checks whether a user is linked to a service.
/// </summary>
internal bool IsLinked(string authType) {
lock (mutex) {
return AuthData != null && AuthData.ContainsKey(authType) && AuthData[authType] != null;
}
}
internal static Task<ParseUser> LogInWithAsync(string authType,
IDictionary<string, object> data,
CancellationToken cancellationToken) {
ParseUser user = null;
return UserController.LogInAsync(authType, data, cancellationToken).OnSuccess(t => {
user = ParseObject.FromState<ParseUser>(t.Result, "_User");
lock (user.mutex) {
if (user.AuthData == null) {
user.AuthData = new Dictionary<string, IDictionary<string, object>>();
}
user.AuthData[authType] = data;
user.SynchronizeAllAuthData();
}
return SaveCurrentUserAsync(user);
}).Unwrap().OnSuccess(t => user);
}
internal static Task<ParseUser> LogInWithAsync(string authType,
CancellationToken cancellationToken) {
var provider = GetProvider(authType);
return provider.AuthenticateAsync(cancellationToken)
.OnSuccess(authData => LogInWithAsync(authType, authData.Result, cancellationToken))
.Unwrap();
}
internal static void RegisterProvider(IParseAuthenticationProvider provider) {
authProviders[provider.AuthType] = provider;
var curUser = ParseUser.CurrentUser;
if (curUser != null) {
curUser.SynchronizeAuthData(provider);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Prism.Common;
using Xunit;
namespace Prism.Wpf.Tests
{
public class ListDictionaryFixture
{
static ListDictionary<string, object> list;
public ListDictionaryFixture()
{
list = new ListDictionary<string, object>();
}
[Fact]
public void AddThrowsIfKeyNull()
{
var ex = Assert.Throws<ArgumentNullException>(() =>
{
list.Add(null, new object());
});
}
[Fact]
public void AddThrowsIfValueNull()
{
var ex = Assert.Throws<ArgumentNullException>(() =>
{
list.Add("", null);
});
}
[Fact]
public void CanAddValue()
{
object value1 = new object();
object value2 = new object();
list.Add("foo", value1);
list.Add("foo", value2);
Assert.Equal(2, list["foo"].Count);
Assert.Same(value1, list["foo"][0]);
Assert.Same(value2, list["foo"][1]);
}
[Fact]
public void CanIndexValuesByKey()
{
list.Add("foo", new object());
list.Add("foo", new object());
Assert.Equal(2, list["foo"].Count);
}
[Fact]
public void ThrowsIfRemoveKeyNull()
{
var ex = Assert.Throws<ArgumentNullException>(() =>
{
list.RemoveValue(null, new object());
});
}
[Fact]
public void CanRemoveValue()
{
object value = new object();
list.Add("foo", value);
list.RemoveValue("foo", value);
Assert.Equal(0, list["foo"].Count);
}
[Fact]
public void CanRemoveValueFromAllLists()
{
object value = new object();
list.Add("foo", value);
list.Add("bar", value);
list.RemoveValue(value);
Assert.Equal(0, list.Values.Count);
}
[Fact]
public void RemoveNonExistingValueNoOp()
{
list.Add("foo", new object());
list.RemoveValue("foo", new object());
}
[Fact]
public void RemoveNonExistingKeyNoOp()
{
list.RemoveValue("foo", new object());
}
[Fact]
public void ThrowsIfRemoveListKeyNull()
{
var ex = Assert.Throws<ArgumentNullException>(() =>
{
list.Remove(null);
});
}
[Fact]
public void CanRemoveList()
{
list.Add("foo", new object());
list.Add("foo", new object());
bool removed = list.Remove("foo");
Assert.True(removed);
Assert.Equal(0, list.Keys.Count);
}
[Fact]
public void CanSetList()
{
List<object> values = new List<object>();
values.Add(new object());
list.Add("foo", new object());
list.Add("foo", new object());
list["foo"] = values;
Assert.Equal(1, list["foo"].Count);
}
[Fact]
public void CanEnumerateKeyValueList()
{
int count = 0;
list.Add("foo", new object());
list.Add("foo", new object());
foreach (KeyValuePair<string, IList<object>> pair in list)
{
foreach (object value in pair.Value)
{
count++;
}
Assert.Equal("foo", pair.Key);
}
Assert.Equal(2, count);
}
[Fact]
public void CanGetFlatListOfValues()
{
list.Add("foo", new object());
list.Add("foo", new object());
list.Add("bar", new object());
IList<object> values = list.Values;
Assert.Equal(3, values.Count);
}
[Fact]
public void IndexerAccessAlwaysSucceeds()
{
IList<object> values = list["foo"];
Assert.NotNull(values);
}
[Fact]
public void ThrowsIfContainsKeyNull()
{
var ex = Assert.Throws<ArgumentNullException>(() =>
{
list.ContainsKey(null);
});
}
[Fact]
public void CanAskContainsKey()
{
Assert.False(list.ContainsKey("foo"));
}
[Fact]
public void CanAskContainsValueInAnyList()
{
object obj = new object();
list.Add("foo", new object());
list.Add("bar", new object());
list.Add("baz", obj);
bool contains = list.ContainsValue(obj);
Assert.True(contains);
}
[Fact]
public void CanClearDictionary()
{
list.Add("foo", new object());
list.Add("bar", new object());
list.Add("baz", new object());
list.Clear();
Assert.Empty(list);
}
[Fact]
public void CanGetFilteredValuesByKeys()
{
list.Add("foo", new object());
list.Add("bar", new object());
list.Add("baz", new object());
IEnumerable<object> filtered = list.FindAllValuesByKey(delegate (string key)
{
return key.StartsWith("b");
});
int count = 0;
foreach (object obj in filtered)
{
count++;
}
Assert.Equal(2, count);
}
[Fact]
public void CanGetFilteredValues()
{
list.Add("foo", DateTime.Now);
list.Add("bar", new object());
list.Add("baz", DateTime.Today);
IEnumerable<object> filtered = list.FindAllValues(delegate (object value)
{
return value is DateTime;
});
int count = 0;
foreach (object obj in filtered)
{
count++;
}
Assert.Equal(2, count);
}
}
}
| |
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2006 Novell, Inc. (http://www.novell.com)
//
//
using System;
using System.Collections.Generic;
using System.Linq;
using static Avalonia.X11.XLib;
// ReSharper disable FieldCanBeMadeReadOnly.Global
// ReSharper disable IdentifierTypo
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable CommentTypo
// ReSharper disable ArrangeThisQualifier
// ReSharper disable NotAccessedField.Global
// ReSharper disable InconsistentNaming
// ReSharper disable StringLiteralTypo
#pragma warning disable 649
namespace Avalonia.X11
{
internal class X11Atoms
{
private readonly IntPtr _display;
// Our atoms
public readonly IntPtr AnyPropertyType = (IntPtr)0;
public readonly IntPtr XA_PRIMARY = (IntPtr)1;
public readonly IntPtr XA_SECONDARY = (IntPtr)2;
public readonly IntPtr XA_ARC = (IntPtr)3;
public readonly IntPtr XA_ATOM = (IntPtr)4;
public readonly IntPtr XA_BITMAP = (IntPtr)5;
public readonly IntPtr XA_CARDINAL = (IntPtr)6;
public readonly IntPtr XA_COLORMAP = (IntPtr)7;
public readonly IntPtr XA_CURSOR = (IntPtr)8;
public readonly IntPtr XA_CUT_BUFFER0 = (IntPtr)9;
public readonly IntPtr XA_CUT_BUFFER1 = (IntPtr)10;
public readonly IntPtr XA_CUT_BUFFER2 = (IntPtr)11;
public readonly IntPtr XA_CUT_BUFFER3 = (IntPtr)12;
public readonly IntPtr XA_CUT_BUFFER4 = (IntPtr)13;
public readonly IntPtr XA_CUT_BUFFER5 = (IntPtr)14;
public readonly IntPtr XA_CUT_BUFFER6 = (IntPtr)15;
public readonly IntPtr XA_CUT_BUFFER7 = (IntPtr)16;
public readonly IntPtr XA_DRAWABLE = (IntPtr)17;
public readonly IntPtr XA_FONT = (IntPtr)18;
public readonly IntPtr XA_INTEGER = (IntPtr)19;
public readonly IntPtr XA_PIXMAP = (IntPtr)20;
public readonly IntPtr XA_POINT = (IntPtr)21;
public readonly IntPtr XA_RECTANGLE = (IntPtr)22;
public readonly IntPtr XA_RESOURCE_MANAGER = (IntPtr)23;
public readonly IntPtr XA_RGB_COLOR_MAP = (IntPtr)24;
public readonly IntPtr XA_RGB_BEST_MAP = (IntPtr)25;
public readonly IntPtr XA_RGB_BLUE_MAP = (IntPtr)26;
public readonly IntPtr XA_RGB_DEFAULT_MAP = (IntPtr)27;
public readonly IntPtr XA_RGB_GRAY_MAP = (IntPtr)28;
public readonly IntPtr XA_RGB_GREEN_MAP = (IntPtr)29;
public readonly IntPtr XA_RGB_RED_MAP = (IntPtr)30;
public readonly IntPtr XA_STRING = (IntPtr)31;
public readonly IntPtr XA_VISUALID = (IntPtr)32;
public readonly IntPtr XA_WINDOW = (IntPtr)33;
public readonly IntPtr XA_WM_COMMAND = (IntPtr)34;
public readonly IntPtr XA_WM_HINTS = (IntPtr)35;
public readonly IntPtr XA_WM_CLIENT_MACHINE = (IntPtr)36;
public readonly IntPtr XA_WM_ICON_NAME = (IntPtr)37;
public readonly IntPtr XA_WM_ICON_SIZE = (IntPtr)38;
public readonly IntPtr XA_WM_NAME = (IntPtr)39;
public readonly IntPtr XA_WM_NORMAL_HINTS = (IntPtr)40;
public readonly IntPtr XA_WM_SIZE_HINTS = (IntPtr)41;
public readonly IntPtr XA_WM_ZOOM_HINTS = (IntPtr)42;
public readonly IntPtr XA_MIN_SPACE = (IntPtr)43;
public readonly IntPtr XA_NORM_SPACE = (IntPtr)44;
public readonly IntPtr XA_MAX_SPACE = (IntPtr)45;
public readonly IntPtr XA_END_SPACE = (IntPtr)46;
public readonly IntPtr XA_SUPERSCRIPT_X = (IntPtr)47;
public readonly IntPtr XA_SUPERSCRIPT_Y = (IntPtr)48;
public readonly IntPtr XA_SUBSCRIPT_X = (IntPtr)49;
public readonly IntPtr XA_SUBSCRIPT_Y = (IntPtr)50;
public readonly IntPtr XA_UNDERLINE_POSITION = (IntPtr)51;
public readonly IntPtr XA_UNDERLINE_THICKNESS = (IntPtr)52;
public readonly IntPtr XA_STRIKEOUT_ASCENT = (IntPtr)53;
public readonly IntPtr XA_STRIKEOUT_DESCENT = (IntPtr)54;
public readonly IntPtr XA_ITALIC_ANGLE = (IntPtr)55;
public readonly IntPtr XA_X_HEIGHT = (IntPtr)56;
public readonly IntPtr XA_QUAD_WIDTH = (IntPtr)57;
public readonly IntPtr XA_WEIGHT = (IntPtr)58;
public readonly IntPtr XA_POINT_SIZE = (IntPtr)59;
public readonly IntPtr XA_RESOLUTION = (IntPtr)60;
public readonly IntPtr XA_COPYRIGHT = (IntPtr)61;
public readonly IntPtr XA_NOTICE = (IntPtr)62;
public readonly IntPtr XA_FONT_NAME = (IntPtr)63;
public readonly IntPtr XA_FAMILY_NAME = (IntPtr)64;
public readonly IntPtr XA_FULL_NAME = (IntPtr)65;
public readonly IntPtr XA_CAP_HEIGHT = (IntPtr)66;
public readonly IntPtr XA_WM_CLASS = (IntPtr)67;
public readonly IntPtr XA_WM_TRANSIENT_FOR = (IntPtr)68;
public readonly IntPtr EDID;
public readonly IntPtr WM_PROTOCOLS;
public readonly IntPtr WM_DELETE_WINDOW;
public readonly IntPtr WM_TAKE_FOCUS;
public readonly IntPtr _NET_SUPPORTED;
public readonly IntPtr _NET_CLIENT_LIST;
public readonly IntPtr _NET_NUMBER_OF_DESKTOPS;
public readonly IntPtr _NET_DESKTOP_GEOMETRY;
public readonly IntPtr _NET_DESKTOP_VIEWPORT;
public readonly IntPtr _NET_CURRENT_DESKTOP;
public readonly IntPtr _NET_DESKTOP_NAMES;
public readonly IntPtr _NET_ACTIVE_WINDOW;
public readonly IntPtr _NET_WORKAREA;
public readonly IntPtr _NET_SUPPORTING_WM_CHECK;
public readonly IntPtr _NET_VIRTUAL_ROOTS;
public readonly IntPtr _NET_DESKTOP_LAYOUT;
public readonly IntPtr _NET_SHOWING_DESKTOP;
public readonly IntPtr _NET_CLOSE_WINDOW;
public readonly IntPtr _NET_MOVERESIZE_WINDOW;
public readonly IntPtr _NET_WM_MOVERESIZE;
public readonly IntPtr _NET_RESTACK_WINDOW;
public readonly IntPtr _NET_REQUEST_FRAME_EXTENTS;
public readonly IntPtr _NET_WM_NAME;
public readonly IntPtr _NET_WM_VISIBLE_NAME;
public readonly IntPtr _NET_WM_ICON_NAME;
public readonly IntPtr _NET_WM_VISIBLE_ICON_NAME;
public readonly IntPtr _NET_WM_DESKTOP;
public readonly IntPtr _NET_WM_WINDOW_TYPE;
public readonly IntPtr _NET_WM_STATE;
public readonly IntPtr _NET_WM_ALLOWED_ACTIONS;
public readonly IntPtr _NET_WM_STRUT;
public readonly IntPtr _NET_WM_STRUT_PARTIAL;
public readonly IntPtr _NET_WM_ICON_GEOMETRY;
public readonly IntPtr _NET_WM_ICON;
public readonly IntPtr _NET_WM_PID;
public readonly IntPtr _NET_WM_HANDLED_ICONS;
public readonly IntPtr _NET_WM_USER_TIME;
public readonly IntPtr _NET_FRAME_EXTENTS;
public readonly IntPtr _NET_WM_PING;
public readonly IntPtr _NET_WM_SYNC_REQUEST;
public readonly IntPtr _NET_SYSTEM_TRAY_S;
public readonly IntPtr _NET_SYSTEM_TRAY_ORIENTATION;
public readonly IntPtr _NET_SYSTEM_TRAY_OPCODE;
public readonly IntPtr _NET_WM_STATE_MAXIMIZED_HORZ;
public readonly IntPtr _NET_WM_STATE_MAXIMIZED_VERT;
public readonly IntPtr _NET_WM_STATE_FULLSCREEN;
public readonly IntPtr _XEMBED;
public readonly IntPtr _XEMBED_INFO;
public readonly IntPtr _MOTIF_WM_HINTS;
public readonly IntPtr _NET_WM_STATE_SKIP_TASKBAR;
public readonly IntPtr _NET_WM_STATE_ABOVE;
public readonly IntPtr _NET_WM_STATE_MODAL;
public readonly IntPtr _NET_WM_STATE_HIDDEN;
public readonly IntPtr _NET_WM_CONTEXT_HELP;
public readonly IntPtr _NET_WM_WINDOW_OPACITY;
public readonly IntPtr _NET_WM_WINDOW_TYPE_DESKTOP;
public readonly IntPtr _NET_WM_WINDOW_TYPE_DOCK;
public readonly IntPtr _NET_WM_WINDOW_TYPE_TOOLBAR;
public readonly IntPtr _NET_WM_WINDOW_TYPE_MENU;
public readonly IntPtr _NET_WM_WINDOW_TYPE_UTILITY;
public readonly IntPtr _NET_WM_WINDOW_TYPE_SPLASH;
public readonly IntPtr _NET_WM_WINDOW_TYPE_DIALOG;
public readonly IntPtr _NET_WM_WINDOW_TYPE_NORMAL;
public readonly IntPtr CLIPBOARD;
public readonly IntPtr CLIPBOARD_MANAGER;
public readonly IntPtr SAVE_TARGETS;
public readonly IntPtr MULTIPLE;
public readonly IntPtr PRIMARY;
public readonly IntPtr OEMTEXT;
public readonly IntPtr UNICODETEXT;
public readonly IntPtr TARGETS;
public readonly IntPtr UTF8_STRING;
public readonly IntPtr UTF16_STRING;
public readonly IntPtr ATOM_PAIR;
public readonly IntPtr MANAGER;
public readonly IntPtr _KDE_NET_WM_BLUR_BEHIND_REGION;
public readonly IntPtr INCR;
private readonly Dictionary<string, IntPtr> _namesToAtoms = new Dictionary<string, IntPtr>();
private readonly Dictionary<IntPtr, string> _atomsToNames = new Dictionary<IntPtr, string>();
public X11Atoms(IntPtr display)
{
_display = display;
// make sure this array stays in sync with the statements below
var fields = typeof(X11Atoms).GetFields()
.Where(f => f.FieldType == typeof(IntPtr) && (IntPtr)f.GetValue(this) == IntPtr.Zero).ToArray();
var atomNames = fields.Select(f => f.Name).ToArray();
IntPtr[] atoms = new IntPtr [atomNames.Length];
;
XInternAtoms(display, atomNames, atomNames.Length, true, atoms);
for (var c = 0; c < fields.Length; c++)
{
_namesToAtoms[fields[c].Name] = atoms[c];
_atomsToNames[atoms[c]] = fields[c].Name;
fields[c].SetValue(this, atoms[c]);
}
}
public IntPtr GetAtom(string name)
{
if (_namesToAtoms.TryGetValue(name, out var rv))
return rv;
var atom = XInternAtom(_display, name, false);
_namesToAtoms[name] = atom;
_atomsToNames[atom] = name;
return atom;
}
public string GetAtomName(IntPtr atom)
{
if (_atomsToNames.TryGetValue(atom, out var rv))
return rv;
var name = XLib.GetAtomName(_display, atom);
if (name == null)
return null;
_atomsToNames[atom] = name;
_namesToAtoms[name] = atom;
return name;
}
}
}
| |
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Tamir.SharpSsh.java.lang;
namespace Tamir.SharpSsh.jsch
{
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2002,2003,2004 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
internal class ChannelX11 : Channel
{
private const int LOCAL_WINDOW_SIZE_MAX = 0x20000;
private const int LOCAL_MAXIMUM_PACKET_SIZE = 0x4000;
internal static String host = "127.0.0.1";
internal static int port = 6000;
internal bool _init = true;
internal static byte[] cookie = null;
//static byte[] cookie_hex="0c281f065158632a427d3e074d79265d".getBytes();
internal static byte[] cookie_hex = null;
private static Hashtable faked_cookie_pool = new Hashtable();
private static Hashtable faked_cookie_hex_pool = new Hashtable();
internal static byte[] table = {
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
0x61, 0x62, 0x63, 0x64, 0x65, 0x66
};
internal static int revtable(byte foo)
{
for (int i = 0; i < table.Length; i++)
{
if (table[i] == foo) return i;
}
return 0;
}
internal static void setCookie(String foo)
{
cookie_hex = Util.getBytes(foo);
cookie = new byte[16];
for (int i = 0; i < 16; i++)
{
cookie[i] = (byte) (((revtable(cookie_hex[i*2]) << 4) & 0xf0) |
((revtable(cookie_hex[i*2 + 1])) & 0xf));
}
}
internal static void setHost(String foo)
{
host = foo;
}
internal static void setPort(int foo)
{
port = foo;
}
internal static byte[] getFakedCookie(Session session)
{
lock (faked_cookie_hex_pool)
{
byte[] foo = (byte[]) faked_cookie_hex_pool[session];
if (foo == null)
{
Random random = Session.random;
foo = new byte[16];
lock (random)
{
random.fill(foo, 0, 16);
}
/*
System.out.print("faked_cookie: ");
for(int i=0; i<foo.length; i++){
System.out.print(Integer.toHexString(foo[i]&0xff)+":");
}
System.out.println("");
*/
faked_cookie_pool.Add(session, foo);
byte[] bar = new byte[32];
for (int i = 0; i < 16; i++)
{
bar[2*i] = table[(foo[i] >> 4) & 0xf];
bar[2*i + 1] = table[(foo[i]) & 0xf];
}
faked_cookie_hex_pool.Add(session, bar);
foo = bar;
}
return foo;
}
}
private Socket socket = null;
internal ChannelX11() : base()
{
setLocalWindowSizeMax(LOCAL_WINDOW_SIZE_MAX);
setLocalWindowSize(LOCAL_WINDOW_SIZE_MAX);
setLocalPacketSize(LOCAL_MAXIMUM_PACKET_SIZE);
type = Util.getBytes("x11");
try
{
IPEndPoint ep = new IPEndPoint(Dns.GetHostEntry(host).AddressList[0], port);
socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);
socket.Connect(ep);
io = new IO();
NetworkStream ns = new NetworkStream(socket);
io.setInputStream(ns);
io.setOutputStream(ns);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public override void run()
{
thread = new JavaThread(Thread.CurrentThread);
Buffer buf = new Buffer(rmpsize);
Packet packet = new Packet(buf);
int i = 0;
try
{
while (thread != null)
{
i = io.ins.Read(buf.buffer,
14,
buf.buffer.Length - 14
- 16 - 20 // padding and mac
);
if (i <= 0)
{
eof();
break;
}
if (_close) break;
packet.reset();
buf.putByte((byte) Session.SSH_MSG_CHANNEL_DATA);
buf.putInt(recipient);
buf.putInt(i);
buf.skip(i);
session.write(packet, this, i);
}
}
catch
{
//System.out.println(e);
}
thread = null;
}
internal override void write(byte[] foo, int s, int l)
{
//if(eof_local)return;
if (_init)
{
int plen = (foo[s + 6] & 0xff)*256 + (foo[s + 7] & 0xff);
int dlen = (foo[s + 8] & 0xff)*256 + (foo[s + 9] & 0xff);
if ((foo[s] & 0xff) == 0x42)
{
}
else if ((foo[s] & 0xff) == 0x6c)
{
plen = (int) (((uint) plen >> 8) & 0xff) | ((plen << 8) & 0xff00);
dlen = (int) (((uint) dlen >> 8) & 0xff) | ((dlen << 8) & 0xff00);
}
else
{
// ??
}
byte[] bar = new byte[dlen];
Array.Copy(foo, s + 12 + plen + ((-plen) & 3), bar, 0, dlen);
byte[] faked_cookie = (byte[]) faked_cookie_pool[session];
if (equals(bar, faked_cookie))
{
if (cookie != null)
Array.Copy(cookie, 0, foo, s + 12 + plen + ((-plen) & 3), dlen);
}
else
{
Console.WriteLine("wrong cookie");
}
_init = false;
}
io.put(foo, s, l);
}
public override void disconnect()
{
close();
thread = null;
try
{
if (io != null)
{
try
{
if (io.ins != null)
io.ins.Close();
}
catch
{
}
try
{
if (io.outs != null)
io.outs.Close();
}
catch
{
}
}
try
{
if (socket != null)
socket.Close();
}
catch
{
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
io = null;
del(this);
}
private static bool equals(byte[] foo, byte[] bar)
{
if (foo.Length != bar.Length) return false;
for (int i = 0; i < foo.Length; i++)
{
if (foo[i] != bar[i]) return false;
}
return true;
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA / LumiSoft *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using LumiSoft.Media.Wave.Native;
namespace LumiSoft.Media.Wave
{
/// <summary>
/// This class implements streaming wav data player.
/// </summary>
public class WaveOut : IDisposable
{
#region class PlayItem
/// <summary>
/// This class holds queued wav play item.
/// </summary>
internal class PlayItem
{
private GCHandle m_HeaderHandle;
private GCHandle m_DataHandle;
private int m_DataSize = 0;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="headerHandle">Header handle.</param>
/// <param name="header">Wav header.</param>
/// <param name="dataHandle">Wav header data handle.</param>
/// <param name="dataSize">Data size in bytes.</param>
public PlayItem(ref GCHandle headerHandle,ref GCHandle dataHandle,int dataSize)
{
m_HeaderHandle = headerHandle;
m_DataHandle = dataHandle;
m_DataSize = dataSize;
}
#region method Dispose
/// <summary>
/// Cleans up any resources being used.
/// </summary>
public void Dispose()
{
m_HeaderHandle.Free();
m_DataHandle.Free();
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets header handle.
/// </summary>
public GCHandle HeaderHandle
{
get{ return m_HeaderHandle; }
}
/// <summary>
/// Gets header.
/// </summary>
public WAVEHDR Header
{
get{ return (WAVEHDR)m_HeaderHandle.Target; }
}
/// <summary>
/// Gets wav header data pointer handle.
/// </summary>
public GCHandle DataHandle
{
get{ return m_DataHandle; }
}
/// <summary>
/// Gets wav header data size in bytes.
/// </summary>
public int DataSize
{
get{ return m_DataSize; }
}
#endregion
}
#endregion
private WavOutDevice m_pOutDevice = null;
private int m_SamplesPerSec = 8000;
private int m_BitsPerSample = 16;
private int m_Channels = 1;
private int m_MinBuffer = 1200;
private IntPtr m_pWavDevHandle = IntPtr.Zero;
private int m_BlockSize = 0;
private int m_BytesBuffered = 0;
private bool m_IsPaused = false;
private List<PlayItem> m_pPlayItems = null;
private waveOutProc m_pWaveOutProc = null;
private bool m_IsDisposed = false;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="outputDevice">Output device.</param>
/// <param name="samplesPerSec">Sample rate, in samples per second (hertz). For PCM common values are
/// 8.0 kHz, 11.025 kHz, 22.05 kHz, and 44.1 kHz.</param>
/// <param name="bitsPerSample">Bits per sample. For PCM 8 or 16 are the only valid values.</param>
/// <param name="channels">Number of channels.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>outputDevice</b> is null.</exception>
/// <exception cref="ArgumentException">Is raised when any of the aruments has invalid value.</exception>
public WaveOut(WavOutDevice outputDevice,int samplesPerSec,int bitsPerSample,int channels)
{
if(outputDevice == null){
throw new ArgumentNullException("outputDevice");
}
if(samplesPerSec < 8000){
throw new ArgumentException("Argument 'samplesPerSec' value must be >= 8000.");
}
if(bitsPerSample < 8){
throw new ArgumentException("Argument 'bitsPerSample' value must be >= 8.");
}
if(channels < 1){
throw new ArgumentException("Argument 'channels' value must be >= 1.");
}
m_pOutDevice = outputDevice;
m_SamplesPerSec = samplesPerSec;
m_BitsPerSample = bitsPerSample;
m_Channels = channels;
m_BlockSize = m_Channels * (m_BitsPerSample / 8);
m_pPlayItems = new List<PlayItem>();
// Try to open wav device.
WAVEFORMATEX format = new WAVEFORMATEX();
format.wFormatTag = WavFormat.PCM;
format.nChannels = (ushort)m_Channels;
format.nSamplesPerSec = (uint)samplesPerSec;
format.nAvgBytesPerSec = (uint)(m_SamplesPerSec * m_Channels * (m_BitsPerSample / 8));
format.nBlockAlign = (ushort)m_BlockSize;
format.wBitsPerSample = (ushort)m_BitsPerSample;
format.cbSize = 0;
// We must delegate reference, otherwise GC will collect it.
m_pWaveOutProc = new waveOutProc(this.OnWaveOutProc);
int result = WavMethods.waveOutOpen(out m_pWavDevHandle,m_pOutDevice.Index,format,m_pWaveOutProc,0,WavConstants.CALLBACK_FUNCTION);
if(result != MMSYSERR.NOERROR){
throw new Exception("Failed to open wav device, error: " + result.ToString() + ".");
}
}
/// <summary>
/// Default destructor.
/// </summary>
~WaveOut()
{
Dispose();
}
#region method Dispose
/// <summary>
/// Cleans up any resources being used.
/// </summary>
public void Dispose()
{
if(m_IsDisposed){
return;
}
m_IsDisposed = true;
try{
// If playing, we need to reset wav device first.
WavMethods.waveOutReset(m_pWavDevHandle);
// If there are unprepared wav headers, we need to unprepare these.
foreach(PlayItem item in m_pPlayItems){
WavMethods.waveOutUnprepareHeader(m_pWavDevHandle,item.HeaderHandle.AddrOfPinnedObject(),Marshal.SizeOf(item.Header));
item.Dispose();
}
// Close output device.
WavMethods.waveOutClose(m_pWavDevHandle);
m_pOutDevice = null;
m_pWavDevHandle = IntPtr.Zero;
m_pPlayItems = null;
m_pWaveOutProc = null;
}
catch{
}
}
#endregion
#region method OnWaveOutProc
/// <summary>
/// This method is called when wav device generates some event.
/// </summary>
/// <param name="hdrvr">Handle to the waveform-audio device associated with the callback.</param>
/// <param name="uMsg">Waveform-audio output message.</param>
/// <param name="dwUser">User-instance data specified with waveOutOpen.</param>
/// <param name="dwParam1">Message parameter.</param>
/// <param name="dwParam2">Message parameter.</param>
private void OnWaveOutProc(IntPtr hdrvr,int uMsg,int dwUser,int dwParam1,int dwParam2)
{
// NOTE: MSDN warns, we may not call any wav related methods here.
try{
if(uMsg == WavConstants.MM_WOM_DONE){
ThreadPool.QueueUserWorkItem(new WaitCallback(this.OnCleanUpFirstBlock));
}
}
catch{
}
}
#endregion
#region method OnCleanUpFirstBlock
/// <summary>
/// Cleans up the first data block in play queue.
/// </summary>
/// <param name="state">User data.</param>
private void OnCleanUpFirstBlock(object state)
{
try{
lock(m_pPlayItems){
PlayItem item = m_pPlayItems[0];
WavMethods.waveOutUnprepareHeader(m_pWavDevHandle,item.HeaderHandle.AddrOfPinnedObject(),Marshal.SizeOf(item.Header));
m_pPlayItems.Remove(item);
m_BytesBuffered -= item.DataSize;
item.Dispose();
}
}
catch{
}
}
#endregion
#region method Play
/// <summary>
/// Plays specified audio data bytes. If player is currently playing, data will be queued for playing.
/// </summary>
/// <param name="audioData">Audio data. Data boundary must n * BlockSize.</param>
/// <param name="offset">Offset in the buffer.</param>
/// <param name="count">Number of bytes to play form the specified offset.</param>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
/// <exception cref="ArgumentNullException">Is raised when <b>audioData</b> is null.</exception>
/// <exception cref="ArgumentException">Is raised when <b>audioData</b> is with invalid length.</exception>
public void Play(byte[] audioData,int offset,int count)
{
if(m_IsDisposed){
throw new ObjectDisposedException("WaveOut");
}
if(audioData == null){
throw new ArgumentNullException("audioData");
}
if((count % m_BlockSize) != 0){
throw new ArgumentException("Audio data is not n * BlockSize.");
}
//--- Queue specified audio block for play. --------------------------------------------------------
byte[] data = new byte[count];
Array.Copy(audioData,offset,data,0,count);
GCHandle dataHandle = GCHandle.Alloc(data,GCHandleType.Pinned);
// m_BytesBuffered += data.Length;
WAVEHDR wavHeader = new WAVEHDR();
wavHeader.lpData = dataHandle.AddrOfPinnedObject();
wavHeader.dwBufferLength = (uint)data.Length;
wavHeader.dwBytesRecorded = 0;
wavHeader.dwUser = IntPtr.Zero;
wavHeader.dwFlags = 0;
wavHeader.dwLoops = 0;
wavHeader.lpNext = IntPtr.Zero;
wavHeader.reserved = 0;
GCHandle headerHandle = GCHandle.Alloc(wavHeader,GCHandleType.Pinned);
int result = 0;
result = WavMethods.waveOutPrepareHeader(m_pWavDevHandle,headerHandle.AddrOfPinnedObject(),Marshal.SizeOf(wavHeader));
if(result == MMSYSERR.NOERROR){
PlayItem item = new PlayItem(ref headerHandle,ref dataHandle,data.Length);
m_pPlayItems.Add(item);
// We ran out of minimum buffer, we must pause playing while min buffer filled.
if(m_BytesBuffered < 1000){
if(!m_IsPaused){
WavMethods.waveOutPause(m_pWavDevHandle);
m_IsPaused = true;
}
//File.AppendAllText("aaaa.txt","Begin buffer\r\n");
}
// Buffering completed,we may resume playing.
else if(m_IsPaused && m_BytesBuffered > m_MinBuffer){
WavMethods.waveOutRestart(m_pWavDevHandle);
m_IsPaused = false;
//File.AppendAllText("aaaa.txt","end buffer: " + m_BytesBuffered + "\r\n");
}
/*
// TODO: If we ran out of minimum buffer, we must pause playing while min buffer filled.
if(m_BytesBuffered < m_MinBuffer){
if(!m_IsPaused){
WavMethods.waveOutPause(m_pWavDevHandle);
m_IsPaused = true;
}
}
else if(m_IsPaused){
WavMethods.waveOutRestart(m_pWavDevHandle);
}*/
m_BytesBuffered += data.Length;
result = WavMethods.waveOutWrite(m_pWavDevHandle,headerHandle.AddrOfPinnedObject(),Marshal.SizeOf(wavHeader));
}
else{
dataHandle.Free();
headerHandle.Free();
}
//--------------------------------------------------------------------------------------------------
}
#endregion
#region method GetVolume
/// <summary>
/// Gets audio output volume.
/// </summary>
/// <param name="left">Left channel volume level.</param>
/// <param name="right">Right channel volume level.</param>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
public void GetVolume(ref ushort left,ref ushort right)
{
if(m_IsDisposed){
throw new ObjectDisposedException("WaveOut");
}
int volume = 0;
WavMethods.waveOutGetVolume(m_pWavDevHandle,out volume);
left = (ushort)(volume & 0x0000ffff);
right = (ushort)(volume >> 16);
}
#endregion
#region method SetVolume
/// <summary>
/// Sets audio output volume.
/// </summary>
/// <param name="left">Left channel volume level.</param>
/// <param name="right">Right channel volume level.</param>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
public void SetVolume(ushort left,ushort right)
{
if(m_IsDisposed){
throw new ObjectDisposedException("WaveOut");
}
WavMethods.waveOutSetVolume(m_pWavDevHandle,(right << 16 | left & 0xFFFF));
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets all available output audio devices.
/// </summary>
public static WavOutDevice[] Devices
{
get{
List<WavOutDevice> retVal = new List<WavOutDevice>();
// Get all available output devices and their info.
int devicesCount = WavMethods.waveOutGetNumDevs();
for(int i=0;i<devicesCount;i++){
WAVEOUTCAPS pwoc = new WAVEOUTCAPS();
if(WavMethods.waveOutGetDevCaps((uint)i,ref pwoc,Marshal.SizeOf(pwoc)) == MMSYSERR.NOERROR){
retVal.Add(new WavOutDevice(i,pwoc.szPname,pwoc.wChannels));
}
}
return retVal.ToArray();
}
}
/// <summary>
/// Gets if this object is disposed.
/// </summary>
public bool IsDisposed
{
get{ return m_IsDisposed; }
}
/// <summary>
/// Gets current output device.
/// </summary>
/// <exception cref="">Is raised when this object is disposed and this property is accessed.</exception>
public WavOutDevice OutputDevice
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("WaveOut");
}
return m_pOutDevice;
}
}
/// <summary>
/// Gets number of samples per second.
/// </summary>
/// <exception cref="">Is raised when this object is disposed and this property is accessed.</exception>
public int SamplesPerSec
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("WaveOut");
}
return m_SamplesPerSec;
}
}
/// <summary>
/// Gets number of buts per sample.
/// </summary>
/// <exception cref="">Is raised when this object is disposed and this property is accessed.</exception>
public int BitsPerSample
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("WaveOut");
}
return m_BitsPerSample;
}
}
/// <summary>
/// Gets number of channels.
/// </summary>
/// <exception cref="">Is raised when this object is disposed and this property is accessed.</exception>
public int Channels
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("WaveOut");
}
return m_Channels;
}
}
/// <summary>
/// Gets one smaple block size in bytes.
/// </summary>
/// <exception cref="">Is raised when this object is disposed and this property is accessed.</exception>
public int BlockSize
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("WaveOut");
}
return m_BlockSize;
}
}
/// <summary>
/// Gets if wav player is currently playing something.
/// </summary>
/// <exception cref="">Is raised when this object is disposed and this property is accessed.</exception>
public bool IsPlaying
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("WaveOut");
}
if(m_pPlayItems.Count > 0){
return true;
}
else{
return false;
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
public enum TopicName
{
NOTHING,
Cooking,
Fish,
Volleyball,
Clothes,
Bugs,
Drinking,
Internet,
Shopping,
Teacup,
Motorcycles,
Lollipop,
Hats,
Gaming,
Eating,
Basketball,
Cars,
Leaf,
Book,
Biking,
Cats,
Hiking,
Computers,
Movies,
Tennis,
Coffee,
TV,
Microscope,
Shoes,
Milk,
Teapot,
Weather,
Painting,
Undershirts,
Dresses,
Raddish,
Photography,
Heels,
Music,
AtomicPower,
Planes,
Sunsets,
Lighthouse,
Ironing,
Waves,
Smoking,
Books,
Recycling,
Humans,
MAX //Not an actual topic, just used for iteration count
}
public class TopicSet {
private List<Topic> allTopics;
private Random rnd = new Random();
public TopicSet() {
allTopics = new List<Topic> ();
Topic videoGames = new Topic (TopicName.Gaming);
Topic cars = new Topic (TopicName.Cars);
Topic motorcycles = new Topic (TopicName.Motorcycles);
Topic clothes = new Topic (TopicName.Clothes);
Topic marklar = new Topic (TopicName.AtomicPower);
Topic microscope = new Topic (TopicName.Microscope);
Topic milk = new Topic (TopicName.Milk);
videoGames.AddTopic (cars);
videoGames.AddTopic (motorcycles);
videoGames.AddTopic (clothes);
videoGames.AddTopic (marklar);
videoGames.AddTopic (microscope);
videoGames.AddTopic (milk);
cars.AddTopic (videoGames);
cars.AddTopic (motorcycles);
cars.AddTopic (clothes);
cars.AddTopic (marklar);
cars.AddTopic (microscope);
cars.AddTopic (milk);
motorcycles.AddTopic (videoGames);
motorcycles.AddTopic (cars);
motorcycles.AddTopic (clothes);
motorcycles.AddTopic (marklar);
motorcycles.AddTopic (microscope);
motorcycles.AddTopic (milk);
clothes.AddTopic (videoGames);
clothes.AddTopic (cars);
clothes.AddTopic (motorcycles);
clothes.AddTopic (marklar);
clothes.AddTopic (microscope);
clothes.AddTopic (milk);
marklar.AddTopic (videoGames);
marklar.AddTopic (cars);
marklar.AddTopic (motorcycles);
marklar.AddTopic (clothes);
marklar.AddTopic (microscope);
marklar.AddTopic (milk);
microscope.AddTopic (videoGames);
microscope.AddTopic (cars);
microscope.AddTopic (motorcycles);
microscope.AddTopic (clothes);
microscope.AddTopic (marklar);
microscope.AddTopic (milk);
milk.AddTopic (videoGames);
milk.AddTopic (cars);
milk.AddTopic (motorcycles);
milk.AddTopic (clothes);
milk.AddTopic (marklar);
milk.AddTopic (microscope);
allTopics.Add (videoGames);
allTopics.Add (cars);
allTopics.Add (motorcycles);
allTopics.Add (clothes);
allTopics.Add (marklar);
allTopics.Add (microscope);
allTopics.Add (milk);
}
public Topic GetStartingTopic() {
return allTopics [rnd.Next (allTopics.Count)];
}
public List<Topic> GetNRandomTopics(int n)
{
List<Topic> nextTopics = new List<Topic>();
int topicsNeeded = n;
int topicsSeen = 0;
foreach (Topic topic in allTopics)
{
if (rnd.Next(allTopics.Count -topicsSeen) <= (topicsNeeded-1))
{
nextTopics.Add(topic);
topicsNeeded--;
}
topicsSeen++;
}
return nextTopics;
}
}
public class Topic
{
private List<Topic> relatedTopics;
private TopicName topicName;
private Random rnd = new Random();
public List<Topic> GetPossibleTopics() {
Console.WriteLine ("Getting Possible Topics");
return GetNRandomTopics (4);
}
private List<Topic> GetNRandomTopics (int n)
{
List<Topic> nextTopics = new List<Topic>();
int topicsNeeded = n;
int topicsSeen = 0;
foreach (Topic topic in relatedTopics)
{
if (rnd.Next(relatedTopics.Count -topicsSeen) <= (topicsNeeded-1))
{
nextTopics.Add(topic);
topicsNeeded--;
}
topicsSeen++;
}
return nextTopics;
}
public Topic(TopicName name) {
topicName = name;
relatedTopics = new List<Topic> ();
}
public void AddTopic(Topic topic) {
relatedTopics.Add (topic);
}
public String GetTopicName() {
return topicName.ToString ();;
}
}
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("Hello World!");
TopicSet topics = new TopicSet ();
Topic topic = topics.GetStartingTopic ();
Console.WriteLine (topic.GetTopicName());
Console.WriteLine ("Related Topics");
List<Topic> nextTopics = topic.GetPossibleTopics ();
foreach (Topic currTopic in nextTopics) // Loop through List with foreach.
{
Console.WriteLine(currTopic.GetTopicName());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.IO
{
public static class __File
{
public static IObservable<System.IO.StreamReader> OpenText(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.OpenText(pathLambda));
}
public static IObservable<System.IO.StreamWriter> CreateText(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.CreateText(pathLambda));
}
public static IObservable<System.IO.StreamWriter> AppendText(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.AppendText(pathLambda));
}
public static IObservable<System.Reactive.Unit> Copy(IObservable<System.String> sourceFileName,
IObservable<System.String> destFileName)
{
return ObservableExt.ZipExecute(sourceFileName, destFileName,
(sourceFileNameLambda, destFileNameLambda) =>
System.IO.File.Copy(sourceFileNameLambda, destFileNameLambda));
}
public static IObservable<System.Reactive.Unit> Copy(IObservable<System.String> sourceFileName,
IObservable<System.String> destFileName, IObservable<System.Boolean> overwrite)
{
return ObservableExt.ZipExecute(sourceFileName, destFileName, overwrite,
(sourceFileNameLambda, destFileNameLambda, overwriteLambda) =>
System.IO.File.Copy(sourceFileNameLambda, destFileNameLambda, overwriteLambda));
}
public static IObservable<System.IO.FileStream> Create(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.Create(pathLambda));
}
public static IObservable<System.IO.FileStream> Create(IObservable<System.String> path,
IObservable<System.Int32> bufferSize)
{
return Observable.Zip(path, bufferSize,
(pathLambda, bufferSizeLambda) => System.IO.File.Create(pathLambda, bufferSizeLambda));
}
public static IObservable<System.IO.FileStream> Create(IObservable<System.String> path,
IObservable<System.Int32> bufferSize, IObservable<System.IO.FileOptions> options)
{
return Observable.Zip(path, bufferSize, options,
(pathLambda, bufferSizeLambda, optionsLambda) =>
System.IO.File.Create(pathLambda, bufferSizeLambda, optionsLambda));
}
public static IObservable<System.IO.FileStream> Create(IObservable<System.String> path,
IObservable<System.Int32> bufferSize, IObservable<System.IO.FileOptions> options,
IObservable<System.Security.AccessControl.FileSecurity> fileSecurity)
{
return Observable.Zip(path, bufferSize, options, fileSecurity,
(pathLambda, bufferSizeLambda, optionsLambda, fileSecurityLambda) =>
System.IO.File.Create(pathLambda, bufferSizeLambda, optionsLambda, fileSecurityLambda));
}
public static IObservable<System.Reactive.Unit> Delete(IObservable<System.String> path)
{
return Observable.Do(path, (pathLambda) => System.IO.File.Delete(pathLambda)).ToUnit();
}
public static IObservable<System.Reactive.Unit> Decrypt(IObservable<System.String> path)
{
return Observable.Do(path, (pathLambda) => System.IO.File.Decrypt(pathLambda)).ToUnit();
}
public static IObservable<System.Reactive.Unit> Encrypt(IObservable<System.String> path)
{
return Observable.Do(path, (pathLambda) => System.IO.File.Encrypt(pathLambda)).ToUnit();
}
public static IObservable<System.Boolean> Exists(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.Exists(pathLambda));
}
public static IObservable<System.IO.FileStream> Open(IObservable<System.String> path,
IObservable<System.IO.FileMode> mode)
{
return Observable.Zip(path, mode, (pathLambda, modeLambda) => System.IO.File.Open(pathLambda, modeLambda));
}
public static IObservable<System.IO.FileStream> Open(IObservable<System.String> path,
IObservable<System.IO.FileMode> mode, IObservable<System.IO.FileAccess> access)
{
return Observable.Zip(path, mode, access,
(pathLambda, modeLambda, accessLambda) => System.IO.File.Open(pathLambda, modeLambda, accessLambda));
}
public static IObservable<System.IO.FileStream> Open(IObservable<System.String> path,
IObservable<System.IO.FileMode> mode, IObservable<System.IO.FileAccess> access,
IObservable<System.IO.FileShare> share)
{
return Observable.Zip(path, mode, access, share,
(pathLambda, modeLambda, accessLambda, shareLambda) =>
System.IO.File.Open(pathLambda, modeLambda, accessLambda, shareLambda));
}
public static IObservable<System.Reactive.Unit> SetCreationTime(IObservable<System.String> path,
IObservable<System.DateTime> creationTime)
{
return ObservableExt.ZipExecute(path, creationTime,
(pathLambda, creationTimeLambda) => System.IO.File.SetCreationTime(pathLambda, creationTimeLambda));
}
public static IObservable<System.Reactive.Unit> SetCreationTimeUtc(IObservable<System.String> path,
IObservable<System.DateTime> creationTimeUtc)
{
return ObservableExt.ZipExecute(path, creationTimeUtc,
(pathLambda, creationTimeUtcLambda) =>
System.IO.File.SetCreationTimeUtc(pathLambda, creationTimeUtcLambda));
}
public static IObservable<System.DateTime> GetCreationTime(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.GetCreationTime(pathLambda));
}
public static IObservable<System.DateTime> GetCreationTimeUtc(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.GetCreationTimeUtc(pathLambda));
}
public static IObservable<System.Reactive.Unit> SetLastAccessTime(IObservable<System.String> path,
IObservable<System.DateTime> lastAccessTime)
{
return ObservableExt.ZipExecute(path, lastAccessTime,
(pathLambda, lastAccessTimeLambda) => System.IO.File.SetLastAccessTime(pathLambda, lastAccessTimeLambda));
}
public static IObservable<System.Reactive.Unit> SetLastAccessTimeUtc(IObservable<System.String> path,
IObservable<System.DateTime> lastAccessTimeUtc)
{
return ObservableExt.ZipExecute(path, lastAccessTimeUtc,
(pathLambda, lastAccessTimeUtcLambda) =>
System.IO.File.SetLastAccessTimeUtc(pathLambda, lastAccessTimeUtcLambda));
}
public static IObservable<System.DateTime> GetLastAccessTime(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.GetLastAccessTime(pathLambda));
}
public static IObservable<System.DateTime> GetLastAccessTimeUtc(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.GetLastAccessTimeUtc(pathLambda));
}
public static IObservable<System.Reactive.Unit> SetLastWriteTime(IObservable<System.String> path,
IObservable<System.DateTime> lastWriteTime)
{
return ObservableExt.ZipExecute(path, lastWriteTime,
(pathLambda, lastWriteTimeLambda) => System.IO.File.SetLastWriteTime(pathLambda, lastWriteTimeLambda));
}
public static IObservable<System.Reactive.Unit> SetLastWriteTimeUtc(IObservable<System.String> path,
IObservable<System.DateTime> lastWriteTimeUtc)
{
return ObservableExt.ZipExecute(path, lastWriteTimeUtc,
(pathLambda, lastWriteTimeUtcLambda) =>
System.IO.File.SetLastWriteTimeUtc(pathLambda, lastWriteTimeUtcLambda));
}
public static IObservable<System.DateTime> GetLastWriteTime(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.GetLastWriteTime(pathLambda));
}
public static IObservable<System.DateTime> GetLastWriteTimeUtc(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.GetLastWriteTimeUtc(pathLambda));
}
public static IObservable<System.IO.FileAttributes> GetAttributes(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.GetAttributes(pathLambda));
}
public static IObservable<System.Reactive.Unit> SetAttributes(IObservable<System.String> path,
IObservable<System.IO.FileAttributes> fileAttributes)
{
return ObservableExt.ZipExecute(path, fileAttributes,
(pathLambda, fileAttributesLambda) => System.IO.File.SetAttributes(pathLambda, fileAttributesLambda));
}
public static IObservable<System.Security.AccessControl.FileSecurity> GetAccessControl(
IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.GetAccessControl(pathLambda));
}
public static IObservable<System.Security.AccessControl.FileSecurity> GetAccessControl(
IObservable<System.String> path,
IObservable<System.Security.AccessControl.AccessControlSections> includeSections)
{
return Observable.Zip(path, includeSections,
(pathLambda, includeSectionsLambda) =>
System.IO.File.GetAccessControl(pathLambda, includeSectionsLambda));
}
public static IObservable<System.Reactive.Unit> SetAccessControl(IObservable<System.String> path,
IObservable<System.Security.AccessControl.FileSecurity> fileSecurity)
{
return ObservableExt.ZipExecute(path, fileSecurity,
(pathLambda, fileSecurityLambda) => System.IO.File.SetAccessControl(pathLambda, fileSecurityLambda));
}
public static IObservable<System.IO.FileStream> OpenRead(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.OpenRead(pathLambda));
}
public static IObservable<System.IO.FileStream> OpenWrite(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.OpenWrite(pathLambda));
}
public static IObservable<System.String> ReadAllText(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.ReadAllText(pathLambda));
}
public static IObservable<System.String> ReadAllText(IObservable<System.String> path,
IObservable<System.Text.Encoding> encoding)
{
return Observable.Zip(path, encoding,
(pathLambda, encodingLambda) => System.IO.File.ReadAllText(pathLambda, encodingLambda));
}
public static IObservable<System.Reactive.Unit> WriteAllText(IObservable<System.String> path,
IObservable<System.String> contents)
{
return ObservableExt.ZipExecute(path, contents,
(pathLambda, contentsLambda) => System.IO.File.WriteAllText(pathLambda, contentsLambda));
}
public static IObservable<System.Reactive.Unit> WriteAllText(IObservable<System.String> path,
IObservable<System.String> contents, IObservable<System.Text.Encoding> encoding)
{
return ObservableExt.ZipExecute(path, contents, encoding,
(pathLambda, contentsLambda, encodingLambda) =>
System.IO.File.WriteAllText(pathLambda, contentsLambda, encodingLambda));
}
public static IObservable<System.Byte[]> ReadAllBytes(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.ReadAllBytes(pathLambda));
}
public static IObservable<System.Reactive.Unit> WriteAllBytes(IObservable<System.String> path,
IObservable<System.Byte[]> bytes)
{
return ObservableExt.ZipExecute(path, bytes,
(pathLambda, bytesLambda) => System.IO.File.WriteAllBytes(pathLambda, bytesLambda));
}
public static IObservable<System.String[]> ReadAllLines(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.ReadAllLines(pathLambda));
}
public static IObservable<System.String[]> ReadAllLines(IObservable<System.String> path,
IObservable<System.Text.Encoding> encoding)
{
return Observable.Zip(path, encoding,
(pathLambda, encodingLambda) => System.IO.File.ReadAllLines(pathLambda, encodingLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.String>> ReadLines(
IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.File.ReadLines(pathLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.String>> ReadLines(
IObservable<System.String> path, IObservable<System.Text.Encoding> encoding)
{
return Observable.Zip(path, encoding,
(pathLambda, encodingLambda) => System.IO.File.ReadLines(pathLambda, encodingLambda));
}
public static IObservable<System.Reactive.Unit> WriteAllLines(IObservable<System.String> path,
IObservable<System.String[]> contents)
{
return ObservableExt.ZipExecute(path, contents,
(pathLambda, contentsLambda) => System.IO.File.WriteAllLines(pathLambda, contentsLambda));
}
public static IObservable<System.Reactive.Unit> WriteAllLines(IObservable<System.String> path,
IObservable<System.String[]> contents, IObservable<System.Text.Encoding> encoding)
{
return ObservableExt.ZipExecute(path, contents, encoding,
(pathLambda, contentsLambda, encodingLambda) =>
System.IO.File.WriteAllLines(pathLambda, contentsLambda, encodingLambda));
}
public static IObservable<System.Reactive.Unit> WriteAllLines(IObservable<System.String> path,
IObservable<System.Collections.Generic.IEnumerable<System.String>> contents)
{
return ObservableExt.ZipExecute(path, contents,
(pathLambda, contentsLambda) => System.IO.File.WriteAllLines(pathLambda, contentsLambda));
}
public static IObservable<System.Reactive.Unit> WriteAllLines(IObservable<System.String> path,
IObservable<System.Collections.Generic.IEnumerable<System.String>> contents,
IObservable<System.Text.Encoding> encoding)
{
return ObservableExt.ZipExecute(path, contents, encoding,
(pathLambda, contentsLambda, encodingLambda) =>
System.IO.File.WriteAllLines(pathLambda, contentsLambda, encodingLambda));
}
public static IObservable<System.Reactive.Unit> AppendAllText(IObservable<System.String> path,
IObservable<System.String> contents)
{
return ObservableExt.ZipExecute(path, contents,
(pathLambda, contentsLambda) => System.IO.File.AppendAllText(pathLambda, contentsLambda));
}
public static IObservable<System.Reactive.Unit> AppendAllText(IObservable<System.String> path,
IObservable<System.String> contents, IObservable<System.Text.Encoding> encoding)
{
return ObservableExt.ZipExecute(path, contents, encoding,
(pathLambda, contentsLambda, encodingLambda) =>
System.IO.File.AppendAllText(pathLambda, contentsLambda, encodingLambda));
}
public static IObservable<System.Reactive.Unit> AppendAllLines(IObservable<System.String> path,
IObservable<System.Collections.Generic.IEnumerable<System.String>> contents)
{
return ObservableExt.ZipExecute(path, contents,
(pathLambda, contentsLambda) => System.IO.File.AppendAllLines(pathLambda, contentsLambda));
}
public static IObservable<System.Reactive.Unit> AppendAllLines(IObservable<System.String> path,
IObservable<System.Collections.Generic.IEnumerable<System.String>> contents,
IObservable<System.Text.Encoding> encoding)
{
return ObservableExt.ZipExecute(path, contents, encoding,
(pathLambda, contentsLambda, encodingLambda) =>
System.IO.File.AppendAllLines(pathLambda, contentsLambda, encodingLambda));
}
public static IObservable<System.Reactive.Unit> Move(IObservable<System.String> sourceFileName,
IObservable<System.String> destFileName)
{
return ObservableExt.ZipExecute(sourceFileName, destFileName,
(sourceFileNameLambda, destFileNameLambda) =>
System.IO.File.Move(sourceFileNameLambda, destFileNameLambda));
}
public static IObservable<System.Reactive.Unit> Replace(IObservable<System.String> sourceFileName,
IObservable<System.String> destinationFileName, IObservable<System.String> destinationBackupFileName)
{
return ObservableExt.ZipExecute(sourceFileName, destinationFileName, destinationBackupFileName,
(sourceFileNameLambda, destinationFileNameLambda, destinationBackupFileNameLambda) =>
System.IO.File.Replace(sourceFileNameLambda, destinationFileNameLambda,
destinationBackupFileNameLambda));
}
public static IObservable<System.Reactive.Unit> Replace(IObservable<System.String> sourceFileName,
IObservable<System.String> destinationFileName, IObservable<System.String> destinationBackupFileName,
IObservable<System.Boolean> ignoreMetadataErrors)
{
return ObservableExt.ZipExecute(sourceFileName, destinationFileName, destinationBackupFileName,
ignoreMetadataErrors,
(sourceFileNameLambda, destinationFileNameLambda, destinationBackupFileNameLambda,
ignoreMetadataErrorsLambda) =>
System.IO.File.Replace(sourceFileNameLambda, destinationFileNameLambda,
destinationBackupFileNameLambda, ignoreMetadataErrorsLambda));
}
}
}
| |
/*
* Copyright (c) 2006-2013 Michal Kuncl <[email protected]> http://www.pavucina.info
* 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.IO;
using System.Text;
using System.Threading;
namespace ArachNGIN.Files.Streams
{
/// <summary>
/// Class for working with streams. Full of static functions
/// </summary>
public static class StreamHandling
{
/// <summary>
/// Copies one stream to another.
/// </summary>
/// <param name="sSource">The source stream.</param>
/// <param name="sDest">The destination stream.</param>
/// <param name="iCount">Bytes to copy.</param>
/// <returns></returns>
/// <exception cref="IOException">An I/O error occurs. </exception>
public static long StreamCopy(Stream sSource, Stream sDest, long iCount)
{
const int maxBufSize = 0xF000;
int bufSize;
var rInput = new BinaryReader(sSource);
var wOutput = new BinaryWriter(sDest);
if (iCount == 0)
{
sSource.Position = 0;
iCount = sSource.Length;
}
var result = iCount;
if (iCount > maxBufSize) bufSize = maxBufSize;
else bufSize = (int)iCount;
try
{
// serizneme vystup
sDest.SetLength(0);
while (iCount != 0)
{
int n;
if (iCount > bufSize) n = bufSize;
else n = (int)iCount;
var buffer = rInput.ReadBytes(n);
wOutput.Write(buffer);
iCount = iCount - n;
}
}
finally
{
// si po sobe hezky splachneme :-)
wOutput.Flush();
}
return result;
}
/// <summary>
/// Copies one stream to another.
/// </summary>
/// <param name="sSource">The source stream.</param>
/// <param name="sDest">The destination stream.</param>
/// <param name="iCount">Bytes to copy.</param>
/// <param name="iStartposition">Starting position.</param>
/// <returns></returns>
/// <exception cref="IOException">An I/O error occurs. </exception>
public static long StreamCopy(Stream sSource, Stream sDest, long iCount, long iStartposition)
{
const int maxBufSize = 0xF000;
int bufSize;
var rInput = new BinaryReader(sSource);
var wOutput = new BinaryWriter(sDest);
if (iCount == 0)
{
sSource.Position = 0;
iCount = sSource.Length;
}
var result = iCount;
if (iCount > maxBufSize) bufSize = maxBufSize;
else bufSize = (int)iCount;
try
{
// naseekujeme zapisovaci pozici
wOutput.Seek((int)iStartposition, SeekOrigin.Begin);
while (iCount != 0)
{
int n;
if (iCount > bufSize) n = bufSize;
else n = (int)iCount;
var buffer = rInput.ReadBytes(n);
wOutput.Write(buffer);
iCount = iCount - n;
}
}
finally
{
// si po sobe hezky splachneme :-)
wOutput.Flush();
}
return result;
}
/// <summary>
/// Copies a stream.
/// </summary>
/// <param name="source">The stream containing the source data.</param>
/// <param name="target">The stream that will receive the source data.</param>
/// <remarks>
/// This function copies until no more can be read from the stream
/// and does not close the stream when done.<br />
/// Read and write are performed simultaneously to improve throughput.<br />
/// If no data can be read for 60 seconds, the copy will time-out.
/// </remarks>
/// <exception cref="ArgumentException">The sum of offset and count is larger than the buffer length. </exception>
/// <exception cref="IOException">Stream write failed.</exception>
/// <exception cref="AbandonedMutexException">
/// The wait completed because a thread exited without releasing a mutex. This
/// exception is not thrown on Windows 98 or Windows Millennium Edition.
/// </exception>
/// <exception cref="OverflowException">
/// The array is multidimensional and contains more than
/// <see cref="F:System.Int32.MaxValue" /> elements.
/// </exception>
public static void StreamCopyAsync(Stream source, Stream target)
{
// This stream copy supports a source-read happening at the same time
// as target-write. A simpler implementation would be to use just
// Write() instead of BeginWrite(), at the cost of speed.
var readbuffer = new byte[4096];
var writebuffer = new byte[4096];
IAsyncResult asyncResult = null;
for (;;)
{
// Read data into the readbuffer. The previous call to BeginWrite, if any,
// is executing in the background..
var read = source.Read(readbuffer, 0, readbuffer.Length);
// Ok, we have read some data and we're ready to write it, so wait here
// to make sure that the previous write is done before we write again.
if (asyncResult != null)
{
// This should work down to ~0.01kb/sec
asyncResult.AsyncWaitHandle.WaitOne(60000);
target.EndWrite(asyncResult); // Last step to the 'write'.
if (!asyncResult.IsCompleted) // Make sure the write really completed.
throw new IOException("Stream write failed.");
}
if (read <= 0)
return; // source stream says we're done - nothing else to read.
// Swap the read and write buffers so we can write what we read, and we can
// use the then use the other buffer for our next read.
var tbuf = writebuffer;
writebuffer = readbuffer;
readbuffer = tbuf;
// Asynchronously write the data, asyncResult.AsyncWaitHandle will
// be set when done.
asyncResult = target.BeginWrite(writebuffer, 0, read, null, null);
}
}
/// <summary>
/// Converts a PChar (null terminated string) to normal string
/// </summary>
/// <param name="cInput">The char array input.</param>
/// <returns></returns>
public static string PCharToString(IEnumerable<char> cInput)
{
// TODO: ODDELIT DO ArachNGIN.Strings! (az bude)
var result = new StringBuilder();
foreach (var c in cInput)
{
if (c == 0x0) break; // pcharovej konec retezce
result.Append(c);
}
return result.ToString();
}
/// <summary>
/// Converts stream to string
/// </summary>
/// <param name="stream">The stream.</param>
/// <returns></returns>
/// <exception cref="OutOfMemoryException">There is insufficient memory to allocate a buffer for the returned string. </exception>
/// <exception cref="IOException">An I/O error occurs. </exception>
public static string StreamToString(Stream stream)
{
stream.Position = 0;
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
/// <summary>
/// Converts string to stream
/// </summary>
/// <param name="source">The source.</param>
/// <returns></returns>
public static Stream StringToStream(string source)
{
var byteArray = Encoding.UTF8.GetBytes(source);
return new MemoryStream(byteArray);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace CCN.WebAPI.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using Aspose.Email;
using Aspose.Email.Mapi;
using Aspose.Email.Storage.Mbox;
using Aspose.Email.Storage.Pst;
using Aspose.Slides;
using System;
using System.IO;
namespace Aspose.Email.Live.Demos.UI.Services.Email
{
public partial class EmailService
{
public void ConvertOst(Stream input, string shortResourceNameWithExtension, IOutputHandler handler, string outputType)
{
PrepareOutputType(ref outputType);
switch (outputType)
{
case "eml": ConvertOstToEml(input, shortResourceNameWithExtension, handler); break;
case "msg": ConvertOstToMsg(input, shortResourceNameWithExtension, handler); break;
case "mbox": ConvertOstToMbox(input, shortResourceNameWithExtension, handler); break;
case "ost": ReturnSame(input, shortResourceNameWithExtension, handler); break;
case "pst": ConvertOSTToPST(input, shortResourceNameWithExtension, handler); break;
case "mht": ConvertOstToMht(input, shortResourceNameWithExtension, handler); break;
case "html": ConvertOstToHtml(input, shortResourceNameWithExtension, handler); break;
case "svg": ConvertOstToSvg(input, shortResourceNameWithExtension, handler); break;
case "tiff": ConvertOstToTiff(input, shortResourceNameWithExtension, handler); break;
case "jpg": ConvertOstToJpg(input, shortResourceNameWithExtension, handler); break;
case "bmp": ConvertOstToBmp(input, shortResourceNameWithExtension, handler); break;
case "png": ConvertOstToPng(input, shortResourceNameWithExtension, handler); break;
case "pdf": ConvertOstToPdf(input, shortResourceNameWithExtension, handler); break;
case "doc": ConvertOstToDoc(input, shortResourceNameWithExtension, handler); break;
case "ppt": ConvertOstToPpt(input, shortResourceNameWithExtension, handler); break;
case "rtf": ConvertOstToRtf(input, shortResourceNameWithExtension, handler); break;
case "docx": ConvertOstToDocx(input, shortResourceNameWithExtension, handler); break;
case "docm": ConvertOstToDocm(input, shortResourceNameWithExtension, handler); break;
case "dotx": ConvertOstToDotx(input, shortResourceNameWithExtension, handler); break;
case "dotm": ConvertOstToDotm(input, shortResourceNameWithExtension, handler); break;
case "odt": ConvertOstToOdt(input, shortResourceNameWithExtension, handler); break;
case "ott": ConvertOstToOtt(input, shortResourceNameWithExtension, handler); break;
case "epub": ConvertOstToEpub(input, shortResourceNameWithExtension, handler); break;
case "txt": ConvertOstToTxt(input, shortResourceNameWithExtension, handler); break;
case "emf": ConvertOstToEmf(input, shortResourceNameWithExtension, handler); break;
case "xps": ConvertOstToXps(input, shortResourceNameWithExtension, handler); break;
case "pcl": ConvertOstToPcl(input, shortResourceNameWithExtension, handler); break;
case "ps": ConvertOstToPs(input, shortResourceNameWithExtension, handler); break;
case "mhtml": ConvertOstToMhtml(input, shortResourceNameWithExtension, handler); break;
default:
throw new NotSupportedException($"Output type not supported {outputType.ToUpperInvariant()}");
}
}
public void ConvertOstToPng(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Png);
}
public void ConvertOstToBmp(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Bmp);
}
public void ConvertOstToJpg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Jpeg);
}
public void ConvertOstToTiff(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Tiff);
}
public void ConvertOstToSvg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Svg);
}
public void ConvertOstToHtml(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Html);
}
public void ConvertOstToMbox(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var personalStorage = PersonalStorage.FromStream(input))
{
var options = new MailConversionOptions();
using (var output = handler.CreateOutputStream(Path.ChangeExtension(shortResourceNameWithExtension, ".mbox")))
{
using (var writer = new MboxrdStorageWriter(output, false))
{
HandleFolderAndSubfolders(mapiMessage =>
{
using (var msg = mapiMessage.ToMailMessage(options))
writer.WriteMessage(msg);
}, personalStorage.RootFolder);
}
}
}
}
public void ConvertOstToMht(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
// Save as mht with header
var mhtSaveOptions = new MhtSaveOptions
{
//Specify formatting options required
//Here we are specifying to write header informations to output without writing extra print header
//and the output headers should display as the original headers in message
MhtFormatOptions = MhtFormatOptions.WriteHeader | MhtFormatOptions.HideExtraPrintHeader | MhtFormatOptions.DisplayAsOutlook,
// Check the body encoding for validity.
CheckBodyContentEncoding = true
};
using (var personalStorage = PersonalStorage.FromStream(input))
{
int i = 0;
HandleFolderAndSubfolders(mapiMessage =>
{
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension + "_Message" + i++ + ".mht"))
mapiMessage.Save(output, mhtSaveOptions);
}, personalStorage.RootFolder);
}
}
public void ConvertOstToMsg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var personalStorage = PersonalStorage.FromStream(input))
{
int i = 0;
HandleFolderAndSubfolders(mapiMessage =>
{
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension + "_Message" + i++ + ".msg"))
mapiMessage.Save(output, SaveOptions.DefaultMsgUnicode);
}, personalStorage.RootFolder);
}
}
public void ConvertOstToEml(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var personalStorage = PersonalStorage.FromStream(input))
{
int i = 0;
HandleFolderAndSubfolders(mapiMessage =>
{
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension + "_Message" + i++ + ".eml"))
mapiMessage.Save(output, SaveOptions.DefaultEml);
}, personalStorage.RootFolder);
}
}
public void ConvertOSTToPST(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
// 'SaveAs' to stream currently not supported by Aspose.Email.
// That is why convert opened ost in memory and save memoryStream to output
using (var memoryStream = new MemoryStream())
{
input.CopyTo(memoryStream);
using (var personalStorage = PersonalStorage.FromStream(memoryStream))
personalStorage.ConvertTo(FileFormat.Pst);
using (var output = handler.CreateOutputStream(Path.ChangeExtension(shortResourceNameWithExtension, ".pst")))
memoryStream.CopyTo(output);
}
}
public void ConvertOstToPdf(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Pdf);
}
public void ConvertOstToDoc(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Doc);
}
public void ConvertOstToPpt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var personalStorage = PersonalStorage.FromStream(input))
{
using (var presentation = new Presentation())
{
var firstSlide = presentation.Slides[0];
var renameCallback = new ImageSavingCallback(handler);
HandleFolderAndSubfolders(mapiMessage =>
{
var newSlide = presentation.Slides.AddClone(firstSlide);
AddMessageInSlide(presentation, newSlide, mapiMessage, renameCallback);
}, personalStorage.RootFolder);
presentation.Slides.Remove(firstSlide);
using (var output = handler.CreateOutputStream(Path.ChangeExtension(shortResourceNameWithExtension, ".ppt")))
presentation.Save(output, Aspose.Slides.Export.SaveFormat.Ppt);
}
}
}
public void ConvertOstToRtf(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Rtf);
}
public void ConvertOstToDocx(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Docx);
}
public void ConvertOstToDocm(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Docm);
}
public void ConvertOstToDotx(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Dotx);
}
public void ConvertOstToDotm(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Dotm);
}
public void ConvertOstToOdt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Odt);
}
public void ConvertOstToOtt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Ott);
}
public void ConvertOstToEpub(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Epub);
}
public void ConvertOstToTxt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Text);
}
public void ConvertOstToEmf(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Emf);
}
public void ConvertOstToXps(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Xps);
}
public void ConvertOstToPcl(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Pcl);
}
public void ConvertOstToPs(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Ps);
}
public void ConvertOstToMhtml(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Mhtml);
}
}
}
| |
// WARNING
//
// This file has been generated automatically by MonoDevelop to store outlets and
// actions made in the Xcode designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using MonoMac.Foundation;
namespace NBTExplorer
{
[Register ("MainWindow")]
partial class MainWindow
{
[Outlet]
MonoMac.AppKit.NSToolbar _toolbar { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarOpenFolder { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarSave { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarRename { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarEdit { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarDelete { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarByte { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarShort { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarInt { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarLong { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarFloat { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarDouble { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarByteArray { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarIntArray { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarString { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarList { get; set; }
[Outlet]
MonoMac.AppKit.NSToolbarItem _toolbarCompound { get; set; }
[Outlet]
MonoMac.AppKit.NSScrollView _mainScrollView { get; set; }
[Outlet]
MonoMac.AppKit.NSOutlineView _mainOutlineView { get; set; }
[Action ("ActionOpenFolder:")]
partial void ActionOpenFolder (MonoMac.Foundation.NSObject sender);
[Action ("ActionSave:")]
partial void ActionSave (MonoMac.Foundation.NSObject sender);
[Action ("ActionRename:")]
partial void ActionRename (MonoMac.Foundation.NSObject sender);
[Action ("ActionEdit:")]
partial void ActionEdit (MonoMac.Foundation.NSObject sender);
[Action ("ActionDelete:")]
partial void ActionDelete (MonoMac.Foundation.NSObject sender);
[Action ("ActionInsertByte:")]
partial void ActionInsertByte (MonoMac.Foundation.NSObject sender);
[Action ("ActionInsertShort:")]
partial void ActionInsertShort (MonoMac.Foundation.NSObject sender);
[Action ("ActionInsertInt:")]
partial void ActionInsertInt (MonoMac.Foundation.NSObject sender);
[Action ("ActionInsertLong:")]
partial void ActionInsertLong (MonoMac.Foundation.NSObject sender);
[Action ("ActionInsertFloat:")]
partial void ActionInsertFloat (MonoMac.Foundation.NSObject sender);
[Action ("ActionInsertDouble:")]
partial void ActionInsertDouble (MonoMac.Foundation.NSObject sender);
[Action ("ActionInsertByteArray:")]
partial void ActionInsertByteArray (MonoMac.Foundation.NSObject sender);
[Action ("ActionInsertIntArray:")]
partial void ActionInsertIntArray (MonoMac.Foundation.NSObject sender);
[Action ("ActionInsertString:")]
partial void ActionInsertString (MonoMac.Foundation.NSObject sender);
[Action ("ActionInsertList:")]
partial void ActionInsertList (MonoMac.Foundation.NSObject sender);
[Action ("ActionInsertCompound:")]
partial void ActionInsertCompound (MonoMac.Foundation.NSObject sender);
void ReleaseDesignerOutlets ()
{
if (_toolbar != null) {
_toolbar.Dispose ();
_toolbar = null;
}
if (_toolbarOpenFolder != null) {
_toolbarOpenFolder.Dispose ();
_toolbarOpenFolder = null;
}
if (_toolbarSave != null) {
_toolbarSave.Dispose ();
_toolbarSave = null;
}
if (_toolbarRename != null) {
_toolbarRename.Dispose ();
_toolbarRename = null;
}
if (_toolbarEdit != null) {
_toolbarEdit.Dispose ();
_toolbarEdit = null;
}
if (_toolbarDelete != null) {
_toolbarDelete.Dispose ();
_toolbarDelete = null;
}
if (_toolbarByte != null) {
_toolbarByte.Dispose ();
_toolbarByte = null;
}
if (_toolbarShort != null) {
_toolbarShort.Dispose ();
_toolbarShort = null;
}
if (_toolbarInt != null) {
_toolbarInt.Dispose ();
_toolbarInt = null;
}
if (_toolbarLong != null) {
_toolbarLong.Dispose ();
_toolbarLong = null;
}
if (_toolbarFloat != null) {
_toolbarFloat.Dispose ();
_toolbarFloat = null;
}
if (_toolbarDouble != null) {
_toolbarDouble.Dispose ();
_toolbarDouble = null;
}
if (_toolbarByteArray != null) {
_toolbarByteArray.Dispose ();
_toolbarByteArray = null;
}
if (_toolbarIntArray != null) {
_toolbarIntArray.Dispose ();
_toolbarIntArray = null;
}
if (_toolbarString != null) {
_toolbarString.Dispose ();
_toolbarString = null;
}
if (_toolbarList != null) {
_toolbarList.Dispose ();
_toolbarList = null;
}
if (_toolbarCompound != null) {
_toolbarCompound.Dispose ();
_toolbarCompound = null;
}
if (_mainScrollView != null) {
_mainScrollView.Dispose ();
_mainScrollView = null;
}
if (_mainOutlineView != null) {
_mainOutlineView.Dispose ();
_mainOutlineView = null;
}
}
}
[Register ("MainWindowController")]
partial class MainWindowController
{
void ReleaseDesignerOutlets ()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using Htc.Vita.Core.Log;
using Htc.Vita.Core.Util;
namespace Htc.Vita.Core.Auth
{
public static partial class OAuth2
{
/// <summary>
/// Class ClientAssistantFactory.
/// </summary>
public abstract class ClientAssistantFactory
{
static ClientAssistantFactory()
{
TypeRegistry.RegisterDefault<ClientAssistantFactory, DefaultOAuth2.DefaultClientAssistantFactory>();
}
/// <summary>
/// Registers this instance type.
/// </summary>
/// <typeparam name="T"></typeparam>
public static void Register<T>()
where T : ClientAssistantFactory, new()
{
TypeRegistry.Register<ClientAssistantFactory, T>();
}
/// <summary>
/// Gets the instance.
/// </summary>
/// <returns>ClientAssistantFactory.</returns>
public static ClientAssistantFactory GetInstance()
{
return TypeRegistry.GetInstance<ClientAssistantFactory>();
}
/// <summary>
/// Gets the instance.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>ClientAssistantFactory.</returns>
public static ClientAssistantFactory GetInstance<T>()
where T : ClientAssistantFactory, new()
{
return TypeRegistry.GetInstance<ClientAssistantFactory, T>();
}
/// <summary>
/// Gets the authorization code receiver.
/// </summary>
/// <returns>AuthorizationCodeReceiver.</returns>
public AuthorizationCodeReceiver GetAuthorizationCodeReceiver()
{
return GetAuthorizationCodeReceiver(
null,
CancellationToken.None
);
}
/// <summary>
/// Gets the authorization code receiver.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>AuthorizationCodeReceiver.</returns>
public AuthorizationCodeReceiver GetAuthorizationCodeReceiver(
Dictionary<string, object> options,
CancellationToken cancellationToken)
{
AuthorizationCodeReceiver result = null;
try
{
result = OnGetAuthorizationCodeReceiver(
options,
cancellationToken
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(ClientAssistantFactory)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Gets the authorization code user agent.
/// </summary>
/// <returns>AuthorizationCodeUserAgent.</returns>
public AuthorizationCodeUserAgent GetAuthorizationCodeUserAgent()
{
return GetAuthorizationCodeUserAgent(
null,
CancellationToken.None
);
}
/// <summary>
/// Gets the authorization code user agent.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>AuthorizationCodeUserAgent.</returns>
public AuthorizationCodeUserAgent GetAuthorizationCodeUserAgent(
Dictionary<string, object> options,
CancellationToken cancellationToken)
{
AuthorizationCodeUserAgent result = null;
try
{
result = OnGetAuthorizationCodeUserAgent(
options,
cancellationToken
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(ClientAssistantFactory)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Called when getting authorization code receiver.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>AuthorizationCodeReceiver.</returns>
protected abstract AuthorizationCodeReceiver OnGetAuthorizationCodeReceiver(
Dictionary<string, object> options,
CancellationToken cancellationToken
);
/// <summary>
/// Called when getting authorization code user agent.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>AuthorizationCodeUserAgent.</returns>
protected abstract AuthorizationCodeUserAgent OnGetAuthorizationCodeUserAgent(
Dictionary<string, object> options,
CancellationToken cancellationToken
);
}
/// <summary>
/// Class ClientFactory.
/// </summary>
public abstract class ClientFactory
{
static ClientFactory()
{
TypeRegistry.RegisterDefault<ClientFactory, DummyOAuth2.DummyClientFactory>();
}
/// <summary>
/// Registers this instance type.
/// </summary>
/// <typeparam name="T"></typeparam>
public static void Register<T>()
where T : ClientFactory, new()
{
TypeRegistry.Register<ClientFactory, T>();
}
/// <summary>
/// Gets the instance.
/// </summary>
/// <returns>ClientFactory.</returns>
public static ClientFactory GetInstance()
{
return TypeRegistry.GetInstance<ClientFactory>();
}
/// <summary>
/// Gets the instance.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>ClientFactory.</returns>
public static ClientFactory GetInstance<T>()
where T : ClientFactory, new()
{
return TypeRegistry.GetInstance<ClientFactory, T>();
}
/// <summary>
/// Gets the authorization code client.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>AuthorizationCodeClient.</returns>
public AuthorizationCodeClient GetAuthorizationCodeClient(AuthorizationCodeClientConfig config)
{
AuthorizationCodeClient result = null;
try
{
result = OnGetAuthorizationCodeClient(config);
}
catch (Exception e)
{
Logger.GetInstance(typeof(ClientFactory)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Called when getting authorization code client.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>AuthorizationCodeClient.</returns>
protected abstract AuthorizationCodeClient OnGetAuthorizationCodeClient(AuthorizationCodeClientConfig config);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using MetX.Standard.Library.Extensions;
namespace MetX.Standard.Library.Encryption
{
public static class SuperRandom
{
private static RNGCryptoServiceProvider _provider;
private static HashAlgorithm _shaProvider;
public static int StartSaltingAtIndex;
public static byte[] Salt;
static SuperRandom()
{
ResetProvider(null);
}
public static void ResetProvider(byte[] saltBytes)
{
_provider = new RNGCryptoServiceProvider();
_shaProvider = SHA256.Create();
FillSaltShaker(saltBytes);
}
public static long NextLong(long minValue, long maxExclusiveValue)
{
if (minValue >= maxExclusiveValue)
throw new ArgumentOutOfRangeException(nameof(minValue),
"minValue must be lower than maxExclusiveValue");
var diff = maxExclusiveValue - minValue;
var upperBound = long.MaxValue / diff * diff;
long value;
do
{
value = NextLong();
} while (value >= upperBound);
return minValue + value % diff;
}
public static int NextInteger(int minValue, int maxExclusiveValue)
{
if (minValue >= maxExclusiveValue)
throw new ArgumentOutOfRangeException(nameof(minValue),
"minValue must be lower than maxExclusiveValue");
var diff = maxExclusiveValue - minValue;
var upperBound = int.MaxValue / diff * diff;
int value;
do
{
value = NextInteger();
} while (value >= upperBound);
return minValue + value % diff;
}
public static int NextInteger()
{
var randomBytes = NextBytes(sizeof(int));
return BitConverter.ToInt32(randomBytes, 0);
}
public static uint NextUnsignedInteger()
{
var randomBytes = NextBytes(sizeof(uint), false);
return BitConverter.ToUInt32(randomBytes, 0);
}
public static uint NextUnsignedInteger(uint minValue, uint maxExclusiveValue)
{
if (minValue >= maxExclusiveValue)
throw new ArgumentOutOfRangeException(nameof(minValue),
"minValue must be lower than maxExclusiveValue");
var diff = maxExclusiveValue - minValue;
var value = NextUnsignedInteger();
if (value > diff)
value %= diff;
return minValue + value;
}
public static int BitsUsed(int n)
{
int count = 0, i;
if(n==0) return 0;
for(i=0; i < 32; i++)
{
var i1 = (1 << i) & n;
if( i1 != 0)
count = i;
}
return ++count;
}
public static int BitsUsed(uint n)
{
int count = 0, i;
if(n==0) return 0;
for(i=0; i < 32; i++)
{
var i1 = (1 << i) & n;
if( i1 != 0)
count = i;
}
return ++count;
}
public static string NextString(int length, bool includeLetters, bool includeNumbers, bool includeSymbols, bool includeSpace)
{
if (length < 1)
return "";
var bytes = NextBytes(sizeof(char) * length * 100);
var result = "";
for (var i = 0; i < bytes.Length; i++)
{
if (bytes[i] >= 127)
bytes[i] -= 127;
if (includeLetters && bytes[i] >= 'a' && bytes[i] <= 'z'
|| bytes[i] >= 'A' && bytes[i] <= 'Z')
result += bytes[i];
else if (includeNumbers && bytes[i] >= '0' && bytes[i] <= '9')
result += bytes[i];
else if (includeSpace && bytes[i] == 32)
result += bytes[i];
else if (includeSymbols
&& (bytes[i] >= '!' && bytes[i] <= '/'
|| bytes[i] >= ':' && bytes[i] <= '@'
|| bytes[i] >= '[' && bytes[i] <= '_'))
result += bytes[i];
}
return result;
}
public static char NextChar()
{
var randomBytes = NextBytes(sizeof(char));
return BitConverter.ToChar(randomBytes, 0);
}
public static uint NextRoll(int dice, int sides)
{
if (dice < 1 || sides < 1)
return 1;
uint result = 0;
for (var i = 0; i < dice; i++)
result += NextUnsignedInteger((uint) 1, (uint) sides);
return result;
}
public static long NextLong()
{
var randomBytes = NextBytes(sizeof(long));
return BitConverter.ToInt64(randomBytes, 0);
}
public static string NextHash(byte[] bytes)
{
return _shaProvider.ComputeHash(bytes).AsString();
}
public static string NextHash(IEnumerable<byte> bytes)
{
return _shaProvider.ComputeHash(bytes.ToArray()).AsString();
}
public static string NextSaltedHash(string data)
{
return data.IsEmpty() ? "" : NextHash(data.ToLower(), SaltShaker);
}
public static string NextHash(string data, Func<byte[], IEnumerable<byte>> shaker = null)
{
if (data.IsEmpty())
return "";
var bytes = _shaProvider
.ComputeHash(data
.ToCharArray()
.Select(c => (byte) c)
.ToArray());
if (shaker == null)
return NextHash(bytes);
var seasonedBytes = shaker(bytes);
return NextHash(seasonedBytes);
}
public static void FillSaltShaker(byte[] salt)
{
if(salt == null)
{
FillSaltShaker();
return;
}
var randomLength = NextInteger(1024, 2048);
StartSaltingAtIndex = 0;
Salt = Repeating(salt, randomLength);
}
public static byte[] Repeating(byte[] bytes, int targetLength)
{
if (bytes == null) return null;
if (bytes.Length == targetLength) return bytes;
if (bytes.Length > targetLength) return bytes.Take(targetLength).ToArray();
var repeated = new byte[targetLength];
for (int i = 0, j = 0; i < targetLength; i++)
{
if (j > bytes.Length - 1)
j = 0;
repeated[i] = bytes[j++];
}
return repeated;
}
public static void FillSaltShaker(int startSaltingAtIndex = 0)
{
StartSaltingAtIndex = startSaltingAtIndex;
var randomLength = NextInteger(1024, 2048);
Salt = NextBytes(randomLength);
}
public static IEnumerable<byte> SaltShaker(IEnumerable<byte> bytes)
{
var byteArray = bytes.ToArray();
for (var i = 0; i < StartSaltingAtIndex && i < byteArray.Length; i++) yield return byteArray[i];
for (var i = StartSaltingAtIndex; i < byteArray.Length; i++)
yield return byteArray[i] ^= Salt[i - StartSaltingAtIndex];
}
public static Func<byte, byte> SpiceBlender => DefaultSpiceBlender;
private static byte DefaultSpiceBlender(byte byteIn)
{
return byteIn.RotateLeft(3);
}
public static IEnumerable<byte> SpiceBlendShaker(IEnumerable<byte> bytes)
{
foreach(var byteIn in bytes)
{
var byteOut = SpiceBlender(byteIn);
yield return byteOut;
}
}
public static byte RotateLeft(this byte value, int count)
{
return (byte) ((value << count) | (value >> (32 - count)));
}
public static byte RotateRight(this byte value, int count)
{
return (byte) ((byte) (value >> count) | (value << (32 - count)));
}
public static byte[] NextBytes(int bytesNumber, bool zeroTheLastByte = false)
{
if (bytesNumber < 1)
return Array.Empty<byte>();
var buffer = new byte[bytesNumber];
_provider.GetBytes(buffer);
for (var i = 0; i < bytesNumber; i++)
{
if (buffer[i] == 0)
buffer[i] = (byte) NextChar();
}
if (zeroTheLastByte)
buffer[bytesNumber-1] = 0;
return buffer;
}
public static string AsString(this byte[] arrInput)
{
int i;
var result = new StringBuilder(arrInput.Length);
for (i = 0; i < arrInput.Length - 1; i++) result.Append(arrInput[i].ToString("X2"));
return result.ToString();
}
}
}
| |
using System;
using System.ServiceModel.Channels;
using System.Xml;
using RabbitMQ.Client;
namespace MessageBus.Binding.RabbitMQ
{
public enum MessageFormat
{
Text = 0x0,
MTOM = 0x1,
NetBinary = 0x2,
}
/// <summary>
/// A windows communication foundation binding over AMQP
/// </summary>
public sealed class RabbitMQBinding : System.ServiceModel.Channels.Binding
{
private bool _isInitialized;
private CompositeDuplexBindingElement _duplex;
private TextMessageEncodingBindingElement _textEncoding;
private MtomMessageEncodingBindingElement _mtomEncoding;
private BinaryMessageEncodingBindingElement _binaryEncoding;
private RabbitMQTransportBindingElement _transport;
/// <summary>
/// Creates a new instance of the RabbitMQBinding class initialized
/// to use the Protocols.DefaultProtocol. The broker must be set
/// before use.
/// </summary>
public RabbitMQBinding()
: this(Protocols.DefaultProtocol)
{ }
/// <summary>
/// Uses the specified protocol. The broker must be set before use.
/// </summary>
/// <param name="protocol">The protocol version to use</param>
public RabbitMQBinding(IProtocol protocol)
{
BrokerProtocol = protocol;
// Set defaults
OneWayOnly = true;
ExactlyOnce = false;
Name = "RabbitMQBinding";
Namespace = "http://schemas.rabbitmq.com/2007/RabbitMQ/";
Initialize();
}
public override BindingElementCollection CreateBindingElements()
{
_transport.BrokerProtocol = BrokerProtocol;
_transport.TransactedReceiveEnabled = ExactlyOnce;
_transport.TTL = TTL;
_transport.AutoDelete = AutoDelete;
_transport.PersistentDelivery = PersistentDelivery;
_transport.AutoBindExchange = AutoBindExchange;
_transport.ReplyToQueue = ReplyToQueue;
_transport.ReplyToExchange = ReplyToExchange;
_transport.OneWayOnly = OneWayOnly;
_transport.ApplicationId = ApplicationId;
_transport.MessageFormat = MessageFormat;
_transport.HeaderNamespace = HeaderNamespace;
_transport.Immediate = Immediate;
_transport.Mandatory = Mandatory;
if (ReaderQuotas != null)
{
ReaderQuotas.CopyTo(_textEncoding.ReaderQuotas);
ReaderQuotas.CopyTo(_mtomEncoding.ReaderQuotas);
ReaderQuotas.CopyTo(_binaryEncoding.ReaderQuotas);
}
BindingElementCollection elements = new BindingElementCollection();
if (!OneWayOnly)
{
elements.Add(_duplex);
}
elements.Add(_binaryEncoding);
elements.Add(_mtomEncoding);
elements.Add(_textEncoding);
elements.Add(_transport);
return elements;
}
private void Initialize()
{
lock (this)
{
if (!_isInitialized)
{
_transport = new RabbitMQTransportBindingElement();
_textEncoding = new TextMessageEncodingBindingElement();
_mtomEncoding = new MtomMessageEncodingBindingElement();
_binaryEncoding = new BinaryMessageEncodingBindingElement();
_duplex = new CompositeDuplexBindingElement();
_isInitialized = true;
}
}
}
/// <summary>
/// Gets the scheme used by the binding
/// </summary>
public override string Scheme
{
get { return CurrentVersion.Scheme; }
}
/// <summary>
/// Specifies the version of the AMQP protocol that should be used to communicate with the broker
/// </summary>
public IProtocol BrokerProtocol { get; set; }
/// <summary>
/// Gets the AMQP transport binding element
/// </summary>
public RabbitMQTransportBindingElement Transport
{
get { return _transport; }
}
/// <summary>
/// Enables transactional message delivery
/// </summary>
public bool ExactlyOnce { get; set; }
/// <summary>
/// Message time to live
/// </summary>
public string TTL { get; set; }
/// <summary>
/// Temporary queue
/// </summary>
public bool AutoDelete { get; set; }
/// <summary>
/// ReplyTo queue name for duplex communication
/// </summary>
/// <remarks>If null will auto delete queue will be generated</remarks>
public string ReplyToQueue { get; set; }
/// <summary>
/// ReplyTo exchange URI for duplex communication callbacks
/// </summary>
public Uri ReplyToExchange { get; set; }
/// <summary>
/// Exchange name to bind the listening queue. Value can be null.
/// </summary>
/// <remarks>If null queue will not be binded automaticaly</remarks>
public string AutoBindExchange { get; set; }
/// <summary>
/// Defines messages delivery mode
/// </summary>
public bool PersistentDelivery { get; set; }
/// <summary>
/// Defines if one way or duplex comunication is required over this binding
/// </summary>
public bool OneWayOnly { get; set; }
/// <summary>
/// Application identificator. If not blanked will attached to the published messages.
/// </summary>
/// <remarks>
/// If IgnoreSelfPublished is True messages with same application id will be dropped.
/// </remarks>
/// <remarks>
/// If not blanked application id will be used as queue name if queue name is not supplied by listener address or ReplyToQueue
/// </remarks>
public string ApplicationId { get; set; }
/// <summary>
/// Defines which message format to use when messages are sent
/// </summary>
/// <remarks>
/// Received messages may be in all supported format even for the same binding
/// </remarks>
public MessageFormat MessageFormat { get; set; }
/// <summary>
/// Specify SOAP headers namespace to map to AMQP message header
/// </summary>
public string HeaderNamespace { get; set; }
/// <summary>
/// Serializer quotas
/// </summary>
public XmlDictionaryReaderQuotas ReaderQuotas { get; set; }
/// <summary>
/// This flag tells the server how to react if the message cannot be routed to a queue. If this flag is set, the server will return an unroutable message with a Return method. If this flag is zero, the server silently drops the message.
/// </summary>
public bool Mandatory { get; set; }
/// <summary>
/// This flag tells the server how to react if the message cannot be routed to a queue consumer immediately. If this flag is set, the server will return an undeliverable message with a Return method. If this flag is zero, the server will queue the message, but with no guarantee that it will ever be consumed.
/// </summary>
public bool Immediate { get; set; }
}
}
| |
// Copyright 2005-2012 Moonfire Games
// Released under the MIT license
// http://mfgames.com/mfgames-cil/license
using System;
using System.Collections.Generic;
using System.Text;
using MfGames.Exceptions;
using MfGames.Extensions.System;
namespace MfGames.HierarchicalPaths
{
/// <summary>
/// Represents an hierarchical path given in the same form as a Unix file
/// path. This is chosen because the forward slash does not require
/// escaping in C# strings and it is a well-known paradim for representing
/// a reference in a tree structure. The individual parts of the path
/// are called Levels.
///
/// There are two forms of paths: absolute and relative. Absolute paths
/// always start with a leading forward slash ("/") and relative start with
/// a period and slash ("."). Otherwise, they follow the same rules for
/// formatting. No path ends with a trailing slash nor can a path element
/// be blank. In these cases (e.g., "/root//child/"), the doubled slash
/// will be collapsed into a single one (e.g., "/root/child").
///
/// Paths can include any Unicode character without escaping except for
/// the backslash and the forward slash. In both cases, the two slashes
/// must be escaped with a backslash (e.g., "\\" and "\/").
///
/// HierarchicalPath is a read-only object. Once created, no methods directly
/// alter the object. Instead, they return a new modified path.
/// </summary>
[Serializable]
public class HierarchicalPath: IComparable<HierarchicalPath>
{
#region Properties
/// <summary>
/// Returns the nth element of the path.
/// </summary>
public string this[int index]
{
get { return levels[index]; }
}
/// <summary>
/// A simple accessor that allows retrieval of a child path
/// from this one. This, in effect, calls Append(). The
/// exception is if the path is given as ".." which then returns
/// the parent object as appropriate (this will already return
/// something, unlike ParentPath or Parent.
/// </summary>
public HierarchicalPath this[string childPath]
{
get { return Append(childPath); }
}
/// <summary>
/// Returns the number of components in the path.
/// </summary>
public int Count
{
get { return levels.Length; }
}
/// <summary>
/// Gets the first level (or root) in the path.
/// </summary>
/// <value>The first.</value>
public string First
{
get
{
// If we have a level, return the value.
if (levels.Length > 0)
{
return levels[0];
}
// We don't have any, so return the root element.
return isRelative
? "."
: "/";
}
}
/// <summary>
/// Contains a flag if the path is relative or absolute.
/// </summary>
public bool IsRelative
{
get { return isRelative; }
}
/// <summary>
/// Gets the last level in the path.
/// </summary>
/// <value>The last.</value>
public string Last
{
get
{
// If we have a level, return the value.
if (levels.Length > 0)
{
return levels[levels.Length - 1];
}
// We don't have any, so return the root element.
return isRelative
? "."
: "/";
}
}
/// <summary>
/// Contains an array of individual levels within the path.
/// </summary>
public IList<string> Levels
{
get { return new List<string>(levels); }
}
/// <summary>
/// Returns the node reference for a parent. If this is already
/// the root, it will automatically return null on this object.
/// </summary>
public HierarchicalPath Parent
{
get
{
// If we have no parts, we don't have a parent.
if (levels.Length == 0)
{
return null;
}
// If we have exactly one level, then we are just the root.
if (levels.Length == 1)
{
return isRelative
? RelativeRoot
: AbsoluteRoot;
}
// Create a new path without the last item in it.
var parentLevels = new string[levels.Length - 1];
for (int index = 0;
index < levels.Length - 1;
index++)
{
parentLevels[index] = levels[index];
}
return new HierarchicalPath(parentLevels, isRelative);
}
}
/// <summary>
/// Returns the string version of the path including escaping for
/// the special characters.
/// </summary>
public string Path
{
get
{
// Check for the simple paths.
if (levels.Length == 0)
{
return isRelative
? "."
: "/";
}
// Build up the path including any escaping.
var buffer = new StringBuilder();
if (isRelative)
{
buffer.Append(".");
}
foreach (string level in levels)
{
buffer.Append("/");
buffer.Append(level.Replace("\\", "\\\\").Replace("/", "\\/"));
}
// Return the resulting string.
return buffer.ToString();
}
}
#endregion
#region Methods
/// <summary>
/// Creates a child from this node, by creating the path that uses
/// this object as a context.
/// </summary>
public HierarchicalPath Append(string childPath)
{
// By the rules, prefixing "./" will also create the desired
// results and use this as a context.
return new HierarchicalPath("./" + childPath, this);
}
/// <summary>
/// Compares the path to another path.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public int CompareTo(HierarchicalPath other)
{
return ToString().CompareTo(other.ToString());
}
/// <summary>
/// Does an equality check on the other path.
/// </summary>
/// <param name="other">The other.</param>
/// <returns></returns>
public bool Equals(HierarchicalPath other)
{
// Make sure that the other is not null.
if (ReferenceEquals(null, other))
{
return false;
}
// If we are identical objects, then return true.
if (ReferenceEquals(this, other))
{
return true;
}
// Check for the relatively.
if (other.isRelative != isRelative)
{
return false;
}
// Equality on the array of strings doesn't work as expected, so we
// compare each string to itself.
string[] otherLevels = other.levels;
if (otherLevels.Length != levels.Length)
{
return false;
}
for (int i = 0;
i < otherLevels.Length;
i++)
{
if (!otherLevels[i].Equals(levels[i]))
{
return false;
}
}
// We got this far, therefore we are equal.
return true;
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof (HierarchicalPath))
{
return false;
}
return Equals((HierarchicalPath) obj);
}
/// <summary>
/// Overrides the hash code to prevent the errors.
/// </summary>
public override int GetHashCode()
{
unchecked
{
// Build up the hash, starting with the flag.
int hashCode = isRelative.GetHashCode() * 397;
// We can't use the array itself because it doesn't produce
// a consistent hash code for dictionary operations.
for (int i = 0;
i < levels.Length;
i++)
{
hashCode ^= levels[i].GetHashCode();
}
// Return the results.
return hashCode;
}
}
/// <summary>
/// Gets the child path of this path after the root path. If the path
/// doesn't start with the rootPath, an exception is thrown.
/// </summary>
/// <param name="rootPath">The root path.</param>
/// <returns></returns>
public HierarchicalPath GetPathAfter(HierarchicalPath rootPath)
{
// Check for the starting path.
if (!StartsWith(rootPath))
{
throw new HierarchicalPathException(
"The two paths don't have a common prefix");
}
// Strip off the root path and create a new path.
var newLevels = new string[levels.Length - rootPath.levels.Length];
for (int index = rootPath.levels.Length;
index < levels.Length;
index++)
{
newLevels[index - rootPath.levels.Length] = levels[index];
}
// Create the new path and return it. This will always be relative
// to the given path since it is a subset.
return new HierarchicalPath(newLevels, true);
}
/// <summary>
/// Gets the subpath starting with the given index.
/// </summary>
/// <param name="firstIndex">The first index.</param>
/// <returns></returns>
public HierarchicalPath Splice(int firstIndex)
{
return new HierarchicalPath(levels, firstIndex, true);
}
/// <summary>
/// Splices the path into a subset of the path, creating a
/// new path.
/// </summary>
/// <param name="offset">The offset.</param>
/// <param name="count">The count.</param>
/// <returns></returns>
public HierarchicalPath Splice(
int offset,
int count)
{
return Splice(offset, count, offset > 0);
}
/// <summary>
/// Splices the path into a subset of the path, creating a
/// new path.
/// </summary>
/// <param name="offset">The offset.</param>
/// <param name="count">The count.</param>
/// <param name="makeRelative">if set to <c>true</c> [make relative].</param>
/// <returns></returns>
public HierarchicalPath Splice(
int offset,
int count,
bool makeRelative)
{
string[] newLevels = levels.Splice(offset, count);
var hierarchicalPath = new HierarchicalPath(newLevels, makeRelative);
return hierarchicalPath;
}
/// <summary>
/// Returns true if the current path starts with the same elements as
/// the specified path and they have the same absolute/relative root.
/// </summary>
/// <param name="path">The path.</param>
/// <returns></returns>
public bool StartsWith(HierarchicalPath path)
{
// Make sure we didn't get a null.
if (path == null)
{
return false;
}
// If the given path is longer than ourselves, then it won't be.
if (levels.Length < path.levels.Length)
{
return false;
}
// If our root type isn't the same, then they don't match.
if (isRelative != path.isRelative)
{
return false;
}
// Loop through the elements in the path and make sure they match
// with the elements of this path.
for (int index = 0;
index < path.levels.Length;
index++)
{
if (levels[index] != path.levels[index])
{
return false;
}
}
// The current path has all the same elements as the given path.
return true;
}
/// <summary>
/// Returns the path when requested as a string.
/// </summary>
public override string ToString()
{
return Path;
}
/// <summary>
/// Appends the level to the list, processing the "." and ".." elements
/// into the list operation.
/// </summary>
/// <param name="levels">The levels.</param>
/// <param name="level">The level.</param>
private static void AppendLevel(
List<string> levels,
string level)
{
// Levels cannot be blank, so throw an exception if we get it.
if (levels == null)
{
throw new ArgumentNullException("levels");
}
// If we have a blank level, we do nothing. This way, we can handle
// various "//" or trailing "/" elements in the parse.
if (String.IsNullOrEmpty(level))
{
return;
}
// Check for the path operations in the list.
if (level == ".")
{
// This is a current path operation, which is simply skipped
// (e.g., "/root/./child" = "/root/child").
return;
}
if (level == "..")
{
// This is a "move up" operation which pops the last item off
// the passed in levels from the list. If there is insuffient
// levels, it will throw an exception.
if (levels.Count == 0)
{
throw new InvalidPathException("Cannot parse .. with sufficient levels.");
}
levels.RemoveAt(levels.Count - 1);
return;
}
// Otherwise, we just append the level to the list.
levels.Add(level);
}
/// <summary>
/// This parses the given path and sets the internal variables to
/// represent the given path.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="context">The context.</param>
/// <param name="options">The options.</param>
private void ParsePath(
string path,
HierarchicalPath context,
HierarchicalPathOptions options)
{
// Perform some sanity checking on the path
if (String.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
// Check for simple paths that are only a / (absolute root) or
// . (relative root).
if (path.Length == 1)
{
if (path == "/")
{
// We can short-cut the processing of this path since there
// is only one element.
isRelative = false;
levels = new string[]
{
};
return;
}
if (path == ".")
{
// This is a relative path that has no other elements inside
// it. We can short-cut the parsing and finish up here.
if (context != null)
{
isRelative = context.IsRelative;
levels = context.levels;
}
else
{
isRelative = true;
levels = new string[]
{
};
}
return;
}
}
// We don't have a simple root path. Check to see if the path starts
// with a forward slash. If it does, it is an absolute path, otherwise
// it will be relative.
var parsedLevels = new List<string>();
int index = 0;
if (path.StartsWith("/"))
{
// This is an absolute root path.
isRelative = false;
index++;
}
else
{
// This is a relative path, so prepend the context, if we have
// one to our parsed levels.
if (context != null)
{
// Copy the contents of the context.
isRelative = context.IsRelative;
parsedLevels.AddRange(context.Levels);
}
else
{
// This is a relative path.
isRelative = true;
}
}
// Go through the remaining elements of the string and break them
// into the individual levels.
var currentLevel = new StringBuilder();
for (; index < path.Length;
index++)
{
// Check for the next character.
switch (path[index])
{
case '\\':
// Check to see if the escape character is the last
// character in the input string.
if (index == path.Length - 1)
{
// We have an escape backslash but we are at the end of
// the line.
throw new InvalidPathException(
"Cannot parse with escape at end of line: " + path);
}
// Grab the next character after the backslash.
currentLevel.Append(path[index + 1]);
index++;
break;
case '/':
AppendLevel(parsedLevels, currentLevel.ToString());
currentLevel.Length = 0;
break;
default:
// Add the character to the current level.
currentLevel.Append(path[index]);
break;
}
}
// Outside of the loop, we check to see if there is anything left
// in the current level and add it to the list.
AppendLevel(parsedLevels, currentLevel.ToString());
// Saved the parsed levels into the levels property.
levels = parsedLevels.ToArray();
// If we are interning, then intern all the strings.
if ((options & HierarchicalPathOptions.InternStrings)
== HierarchicalPathOptions.InternStrings)
{
for (int i = 0;
i < levels.Length;
i++)
{
levels[i] = String.Intern(levels[i]);
}
}
}
#endregion
#region Operators
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="c1">The c1.</param>
/// <param name="c2">The c2.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(HierarchicalPath c1,
HierarchicalPath c2)
{
if (ReferenceEquals(null, c1)
&& ReferenceEquals(null, c2))
{
return true;
}
return c1.Equals(c2);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="c1">The c1.</param>
/// <param name="c2">The c2.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(HierarchicalPath c1,
HierarchicalPath c2)
{
return !(c1 == c2);
}
#endregion
#region Constructors
/// <summary>
/// Creates an empty path that is either absolute or relative based
/// </summary>
public HierarchicalPath(bool isRelative)
{
this.isRelative = isRelative;
levels = new string[]
{
};
}
/// <summary>
/// Constructs a node reference using only the given path. If the
/// path is invalid in any manner, including not being absolute,
/// an exception is thrown.
/// </summary>
/// <param name="path">The path.</param>
public HierarchicalPath(string path)
: this(path, null, HierarchicalPathOptions.None)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HierarchicalPath"/> class.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="options">The options.</param>
public HierarchicalPath(
string path,
HierarchicalPathOptions options)
{
// Create the path components
ParsePath(path, null, options);
}
/// <summary>
/// Initializes a new instance of the <see cref="HierarchicalPath"/> class.
/// </summary>
/// <param name="levels">The levels.</param>
/// <param name="isRelative">if set to <c>true</c> [is relative].</param>
public HierarchicalPath(
IEnumerable<string> levels,
bool isRelative)
{
// Create a sub-array version of the path.
var parts = new List<string>();
foreach (string level in levels)
{
parts.Add(level);
}
// Save the components.
this.levels = parts.ToArray();
this.isRelative = isRelative;
}
/// <summary>
/// Initializes a new instance of the <see cref="HierarchicalPath"/> class.
/// </summary>
/// <param name="levels">The levels.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="isRelative">if set to <c>true</c> [is relative].</param>
public HierarchicalPath(
IEnumerable<string> levels,
int startIndex,
bool isRelative)
{
// Create a sub-array version of the path.
var parts = new List<string>();
foreach (string level in levels)
{
parts.Add(level);
}
// Get the subset of those levels.
this.levels = new string[parts.Count - startIndex];
for (int index = startIndex;
index < parts.Count;
index++)
{
this.levels[index - startIndex] = parts[index];
}
this.isRelative = isRelative;
}
/// <summary>
/// Initializes a new instance of the <see cref="HierarchicalPath"/> class.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="context">The context.</param>
public HierarchicalPath(
string path,
HierarchicalPath context)
: this(path, context, HierarchicalPathOptions.None)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HierarchicalPath"/> class.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="context">The context.</param>
/// <param name="options">The options.</param>
public HierarchicalPath(
string path,
HierarchicalPath context,
HierarchicalPathOptions options)
{
// Create the path components
ParsePath(path, context, options);
}
#endregion
#region Fields
/// <summary>
/// Contains static instance for an absolute root path (i.e., "/").
/// </summary>
public static readonly HierarchicalPath AbsoluteRoot =
new HierarchicalPath(false);
/// <summary>
/// Contains a static instance of a relative root path (i.e., ".").
/// </summary>
public static readonly HierarchicalPath RelativeRoot =
new HierarchicalPath(true);
private bool isRelative;
private string[] levels;
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Author : hiyohiyo
// Mail : [email protected]
// Web : http://openlibsys.org/
// License : The modified BSD license
//
// Copyright 2007-2009 OpenLibSys.org. All rights reserved.
//-----------------------------------------------------------------------------
// This is support library for WinRing0 1.3.x.
using System;
using System.Runtime.InteropServices;
namespace Callor
{
public class Ols : IDisposable
{
const string dllNameX64 = "WinRing0x64.dll";
const string dllName = "WinRing0.dll";
// for this support library
public enum Status
{
NO_ERROR = 0,
DLL_NOT_FOUND = 1,
DLL_INCORRECT_VERSION = 2,
DLL_INITIALIZE_ERROR = 3,
}
// for WinRing0
public enum OlsDllStatus
{
OLS_DLL_NO_ERROR = 0,
OLS_DLL_UNSUPPORTED_PLATFORM = 1,
OLS_DLL_DRIVER_NOT_LOADED = 2,
OLS_DLL_DRIVER_NOT_FOUND = 3,
OLS_DLL_DRIVER_UNLOADED = 4,
OLS_DLL_DRIVER_NOT_LOADED_ON_NETWORK = 5,
OLS_DLL_UNKNOWN_ERROR = 9
}
// for WinRing0
public enum OlsDriverType
{
OLS_DRIVER_TYPE_UNKNOWN = 0,
OLS_DRIVER_TYPE_WIN_9X = 1,
OLS_DRIVER_TYPE_WIN_NT = 2,
OLS_DRIVER_TYPE_WIN_NT4 = 3, // Obsolete
OLS_DRIVER_TYPE_WIN_NT_X64 = 4,
OLS_DRIVER_TYPE_WIN_NT_IA64 = 5
}
// for WinRing0
public enum OlsErrorPci : uint
{
OLS_ERROR_PCI_BUS_NOT_EXIST = 0xE0000001,
OLS_ERROR_PCI_NO_DEVICE = 0xE0000002,
OLS_ERROR_PCI_WRITE_CONFIG = 0xE0000003,
OLS_ERROR_PCI_READ_CONFIG = 0xE0000004
}
// Bus Number, Device Number and Function Number to PCI Device Address
public uint PciBusDevFunc(uint bus, uint dev, uint func)
{
return ((bus&0xFF)<<8) | ((dev&0x1F)<<3) | (func&7);
}
// PCI Device Address to Bus Number
public uint PciGetBus(uint address)
{
return ((address>>8) & 0xFF);
}
// PCI Device Address to Device Number
public uint PciGetDev(uint address)
{
return ((address>>3) & 0x1F);
}
// PCI Device Address to Function Number
public uint PciGetFunc(uint address)
{
return (address&7);
}
[DllImport("kernel32")]
public extern static IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32", SetLastError = true)]
private static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = false)]
private static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName);
private IntPtr module = IntPtr.Zero;
private uint status = (uint)Status.NO_ERROR;
public Ols()
{
string fileName;
if (System.IntPtr.Size == 8)
{
fileName = dllNameX64;
}
else
{
fileName = dllName;
}
module = Ols.LoadLibrary(fileName);
if (module == IntPtr.Zero)
{
status = (uint)Status.DLL_NOT_FOUND;
}
else
{
GetDllStatus = (_GetDllStatus)GetDelegate("GetDllStatus", typeof(_GetDllStatus));
GetDllVersion = (_GetDllVersion)GetDelegate("GetDllVersion", typeof(_GetDllVersion));
GetDriverVersion = (_GetDriverVersion)GetDelegate("GetDriverVersion", typeof(_GetDriverVersion));
GetDriverType = (_GetDriverType)GetDelegate("GetDriverType", typeof(_GetDriverType));
InitializeOls = (_InitializeOls)GetDelegate("InitializeOls", typeof(_InitializeOls));
DeinitializeOls = (_DeinitializeOls)GetDelegate("DeinitializeOls", typeof(_DeinitializeOls));
IsCpuid = (_IsCpuid)GetDelegate("IsCpuid", typeof(_IsCpuid));
IsMsr = (_IsMsr)GetDelegate("IsMsr", typeof(_IsMsr));
IsTsc = (_IsTsc)GetDelegate("IsTsc", typeof(_IsTsc));
Hlt = (_Hlt)GetDelegate("Hlt", typeof(_Hlt));
HltTx = (_HltTx)GetDelegate("HltTx", typeof(_HltTx));
HltPx = (_HltPx)GetDelegate("HltPx", typeof(_HltPx));
Rdmsr = (_Rdmsr)GetDelegate("Rdmsr", typeof(_Rdmsr));
RdmsrTx = (_RdmsrTx)GetDelegate("RdmsrTx", typeof(_RdmsrTx));
RdmsrPx = (_RdmsrPx)GetDelegate("RdmsrPx", typeof(_RdmsrPx));
Wrmsr = (_Wrmsr)GetDelegate("Wrmsr", typeof(_Wrmsr));
WrmsrTx = (_WrmsrTx)GetDelegate("WrmsrTx", typeof(_WrmsrTx));
WrmsrPx = (_WrmsrPx)GetDelegate("WrmsrPx", typeof(_WrmsrPx));
Rdpmc = (_Rdpmc)GetDelegate("Rdpmc", typeof(_Rdpmc));
RdpmcTx = (_RdpmcTx)GetDelegate("RdpmcTx", typeof(_RdpmcTx));
RdpmcPx = (_RdpmcPx)GetDelegate("RdpmcPx", typeof(_RdpmcPx));
Cpuid = (_Cpuid)GetDelegate("Cpuid", typeof(_Cpuid));
CpuidTx = (_CpuidTx)GetDelegate("CpuidTx", typeof(_CpuidTx));
CpuidPx = (_CpuidPx)GetDelegate("CpuidPx", typeof(_CpuidPx));
Rdtsc = (_Rdtsc)GetDelegate("Rdtsc", typeof(_Rdtsc));
RdtscTx = (_RdtscTx)GetDelegate("RdtscTx", typeof(_RdtscTx));
RdtscPx = (_RdtscPx)GetDelegate("RdtscPx", typeof(_RdtscPx));
ReadIoPortByte = (_ReadIoPortByte)GetDelegate("ReadIoPortByte", typeof(_ReadIoPortByte));
ReadIoPortWord = (_ReadIoPortWord)GetDelegate("ReadIoPortWord", typeof(_ReadIoPortWord));
ReadIoPortDword = (_ReadIoPortDword)GetDelegate("ReadIoPortDword", typeof(_ReadIoPortDword));
ReadIoPortByteEx = (_ReadIoPortByteEx)GetDelegate("ReadIoPortByteEx", typeof(_ReadIoPortByteEx));
ReadIoPortWordEx = (_ReadIoPortWordEx)GetDelegate("ReadIoPortWordEx", typeof(_ReadIoPortWordEx));
ReadIoPortDwordEx = (_ReadIoPortDwordEx)GetDelegate("ReadIoPortDwordEx", typeof(_ReadIoPortDwordEx));
WriteIoPortByte = (_WriteIoPortByte)GetDelegate("WriteIoPortByte", typeof(_WriteIoPortByte));
WriteIoPortWord = (_WriteIoPortWord)GetDelegate("WriteIoPortWord", typeof(_WriteIoPortWord));
WriteIoPortDword = (_WriteIoPortDword)GetDelegate("WriteIoPortDword", typeof(_WriteIoPortDword));
WriteIoPortByteEx = (_WriteIoPortByteEx)GetDelegate("WriteIoPortByteEx", typeof(_WriteIoPortByteEx));
WriteIoPortWordEx = (_WriteIoPortWordEx)GetDelegate("WriteIoPortWordEx", typeof(_WriteIoPortWordEx));
WriteIoPortDwordEx = (_WriteIoPortDwordEx)GetDelegate("WriteIoPortDwordEx", typeof(_WriteIoPortDwordEx));
SetPciMaxBusIndex = (_SetPciMaxBusIndex)GetDelegate("SetPciMaxBusIndex", typeof(_SetPciMaxBusIndex));
ReadPciConfigByte = (_ReadPciConfigByte)GetDelegate("ReadPciConfigByte", typeof(_ReadPciConfigByte));
ReadPciConfigWord = (_ReadPciConfigWord)GetDelegate("ReadPciConfigWord", typeof(_ReadPciConfigWord));
ReadPciConfigDword = (_ReadPciConfigDword)GetDelegate("ReadPciConfigDword", typeof(_ReadPciConfigDword));
ReadPciConfigByteEx = (_ReadPciConfigByteEx)GetDelegate("ReadPciConfigByteEx", typeof(_ReadPciConfigByteEx));
ReadPciConfigWordEx = (_ReadPciConfigWordEx)GetDelegate("ReadPciConfigWordEx", typeof(_ReadPciConfigWordEx));
ReadPciConfigDwordEx = (_ReadPciConfigDwordEx)GetDelegate("ReadPciConfigDwordEx", typeof(_ReadPciConfigDwordEx));
WritePciConfigByte = (_WritePciConfigByte)GetDelegate("WritePciConfigByte", typeof(_WritePciConfigByte));
WritePciConfigWord = (_WritePciConfigWord)GetDelegate("WritePciConfigWord", typeof(_WritePciConfigWord));
WritePciConfigDword = (_WritePciConfigDword)GetDelegate("WritePciConfigDword", typeof(_WritePciConfigDword));
WritePciConfigByteEx = (_WritePciConfigByteEx)GetDelegate("WritePciConfigByteEx", typeof(_WritePciConfigByteEx));
WritePciConfigWordEx = (_WritePciConfigWordEx)GetDelegate("WritePciConfigWordEx", typeof(_WritePciConfigWordEx));
WritePciConfigDwordEx = (_WritePciConfigDwordEx)GetDelegate("WritePciConfigDwordEx", typeof(_WritePciConfigDwordEx));
FindPciDeviceById = (_FindPciDeviceById)GetDelegate("FindPciDeviceById", typeof(_FindPciDeviceById));
FindPciDeviceByClass = (_FindPciDeviceByClass)GetDelegate("FindPciDeviceByClass", typeof(_FindPciDeviceByClass));
#if _PHYSICAL_MEMORY_SUPPORT
ReadDmiMemory = (_ReadDmiMemory)GetDelegate("ReadDmiMemory", typeof(_ReadDmiMemory));
ReadPhysicalMemory = (_ReadPhysicalMemory)GetDelegate("ReadPhysicalMemory", typeof(_ReadPhysicalMemory));
WritePhysicalMemory = (_WritePhysicalMemory)GetDelegate("WritePhysicalMemory", typeof(_WritePhysicalMemory));
#endif
if (! (
GetDllStatus != null
&& GetDllVersion != null
&& GetDriverVersion != null
&& GetDriverType != null
&& InitializeOls != null
&& DeinitializeOls != null
&& IsCpuid != null
&& IsMsr != null
&& IsTsc != null
&& Hlt != null
&& HltTx != null
&& HltPx != null
&& Rdmsr != null
&& RdmsrTx != null
&& RdmsrPx != null
&& Wrmsr != null
&& WrmsrTx != null
&& WrmsrPx != null
&& Rdpmc != null
&& RdpmcTx != null
&& RdpmcPx != null
&& Cpuid != null
&& CpuidTx != null
&& CpuidPx != null
&& Rdtsc != null
&& RdtscTx != null
&& RdtscPx != null
&& ReadIoPortByte != null
&& ReadIoPortWord != null
&& ReadIoPortDword != null
&& ReadIoPortByteEx != null
&& ReadIoPortWordEx != null
&& ReadIoPortDwordEx != null
&& WriteIoPortByte != null
&& WriteIoPortWord != null
&& WriteIoPortDword != null
&& WriteIoPortByteEx != null
&& WriteIoPortWordEx != null
&& WriteIoPortDwordEx != null
&& SetPciMaxBusIndex != null
&& ReadPciConfigByte != null
&& ReadPciConfigWord != null
&& ReadPciConfigDword != null
&& ReadPciConfigByteEx != null
&& ReadPciConfigWordEx != null
&& ReadPciConfigDwordEx != null
&& WritePciConfigByte != null
&& WritePciConfigWord != null
&& WritePciConfigDword != null
&& WritePciConfigByteEx != null
&& WritePciConfigWordEx != null
&& WritePciConfigDwordEx != null
&& FindPciDeviceById != null
&& FindPciDeviceByClass != null
#if _PHYSICAL_MEMORY_SUPPORT
&& ReadDmiMemory != null
&& ReadPhysicalMemory != null
&& WritePhysicalMemory != null
#endif
))
{
status = (uint)Status.DLL_INCORRECT_VERSION;
}
if (InitializeOls() == 0)
{
status = (uint)Status.DLL_INITIALIZE_ERROR;
}
}
}
public uint GetStatus()
{
return status;
}
public void Dispose()
{
if (module != IntPtr.Zero)
{
DeinitializeOls();
Ols.FreeLibrary(module);
module = IntPtr.Zero;
}
}
public Delegate GetDelegate(string procName, Type delegateType)
{
IntPtr ptr = GetProcAddress(module, procName);
if (ptr != IntPtr.Zero)
{
Delegate d = Marshal.GetDelegateForFunctionPointer(ptr, delegateType);
return d;
}
int result = Marshal.GetHRForLastWin32Error();
throw Marshal.GetExceptionForHR(result);
}
//-----------------------------------------------------------------------------
// DLL Information
//-----------------------------------------------------------------------------
public delegate uint _GetDllStatus();
public delegate uint _GetDllVersion(ref byte major, ref byte minor, ref byte revision, ref byte release);
public delegate uint _GetDriverVersion(ref byte major, ref byte minor, ref byte revision, ref byte release);
public delegate uint _GetDriverType();
public delegate int _InitializeOls();
public delegate void _DeinitializeOls();
public _GetDllStatus GetDllStatus = null;
public _GetDriverType GetDriverType = null;
public _GetDllVersion GetDllVersion = null;
public _GetDriverVersion GetDriverVersion = null;
public _InitializeOls InitializeOls = null;
public _DeinitializeOls DeinitializeOls = null;
//-----------------------------------------------------------------------------
// CPU
//-----------------------------------------------------------------------------
public delegate int _IsCpuid();
public delegate int _IsMsr();
public delegate int _IsTsc();
public delegate int _Hlt();
public delegate int _HltTx(UIntPtr threadAffinityMask);
public delegate int _HltPx(UIntPtr processAffinityMask);
public delegate int _Rdmsr(uint index, ref uint eax, ref uint edx);
public delegate int _RdmsrTx(uint index, ref uint eax, ref uint edx, UIntPtr threadAffinityMask);
public delegate int _RdmsrPx(uint index, ref uint eax, ref uint edx, UIntPtr processAffinityMask);
public delegate int _Wrmsr(uint index, uint eax, uint edx);
public delegate int _WrmsrTx(uint index, uint eax, uint edx, UIntPtr threadAffinityMask);
public delegate int _WrmsrPx(uint index, uint eax, uint edx, UIntPtr processAffinityMask);
public delegate int _Rdpmc(uint index, ref uint eax, ref uint edx);
public delegate int _RdpmcTx(uint index, ref uint eax, ref uint edx, UIntPtr threadAffinityMask);
public delegate int _RdpmcPx(uint index, ref uint eax, ref uint edx, UIntPtr processAffinityMask);
public delegate int _Cpuid(uint index, ref uint eax, ref uint ebx, ref uint ecx, ref uint edx);
public delegate int _CpuidTx(uint index, ref uint eax, ref uint ebx, ref uint ecx, ref uint edx, UIntPtr threadAffinityMask);
public delegate int _CpuidPx(uint index, ref uint eax, ref uint ebx, ref uint ecx, ref uint edx, UIntPtr processAffinityMask);
public delegate int _Rdtsc(ref uint eax, ref uint edx);
public delegate int _RdtscTx(ref uint eax, ref uint edx, UIntPtr threadAffinityMask);
public delegate int _RdtscPx(ref uint eax, ref uint edx, UIntPtr processAffinityMask);
public _IsCpuid IsCpuid = null;
public _IsMsr IsMsr = null;
public _IsTsc IsTsc = null;
public _Hlt Hlt = null;
public _HltTx HltTx = null;
public _HltPx HltPx = null;
public _Rdmsr Rdmsr = null;
public _RdmsrTx RdmsrTx = null;
public _RdmsrPx RdmsrPx = null;
public _Wrmsr Wrmsr = null;
public _WrmsrTx WrmsrTx = null;
public _WrmsrPx WrmsrPx = null;
public _Rdpmc Rdpmc = null;
public _RdpmcTx RdpmcTx = null;
public _RdpmcPx RdpmcPx = null;
public _Cpuid Cpuid = null;
public _CpuidTx CpuidTx = null;
public _CpuidPx CpuidPx = null;
public _Rdtsc Rdtsc = null;
public _RdtscTx RdtscTx = null;
public _RdtscPx RdtscPx = null;
//-----------------------------------------------------------------------------
// I/O
//-----------------------------------------------------------------------------
public delegate byte _ReadIoPortByte(ushort port);
public delegate ushort _ReadIoPortWord(ushort port);
public delegate uint _ReadIoPortDword(ushort port);
public _ReadIoPortByte ReadIoPortByte;
public _ReadIoPortWord ReadIoPortWord;
public _ReadIoPortDword ReadIoPortDword;
public delegate int _ReadIoPortByteEx(ushort port, ref byte value);
public delegate int _ReadIoPortWordEx(ushort port, ref ushort value);
public delegate int _ReadIoPortDwordEx(ushort port, ref uint value);
public _ReadIoPortByteEx ReadIoPortByteEx;
public _ReadIoPortWordEx ReadIoPortWordEx;
public _ReadIoPortDwordEx ReadIoPortDwordEx;
public delegate void _WriteIoPortByte(ushort port, byte value);
public delegate void _WriteIoPortWord(ushort port, ushort value);
public delegate void _WriteIoPortDword(ushort port, uint value);
public _WriteIoPortByte WriteIoPortByte;
public _WriteIoPortWord WriteIoPortWord;
public _WriteIoPortDword WriteIoPortDword;
public delegate int _WriteIoPortByteEx(ushort port, byte value);
public delegate int _WriteIoPortWordEx(ushort port, ushort value);
public delegate int _WriteIoPortDwordEx(ushort port, uint value);
public _WriteIoPortByteEx WriteIoPortByteEx;
public _WriteIoPortWordEx WriteIoPortWordEx;
public _WriteIoPortDwordEx WriteIoPortDwordEx;
//-----------------------------------------------------------------------------
// PCI
//-----------------------------------------------------------------------------
public delegate void _SetPciMaxBusIndex(byte max);
public _SetPciMaxBusIndex SetPciMaxBusIndex;
public delegate byte _ReadPciConfigByte(uint pciAddress, byte regAddress);
public delegate ushort _ReadPciConfigWord(uint pciAddress, byte regAddress);
public delegate uint _ReadPciConfigDword(uint pciAddress, byte regAddress);
public _ReadPciConfigByte ReadPciConfigByte;
public _ReadPciConfigWord ReadPciConfigWord;
public _ReadPciConfigDword ReadPciConfigDword;
public delegate int _ReadPciConfigByteEx(uint pciAddress, uint regAddress, ref byte value);
public delegate int _ReadPciConfigWordEx(uint pciAddress, uint regAddress, ref ushort value);
public delegate int _ReadPciConfigDwordEx(uint pciAddress, uint regAddress, ref uint value);
public _ReadPciConfigByteEx ReadPciConfigByteEx;
public _ReadPciConfigWordEx ReadPciConfigWordEx;
public _ReadPciConfigDwordEx ReadPciConfigDwordEx;
public delegate void _WritePciConfigByte(uint pciAddress, byte regAddress, byte value);
public delegate void _WritePciConfigWord(uint pciAddress, byte regAddress, ushort value);
public delegate void _WritePciConfigDword(uint pciAddress, byte regAddress, uint value);
public _WritePciConfigByte WritePciConfigByte;
public _WritePciConfigWord WritePciConfigWord;
public _WritePciConfigDword WritePciConfigDword;
public delegate int _WritePciConfigByteEx(uint pciAddress, uint regAddress, byte value);
public delegate int _WritePciConfigWordEx(uint pciAddress, uint regAddress, ushort value);
public delegate int _WritePciConfigDwordEx(uint pciAddress, uint regAddress, uint value);
public _WritePciConfigByteEx WritePciConfigByteEx;
public _WritePciConfigWordEx WritePciConfigWordEx;
public _WritePciConfigDwordEx WritePciConfigDwordEx;
public delegate uint _FindPciDeviceById(ushort vendorId, ushort deviceId, byte index);
public delegate uint _FindPciDeviceByClass(byte baseClass, byte subClass, byte programIf, byte index);
public _FindPciDeviceById FindPciDeviceById;
public _FindPciDeviceByClass FindPciDeviceByClass;
//-----------------------------------------------------------------------------
// Physical Memory (unsafe)
//-----------------------------------------------------------------------------
#if _PHYSICAL_MEMORY_SUPPORT
public unsafe delegate uint _ReadDmiMemory(byte* buffer, uint count, uint unitSize);
public _ReadDmiMemory ReadDmiMemory;
public unsafe delegate uint _ReadPhysicalMemory(UIntPtr address, byte* buffer, uint count, uint unitSize);
public unsafe delegate uint _WritePhysicalMemory(UIntPtr address, byte* buffer, uint count, uint unitSize);
public _ReadPhysicalMemory ReadPhysicalMemory;
public _WritePhysicalMemory WritePhysicalMemory;
#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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
public class UseExpressionBodyForAccessorsTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider());
private IDictionary<OptionKey, object> UseExpressionBody =>
OptionsSet(
SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement),
SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement),
SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement));
private IDictionary<OptionKey, object> UseExpressionBodyIncludingPropertiesAndIndexers =>
OptionsSet(
SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement),
SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement),
SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement));
private IDictionary<OptionKey, object> UseBlockBodyIncludingPropertiesAndIndexers =>
OptionsSet(
SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement),
SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement),
SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement));
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo
{
get
{
[|return|] Bar();
}
}
}",
@"class C
{
int Foo
{
get => Bar();
}
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUpdatePropertyInsteadOfAccessor()
{
await TestInRegularAndScript1Async(
@"class C
{
int Foo
{
get
{
[|return|] Bar();
}
}
}",
@"class C
{
int Foo => Bar();
}", parameters: new TestParameters(options: UseExpressionBodyIncludingPropertiesAndIndexers));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOnIndexer1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int this[int i]
{
get
{
[|return|] Bar();
}
}
}",
@"class C
{
int this[int i]
{
get => Bar();
}
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUpdateIndexerIfIndexerAndAccessorCanBeUpdated()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i]
{
get
{
[|return|] Bar();
}
}
}",
@"class C
{
int this[int i] => Bar();
}", parameters: new TestParameters(options: UseExpressionBodyIncludingPropertiesAndIndexers));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOnSetter1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo
{
set
{
[|Bar|]();
}
}
}",
@"class C
{
int Foo
{
set => [|Bar|]();
}
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestMissingWithOnlySetter()
{
await TestMissingAsync(
@"class C
{
int Foo
{
set => [|Bar|]();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo
{
get
{
[|throw|] new NotImplementedException();
}
}
}",
@"class C
{
int Foo
{
get => throw new NotImplementedException();
}
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody4()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo
{
get
{
[|throw|] new NotImplementedException(); // comment
}
}
}",
@"class C
{
int Foo
{
get => throw new NotImplementedException(); // comment
}
}", ignoreTrivia: false, options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo
{
get [|=>|] Bar();
}
}",
@"class C
{
int Foo
{
get
{
return Bar();
}
}
}", options: UseBlockBodyIncludingPropertiesAndIndexers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBodyForSetter1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo
{
set [|=>|] Bar();
}
}",
@"class C
{
int Foo
{
set
{
Bar();
}
}
}", options: UseBlockBodyIncludingPropertiesAndIndexers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo
{
get [|=>|] throw new NotImplementedException();
}
}",
@"class C
{
int Foo
{
get
{
throw new NotImplementedException();
}
}
}", options: UseBlockBodyIncludingPropertiesAndIndexers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody4()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo
{
get [|=>|] throw new NotImplementedException(); // comment
}
}",
@"class C
{
int Foo
{
get
{
throw new NotImplementedException(); // comment
}
}
}", ignoreTrivia: false, options: UseBlockBodyIncludingPropertiesAndIndexers);
}
}
}
| |
#region Copyright (c) 2002-2005, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net)
/*
Copyright (c) 2002-2005, Bas Geertsema, Xih Solutions (http://www.xihsolutions.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 names of Bas Geertsema or Xih Solutions 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. */
#endregion
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.IO;
using System.Security.Cryptography;
using System.Globalization;
using XihSolutions.DotMSN.Core;
using XihSolutions.DotMSN.DataTransfer;
namespace XihSolutions.DotMSN
{
/// <summary>
/// Defines the type of MSNObject.
/// </summary>
public enum MSNObjectType
{
/// <summary>
/// Unknown msnobject type.
/// </summary>
Unknown = 0,
/// <summary>
/// Emotion icon.
/// </summary>
Emoticon = 2,
/// <summary>
/// User display image.
/// </summary>
UserDisplay = 3,
/// <summary>
/// Background image.
/// </summary>
Background = 5
}
/// <summary>
/// The MSNObject can hold an image, display, emoticon, etc.
/// </summary>
[Serializable()]
public class MSNObject
{
/// <summary>
/// </summary>
private string originalContext = null;
/// <summary>
/// </summary>
private string oldHash = "";
/// <summary>
/// </summary>
[NonSerialized]
private PersistentStream dataStream = null;
/// <summary>
/// </summary>
private string fileLocation = null;
/// <summary>
/// </summary>
private string creator;
/// <summary>
/// </summary>
private int size;
/// <summary>
/// </summary>
private MSNObjectType type;
/// <summary>
/// </summary>
private string location;
/// <summary>
/// </summary>
private string sha;
/// <summary>
/// The datastream to write to, or to read from
/// </summary>
protected PersistentStream DataStream
{
get { return dataStream; }
set
{
dataStream = value;
}
}
/// <summary>
/// The local contact list owner
/// </summary>
public string Creator
{
get { return creator; }
set { creator = value; UpdateInCollection(); }
}
/// <summary>
/// The original context string that was send by the remote contact
/// </summary>
public string OriginalContext
{
get { return originalContext; }
}
/// <summary>
/// The total data size
/// </summary>
public int Size
{
get { return size; }
set { size = value; UpdateInCollection(); }
}
/// <summary>
/// The type of MSN Object
/// </summary>
public MSNObjectType Type
{
get { return type; }
set { type = value; UpdateInCollection(); }
}
/// <summary>
/// The location of the object. This is a location on the hard-drive. Use relative paths. This is only a text string; na data is read in after setting this field. Use FileLocation for that purpose.
/// </summary>
public string Location
{
get { return location; }
set { location = value; UpdateInCollection(); }
}
/// <summary>
/// [Deprecated, use LoadFile()] Gets or sets the file location. When a file is set the file data is immediately read in memory to extract the filehash. It will retain in memory afterwards.
/// </summary>
public string FileLocation
{
get { return fileLocation; }
set
{
this.LoadFile(value);
fileLocation = value;
}
}
/// <summary>
/// Gets or sets the file location. When a file is set the file data is immediately read in memory to extract the filehash. It will retain in memory afterwards.
/// </summary>
/// <param name="fileName"></param>
public void LoadFile(string fileName)
{
if (this.fileLocation == fileName) return;
this.fileLocation = fileName;
this.location = Path.GetRandomFileName();
// close any current datastreams. One is always created in the constructor
if (dataStream != null)
dataStream.Close();
// and open a new stream
dataStream = new PersistentStream(new MemoryStream());
// copy the file
byte[] buffer = new byte[512];
Stream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
int cnt = 0;
while ((cnt = fileStream.Read(buffer, 0, 512)) > 0)
{
dataStream.Write(buffer, 0, cnt);
}
this.size = (int)dataStream.Length;
this.sha = GetStreamHash(dataStream);
UpdateInCollection();
}
/// <summary>
/// The SHA1 encrypted hash of the datastream.
/// </summary>
/// <remarks>
/// Usually the application programmer don't need to set this itself.
/// </remarks>
public string Sha
{
get { return sha; }
set { sha = value; UpdateInCollection(); }
}
/// <summary>
/// Updates the msn object in the global MSNObjectCatalog.
/// </summary>
public void UpdateInCollection()
{
if(oldHash.Length != 0)
MSNObjectCatalog.GetInstance().Remove(oldHash);
oldHash = Context;
MSNObjectCatalog.GetInstance().Add(oldHash, this);
}
/// <summary>
/// Calculates the hash of datastream.
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
protected string GetStreamHash(Stream stream)
{
stream.Seek(0, SeekOrigin.Begin);
// fet file hash
byte[] bytes=new byte[(int)stream.Length];
//put bytes into byte array
stream.Read(bytes,0, (int)stream.Length);
//create SHA1 object
HashAlgorithm hash = new SHA1Managed();
byte[] hashBytes = hash.ComputeHash(bytes);
return Convert.ToBase64String(hashBytes);
}
/// <summary>
/// Creates a MSNObject.
/// </summary>
public MSNObject()
{
DataStream = new PersistentStream(new MemoryStream());
}
/// <summary>
///
/// </summary>
private static Regex contextRe = new Regex("(?<Name>[^= ]+)=\"(?<Value>[^\"]+)\"");
/// <summary>
/// Parses a context send by the remote contact and set the corresponding class variables. Context input is assumed to be not base64 encoded.
/// </summary>
/// <param name="context"></param>
public virtual void ParseContext(string context)
{
ParseContext(context, false);
}
/// <summary>
/// Parses a context send by the remote contact and set the corresponding class variables.
/// </summary>
/// <param name="context"></param>
/// <param name="base64Encoded"></param>
public virtual void ParseContext(string context, bool base64Encoded)
{
originalContext = context;
if(base64Encoded)
context = System.Text.UTF8Encoding.UTF8.GetString(Convert.FromBase64String(context));
string xmlString = System.Web.HttpUtility.UrlDecode(context);
MatchCollection matches = contextRe.Matches(xmlString);
foreach(Match match in matches)
{
string name = match.Groups["Name"].Value.ToLower(System.Globalization.CultureInfo.InvariantCulture);
string val = match.Groups["Value"].Value;
switch(name)
{
case "creator": this.creator = val; break;
case "size" : this.size = int.Parse(val, System.Globalization.CultureInfo.InvariantCulture); break;
case "type" :
{
switch(val)
{
case "2": type = MSNObjectType.Emoticon; break;
case "3": type = MSNObjectType.UserDisplay; break;
case "5": type = MSNObjectType.Background; break;
}
break;
}
case "location":this.location= val; break;
case "sha1d" : this.sha = val; break;
}
}
}
/// <summary>
/// Constructs a MSN object based on a (memory)stream. The client programmer is responsible for inserting this object in the global msn object collection.
/// The stream must remain open during the whole life-length of the application.
/// </summary>
/// <param name="creator"></param>
/// <param name="inputStream"></param>
/// <param name="type"></param>
/// <param name="location"></param>
public MSNObject(string creator, Stream inputStream, MSNObjectType type, string location)
{
this.creator = creator;
this.size = (int)inputStream.Length;
this.type = type;
this.location = location;// + new Random().Next().ToString();
this.sha = GetStreamHash(inputStream);
this.DataStream = new PersistentStream(inputStream);
}
/// <summary>
/// Constructs a MSN object based on a physical file. The client programmer is responsible for inserting this object in the global msn object collection.
/// </summary>
/// <param name="creator"></param>
/// <param name="type"></param>
/// <param name="fileLocation"></param>
public MSNObject(string creator, string fileLocation, MSNObjectType type)
{
this.location = Path.GetFullPath(fileLocation).Replace(Path.GetPathRoot(fileLocation), "");
this.location += new Random().Next().ToString(CultureInfo.InvariantCulture);
this.fileLocation = fileLocation;
Stream stream = OpenStream();
this.creator = creator;
this.size = (int)stream.Length;
this.type = type;
this.sha = GetStreamHash(stream);
stream.Close();
}
/// <summary>
/// Returns the stream to read from. In case of an in-memory stream that stream is returned. In case of a filelocation
/// a stream to the file will be opened and returned. The stream is not guaranteed to positioned at the beginning of the stream.
/// </summary>
/// <returns></returns>
public virtual Stream OpenStream()
{
/*if(dataStream == null)
{
if(fileLocation != null && this.fileLocation.Length > 0)
dataStream = new PersistentStream(new FileStream(fileLocation, FileMode.Open, FileAccess.Read));
else
throw new DotMSNException("No memorystream or filestream available to open in a MSNObject context.");
}
else*/
dataStream.Open();
// otherwise it's a memorystream
return dataStream;
}
/// <summary>
/// Calculates the checksum for the entire MSN Object.
/// </summary>
/// <remarks>This value is used to uniquely identify a MSNObject.</remarks>
/// <returns></returns>
public string CalculateChecksum()
{
string checksum = "Creator"+Creator+"Size"+Size+"Type"+(int)this.Type+"Location"+Location+"FriendlyAAA=SHA1D"+Sha;
HashAlgorithm shaAlg = new SHA1Managed();
string baseEncChecksum = Convert.ToBase64String(shaAlg.ComputeHash(Encoding.ASCII.GetBytes(checksum)));
return baseEncChecksum;
}
/// <summary>
/// The context as an url-encoded xml string.
/// </summary>
public string Context
{
get { return GetEncodedString(); }
set { ParseContext(value); }
}
/// <summary>
/// The context as an xml string, not url-encoded.
/// </summary>
public string ContextPlain
{
get { return GetXmlString(); }
}
/// <summary>
/// Returns the xml string.
/// </summary>
/// <returns></returns>
protected virtual string GetXmlString()
{
return "<msnobj Creator=\""+Creator+"\" Size=\""+Size+"\" Type=\"" + (int)this.Type + "\" Location=\""+Location+"\" Friendly=\"AAA=\" SHA1D=\""+Sha+"\" SHA1C=\""+CalculateChecksum()+"\"/>";
}
/// <summary>
/// Returns the url-encoded xml string.
/// </summary>
/// <returns></returns>
protected virtual string GetEncodedString()
{
return System.Web.HttpUtility.UrlEncode(GetXmlString()).Replace("+", "%20");
}
}
/// <summary>
/// A collection of all available MSN objects. This class is implemented following the singleton pattern.
/// </summary>
/// <remarks>
/// In this collection all user display's, emoticons, etc for the entire application are stored.
/// This allows for easy retrieval of the corresponding msn object by passing in the encrypted hash.
/// Note: Use <see cref="GetInstance"/> to get a reference to the global MSNObjectCatalog object on which you can call methods.
/// </remarks>
[Serializable()]
public class MSNObjectCatalog : ICollection
{
/// <summary>
/// The single instance
/// </summary>
[NonSerialized]
private static MSNObjectCatalog instance = new MSNObjectCatalog();
/// <summary>
/// Collection of all msn objects
/// </summary>
private Hashtable objectCollection = new Hashtable();
/// <summary>
/// Returns the msn object with the supplied hash as checksum.
/// </summary>
/// <param name="hash"></param>
/// <returns></returns>
public MSNObject Get(string hash)
{
object msnObject = objectCollection[hash];
if(msnObject == null)
return null;
else
return (MSNObject)msnObject;
}
/// <summary>
/// Removes the msn object with the specified checksum from the collection.
/// </summary>
/// <param name="checksum"></param>
public void Remove(string checksum)
{
objectCollection.Remove(checksum);
}
/// <summary>
/// Removes the specified msn object from the collection.
/// </summary>
/// <param name="msnObject"></param>
public void Remove(MSNObject msnObject)
{
objectCollection.Remove(msnObject.CalculateChecksum());
}
/// <summary>
/// Adds the MSNObject (a user display, emoticon, etc) in the global collection.
/// </summary>
/// <param name="msnObject"></param>
public void Add(MSNObject msnObject)
{
string hash = msnObject.CalculateChecksum();
Add(hash, msnObject);
}
/// <summary>
/// Adds the MSNObject (a user display, emoticon, etc) in the global collection, with the specified checksum as index.
/// </summary>
/// <param name="checksum"></param>
/// <param name="msnObject"></param>
public void Add(string checksum, MSNObject msnObject)
{
objectCollection[checksum] = msnObject;
}
/// <summary>
/// Returns a reference to the global MSNObjectCatalog object.
/// </summary>
public static MSNObjectCatalog GetInstance()
{
return instance;
}
/// <summary>
/// Constructor.
/// </summary>
private MSNObjectCatalog()
{
}
#region ICollection Members
/// <summary>
/// Returns false,because ObjectCatalog is by default not synchronized.
/// </summary>
public bool IsSynchronized
{
get
{
return false;
}
}
/// <summary>
/// The number of objects in the catalog.
/// </summary>
public int Count
{
get
{
return objectCollection.Count;
}
}
/// <summary>
/// </summary>
/// <param name="array"></param>
/// <param name="index"></param>
public void CopyTo(Array array, int index)
{
objectCollection.CopyTo(array, index);
}
/// <summary>
/// </summary>
public object SyncRoot
{
get
{
return null;
}
}
#endregion
#region IEnumerable Members
/// <summary>
/// </summary>
/// <returns></returns>
public IEnumerator GetEnumerator()
{
return objectCollection.GetEnumerator();
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="CacheRequest.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Class that describes the data to be pre-fected in Automation
// element operations, and manange the current request.
//
// History:
// 02/05/2004 : BrendanM Ported to WCP
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Diagnostics;
using System.Windows.Automation;
using MS.Internal.Automation;
namespace System.Windows.Automation
{
/// <summary>
/// Specified type of reference to use when returning AutomationElements
/// </summary>
/// <remarks>
/// AutomationElementMode.Full is the default, and specified that returned AutomationElements
/// contain a full reference to the underlying UI.
///
/// AutomationElementMode.None specifies taht the returned AutomationElements have no
/// reference to the underlying UI, and contain only cached information.
///
/// Certain operations on AutomationElements, such as GetCurrentProperty
/// or SetFocus require a full reference; attempting to perform these on an
/// AutomationElement that has AutomationElementMode.None will result in an
/// InvalidOperationException being thrown.
///
/// Using AutomationElementMode.None can be more efficient when only properties are needed,
/// as it avoids the overhead involved in setting up full references.
/// </remarks>
#if (INTERNAL_COMPILE)
internal enum AutomationElementMode
#else
public enum AutomationElementMode
#endif
{
/// <summary>
/// Specifies that returned AutomationElements have no reference to the
/// underlying UI, and contain only cached information.
/// </summary>
None,
/// <summary>
/// Specifies that returned AutomationElements have a full reference to the
/// underlying UI.
/// </summary>
Full
}
// Implementation notes:
//
// CacheRequest is the user-facing class that is used to build up
// cache requests, using Add and the other properties. When activated,
// the data is gathered into a UiaCacheRequest instance, which is
// immutable - these are what the rest of UIA uses internally.
//
// The default cache request - which appears to be always at the bottom
// of the stack and which cannot be moved - is not actually part of the
// stack. Instead, current returns it whever the stack is empty.
/// <summary>
/// Class used to specify the properties and patterns that should be
/// prefetched by UIAutomation when returning AutomationElements.
/// </summary>
#if (INTERNAL_COMPILE)
internal sealed class CacheRequest
#else
public sealed class CacheRequest
#endif
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Create a new CacheRequest with default values.
/// </summary>
/// <remarks>
/// A Thread's current CacheRequest determins which properties,
/// patterns and relative elements - if any - are pre-fetched by
/// AutomationElement.
///
/// A default cache request works on the Control view of the tree,
/// and does not prefetch any properties or patterns.
///
/// Use .Push or .Activate to make the CacheRequest the current active
/// CacheRequest for the current thread.
/// </remarks>
public CacheRequest()
{
_instanceLock = new object();
_viewCondition = Automation.ControlViewCondition;
_scope = TreeScope.Element;
_properties = new ArrayList();
_patterns = new ArrayList();
_automationElementMode = AutomationElementMode.Full;
// We always want RuntimeID to be available...
_properties.Add(AutomationElement.RuntimeIdProperty);
_uiaCacheRequest = DefaultUiaCacheRequest;
}
// Private ctor used by Clone()
private CacheRequest( Condition viewCondition,
TreeScope scope,
ArrayList properties,
ArrayList patterns,
AutomationElementMode automationElementMode,
UiaCoreApi.UiaCacheRequest uiaCacheRequest)
{
_instanceLock = new object();
_viewCondition = viewCondition;
_scope = scope;
_properties = properties;
_patterns = patterns;
_automationElementMode = automationElementMode;
_uiaCacheRequest = uiaCacheRequest;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Push this CacheRequest onto this thread's stack of CacheRequests,
/// making it the current CacheRequest for this thread.
/// </summary>
/// <remarks>
/// Use Pop to remove this CacheRequest from the stack, making the previously
/// active CacheRequest active again. CacheRequests can be pushed multiple times,
/// and on multiple threads; but for each thread, must be popped off in the
/// same order as they were pushed.
///
/// A CacheRequest cannot be modified while it is pushed on any thread; attempting
/// to modify it will generate an InvalidOperationException.
/// </remarks>
public void Push()
{
// pushing multiple times is legal,
// and pushing on different threads is also legal,
// so no preconditions to check for here.
AutomationProperty[] propertyArray = (AutomationProperty[])_properties.ToArray(typeof(AutomationProperty));
AutomationPattern[] patternArray = (AutomationPattern[])_patterns.ToArray(typeof(AutomationPattern));
// _threadStack is thread local storage (TLS) based, so can be
// accessed outside of the lock.
if (_threadStack == null)
{
_threadStack = new Stack();
}
_threadStack.Push(this);
lock (_instanceLock)
{
_refCount++;
// Generate a new UiaCacheRequest
if (_uiaCacheRequest == null)
{
_uiaCacheRequest = new UiaCoreApi.UiaCacheRequest(_viewCondition, _scope, propertyArray, patternArray, _automationElementMode);
}
}
}
/// <summary>
/// Pop this CacheRequest from the current thread's stack of CacheRequests,
/// restoring the previously active CacheRequest.
/// </summary>
/// <remarks>
/// Only the currently active CacheRequest can be popped, attempting to pop
/// a CacheRequest which is not the current one will result in an InvalidOperation
/// Exception.
///
/// The CacheRequest stack initially contains a default CacheRequest, which
/// cannot be popped off the stack.
/// </remarks>
public void Pop()
{
// ensure that this is top of stack
// (no lock needed here, since this is per-thread state)
if (_threadStack == null || _threadStack.Count == 0 || _threadStack.Peek() != this)
{
throw new InvalidOperationException(SR.Get(SRID.CacheReqestCanOnlyPopTop));
}
_threadStack.Pop();
lock (_instanceLock)
{
_refCount--;
}
}
/// <summary>
/// Make this the currenly active CacheRequest.
/// </summary>
/// <remarks>
/// Returns an IDisposable which should be disposed
/// when finished using this CacheRequest to deactivate it.
/// This method is designed for use within a 'using' clause.
/// </remarks>
public IDisposable Activate()
{
Push();
return new CacheRequestActivation(this);
}
/// <summary>
/// Clone this CacheRequest
/// </summary>
/// <remarks>
/// The returned CacheRequest contains the same request information, but is not
/// pushed on the state of any thread.
/// </remarks>
public CacheRequest Clone()
{
// New copy contains only temp state, not any locking state (_refCount)
return new CacheRequest(_viewCondition, _scope, (ArrayList)_properties.Clone(), (ArrayList)_patterns.Clone(), _automationElementMode, _uiaCacheRequest);
}
/// <summary>
/// Add an AutomationProperty to this CacheRequest
/// </summary>
/// <param name="property">The identifier of the property to add to this CacheRequest</param>
public void Add(AutomationProperty property)
{
Misc.ValidateArgumentNonNull(property, "property");
lock (_instanceLock)
{
CheckAccess();
if (!_properties.Contains(property))
{
_properties.Add(property);
Invalidate();
}
}
}
/// <summary>
/// Add an AutomationPattern to this CacheRequest
/// </summary>
/// <param name="pattern">The identifier of the pattern to add to this CacheRequest</param>
public void Add(AutomationPattern pattern)
{
Misc.ValidateArgumentNonNull(pattern, "pattern");
lock (_instanceLock)
{
CheckAccess();
if (!_patterns.Contains(pattern))
{
_patterns.Add(pattern);
Invalidate();
}
}
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// Indicate which nodes should be pre-fetched
/// </summary>
/// <remarks>
/// At least one or more of of TreeScope.Element, TreeScope.Children or
/// TreeScope.Descendants must be specified.
///
/// TreeScope.Parent and TreeScope.Ancestors are not supported.
/// </remarks>
public TreeScope TreeScope
{
get
{
return _scope;
}
set
{
if (value == 0)
{
throw new ArgumentException(SR.Get(SRID.TreeScopeNeedAtLeastOne));
}
if ((value & ~(TreeScope.Element | TreeScope.Children | TreeScope.Descendants)) != 0)
{
throw new ArgumentException(SR.Get(SRID.TreeScopeElementChildrenDescendantsOnly));
}
lock (_instanceLock)
{
CheckAccess();
if (_scope != value)
{
_scope = value;
Invalidate();
}
}
}
}
/// <summary>
/// Indicates the view to use when prefetching relative nodes
/// </summary>
/// <remarks>Defaults to Automation.ControlViewCondition</remarks>
public Condition TreeFilter
{
get
{
return _viewCondition;
}
set
{
Misc.ValidateArgumentNonNull(value, "TreeFilter");
lock (_instanceLock)
{
CheckAccess();
if (_viewCondition != value)
{
_viewCondition = value;
Invalidate();
}
}
}
}
/// <summary>
/// Specifies whether returned AutomationElements should contain
/// full references to the underlying UI, or only cached information.
/// </summary>
public AutomationElementMode AutomationElementMode
{
get
{
return _automationElementMode;
}
set
{
lock (_instanceLock)
{
CheckAccess();
if (_automationElementMode != value)
{
_automationElementMode = value;
Invalidate();
}
}
}
}
/// <summary>
/// Return the most recent CacheRequest which has been activated
/// by teh calling thread.
/// </summary>
public static CacheRequest Current
{
get
{
if ( _threadStack == null || _threadStack.Count == 0 )
return DefaultCacheRequest;
return (CacheRequest)_threadStack.Peek();
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
internal static UiaCoreApi.UiaCacheRequest DefaultUiaCacheRequest
{
get
{
if(_defaultUiaCacheRequest == null)
{
_defaultUiaCacheRequest = new UiaCoreApi.UiaCacheRequest(Automation.ControlViewCondition, TreeScope.Element, new AutomationProperty[] { AutomationElement.RuntimeIdProperty }, new AutomationPattern[] { }, AutomationElementMode.Full);
}
return _defaultUiaCacheRequest;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
internal UiaCoreApi.UiaCacheRequest GetUiaCacheRequest()
{
if (_uiaCacheRequest == null)
{
AutomationProperty[] propertiesArray = (AutomationProperty[])_properties.ToArray(typeof(AutomationProperty));
AutomationPattern[] patternsArray = (AutomationPattern[])_patterns.ToArray(typeof(AutomationPattern));
lock (_instanceLock)
{
_uiaCacheRequest = new UiaCoreApi.UiaCacheRequest(_viewCondition, _scope, propertiesArray, patternsArray, _automationElementMode);
}
}
return _uiaCacheRequest;
}
static internal UiaCoreApi.UiaCacheRequest CurrentUiaCacheRequest
{
get
{
// No need to lock here, since this only uses thread state,
// and the UiaCacheRequests are generated within a lock in Push.
CacheRequest current = Current;
return current._uiaCacheRequest;
}
}
#endregion Internal Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
// Ensure that this CacheRequest isn't currently in use
// Must be called within a lock(_instanceLock) to ensure
// thread consistency
void CheckAccess()
{
// Make sure this isn't being used by any thread's
// CacheRequest stacks by using a refcount:
// (Also check for defaultCacheRequest explicitly, since it
// is never explicitly added to the stack)
if (_refCount != 0 || this == DefaultCacheRequest)
{
throw new InvalidOperationException(SR.Get(SRID.CacheReqestCantModifyWhileActive));
}
}
// Called when state changes - sets _uiaCacheRequest to null
// to ensure that a clean one is generated next time Push is called
void Invalidate()
{
_uiaCacheRequest = null;
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
//--- Instance state ---
// Current mutable state...
Condition _viewCondition;
TreeScope _scope;
ArrayList _properties;
ArrayList _patterns;
AutomationElementMode _automationElementMode;
// When we Push, the current state is bundled into this, which is
// immutable. This is what the underlying requesting mechanism uses
UiaCoreApi.UiaCacheRequest _uiaCacheRequest;
// Used to track whether this instance is in use - inc'd on Push,
// dec'd on Pop...
int _refCount = 0;
// Used to lock on this instance...
object _instanceLock = null;
//--- Per-Thread state ---
// The stack of CacheRequests for this thread. Note that these need to be inited
// on-demand, as static initialization does not work with [ThreadStatic] members -
// it only applies to the first thread. Treat null as being the same as a stack with
// just DefaultCacheRequest on it.
[ThreadStatic]
private static Stack _threadStack;
//--- Global/Static state ---
internal static readonly CacheRequest DefaultCacheRequest = new CacheRequest();
internal static UiaCoreApi.UiaCacheRequest _defaultUiaCacheRequest;
#endregion Private Fields
}
//------------------------------------------------------
//
// Related utility classe
//
//------------------------------------------------------
// Helper class returned by Access() - a using() block
// will call Dispose() on this when it goes out of scope.
internal class CacheRequestActivation : IDisposable
{
internal CacheRequestActivation(CacheRequest request)
{
_request = request;
}
public void Dispose()
{
Debug.Assert( _request != null );
if( _request != null )
{
_request.Pop();
_request = null;
}
}
// No finalizer - usually Dispose is used with a finalizer,
// but in this case, IDisposable is being used to manage scoping,
// not ensure that resources are freed.
private CacheRequest _request;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ApplicationGatewaysOperations operations.
/// </summary>
public partial interface IApplicationGatewaysOperations
{
/// <summary>
/// The delete applicationgateway operation deletes the specified
/// applicationgateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the applicationgateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The delete applicationgateway operation deletes the specified
/// applicationgateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the applicationgateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Get applicationgateway operation retreives information about
/// the specified applicationgateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the applicationgateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ApplicationGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Put ApplicationGateway operation creates/updates a
/// ApplicationGateway
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the ApplicationGateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete ApplicationGateway
/// operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ApplicationGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Put ApplicationGateway operation creates/updates a
/// ApplicationGateway
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the ApplicationGateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete ApplicationGateway
/// operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ApplicationGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The List ApplicationGateway opertion retrieves all the
/// applicationgateways in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The List applicationgateway opertion retrieves all the
/// applicationgateways in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Start ApplicationGateway operation starts application
/// gatewayin the specified resource group through Network resource
/// provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> StartWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Start ApplicationGateway operation starts application
/// gatewayin the specified resource group through Network resource
/// provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginStartWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The STOP ApplicationGateway operation stops application gatewayin
/// the specified resource group through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> StopWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The STOP ApplicationGateway operation stops application gatewayin
/// the specified resource group through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginStopWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The List ApplicationGateway opertion retrieves all the
/// applicationgateways in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The List applicationgateway opertion retrieves all the
/// applicationgateways in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.